file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface WETH9 {
function balanceOf(address a) external view returns (uint);
}
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeApprove: approve failed'
);
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::safeTransfer: transfer failed'
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
'TransferHelper::transferFrom: transferFrom failed'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper::safeTransferETH: ETH transfer failed');
}
}
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/libs/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/libs/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/libs/INonfungiblePositionManager.sol
pragma solidity ^0.8.0;
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
interface ILPManager
{
function increaseLiquidityCurrentRange(
uint256 tokenId,
uint256 amountAdd0,
address address1,
uint256 amountAdd1,
address address2
)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
}
pragma solidity ^0.8.0;
/**
* SAFEMATH LIBRARY
*/
library SafeMath {
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
function 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);
}
}
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
interface IERC20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
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);
}
abstract contract Auth {
address internal owner;
mapping (address => bool) internal authorizations;
constructor(address _owner) {
owner = _owner;
authorizations[_owner] = true;
}
/**
* Function modifier to require caller to be contract owner
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "!OWNER"); _;
}
/**
* Function modifier to require caller to be authorized
*/
modifier authorized() {
require(isAuthorized(msg.sender), "!AUTHORIZED"); _;
}
/**
* Authorize address. Owner only
*/
function authorize(address adr) public onlyOwner {
authorizations[adr] = true;
}
/**
* Remove address' authorization. Owner only
*/
function unauthorize(address adr) public onlyOwner {
authorizations[adr] = false;
}
/**
* Check if address is owner
*/
function isOwner(address account) public view returns (bool) {
return account == owner;
}
/**
* Return address' authorization status
*/
function isAuthorized(address adr) public view returns (bool) {
return authorizations[adr];
}
/**
* Transfer ownership to new address. Caller must be owner. Leaves old owner authorized
*/
function transferOwnership(address payable adr) public onlyOwner {
owner = adr;
authorizations[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
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 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 abicoder v2;
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
/// @title Router token swapping functionality
/// @notice Functions for swapping tokens via Uniswap V3
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @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);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
interface IUniswapRouter is ISwapRouter {
function refundETH() external payable;
function WETH9() external returns (address token);
}
/**
* @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);
}
contract Pill is IERC20, Auth, IERC721Receiver {
using SafeMath for uint256;
uint256 public constant MASK = type(uint128).max;
address public WETH = 0xae13d989daC2f0dEbFf460aC112a837C89BAa7cd;
address DEAD = 0x000000000000000000000000000000000000dEaD;
address ZERO = 0x0000000000000000000000000000000000000000;
address DEAD_NON_CHECKSUM = 0x000000000000000000000000000000000000dEaD;
uint256 MAX_INT = 2**256 - 1;
string constant _name = "$PILL";
string constant _symbol = "$PILL";
uint8 constant _decimals = 18;
/// @notice Represents the deposit of an NFT
struct Deposit {
address owner;
uint128 liquidity;
address token0;
address token1;
}
mapping(uint256 => Deposit) public deposits;
uint256 public totalSupply;
uint256 public _maxTxAmount = MAX_INT; // no limitation
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) public mintableAdmins;
mapping (address => bool) isFeeExempt;
mapping (address => bool) isTxLimitExempt;
uint256 liquidityFee = 300; // 3%
uint256 buybackFee = 200; // 2%
uint256 marketingFee = 300; // 3%
uint256 totalFee = 800;
uint256 feeDenominator = 10000;
address public autoLiquidityReceiver;
address public marketingFeeReceiver;
uint256 targetLiquidity = 25;
uint256 targetLiquidityDenominator = 100;
IUniswapRouter public uniswapRouter;
INonfungiblePositionManager public nonfungiblePositionManager;
IERC20 public myWETH;
ILPManager public lpManager;
address public poolAddress;
uint24 public swapFee = 3000;
uint256 public tokenId; // for liquidity
uint256 public launchedAt;
uint256 public launchedAtTimestamp;
uint256 buybackMultiplierNumerator = 200;
uint256 buybackMultiplierDenominator = 100;
uint256 buybackMultiplierTriggeredAt;
uint256 buybackMultiplierLength = 30 minutes;
bool public autoBuybackEnabled = false;
mapping (address => bool) buyBacker;
uint256 autoBuybackCap;
uint256 autoBuybackAccumulator;
uint256 autoBuybackAmount;
uint256 autoBuybackBlockPeriod;
uint256 autoBuybackBlockLast;
bool public swapEnabled = true;
uint256 public swapThreshold = 100 * (10**_decimals); // 100 tokens;
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
modifier onlyMintableAdmins() {
require(mintableAdmins[msg.sender], "You are not admin!"); _;
}
constructor (
address _uniswapRouter,
INonfungiblePositionManager _nonfungiblePositionManager,
address _lpManager
) Auth(msg.sender) {
uniswapRouter = IUniswapRouter(_uniswapRouter);
myWETH = IERC20(uniswapRouter.WETH9());
lpManager = ILPManager(_lpManager);
nonfungiblePositionManager = INonfungiblePositionManager(_nonfungiblePositionManager);
_allowances[address(this)][address(uniswapRouter)] = MAX_INT;
WETH = uniswapRouter.WETH9();
isFeeExempt[msg.sender] = true;
isFeeExempt[_lpManager] = true;
isFeeExempt[address(_nonfungiblePositionManager)] = true;
isFeeExempt[_uniswapRouter] = true;
isTxLimitExempt[msg.sender] = true;
buyBacker[msg.sender] = true;
autoLiquidityReceiver = msg.sender;
marketingFeeReceiver = msg.sender;
approve(_uniswapRouter, MAX_INT);
}
receive() external payable { }
function decimals() external pure override returns (uint8) { return _decimals; }
function symbol() external pure override returns (string memory) { return _symbol; }
function name() external pure override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner; }
modifier onlyBuybacker() { require(buyBacker[msg.sender] == true, ""); _; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function setRouter(IUniswapRouter _uniswapRouter) external onlyOwner {
uniswapRouter = _uniswapRouter;
}
function setPositionManager(INonfungiblePositionManager _nonfungiblePositionManager) external onlyOwner {
nonfungiblePositionManager = _nonfungiblePositionManager;
_allowances[address(this)][address(_nonfungiblePositionManager)] = MAX_INT;
}
function setPoolAddress(address _poolAddress) external onlyOwner {
poolAddress = _poolAddress;
_allowances[address(this)][address(_poolAddress)] = MAX_INT;
}
function setSwapFee(uint24 _swapFee) external onlyOwner {
swapFee = _swapFee;
}
function setTokenId(uint256 _tokenId) external onlyOwner {
tokenId = _tokenId;
}
function setAdmin(address usr, bool isAdmin) external onlyOwner {
mintableAdmins[usr] = isAdmin;
}
function setLPManager(address _lpManager) external onlyOwner {
lpManager = ILPManager(_lpManager);
}
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, MAX_INT);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _transferFrom(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != MAX_INT){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
}
return _transferFrom(sender, recipient, amount);
}
function _transferFrom(address sender, address recipient, uint256 amount) internal returns (bool) {
if(inSwap){ return _basicTransfer(sender, recipient, amount); }
checkTxLimit(sender, amount);
if(shouldTakeFee(sender) && shouldTakeFee(recipient) && shouldSwapBack()){ swapBack(); }
if(shouldTakeFee(sender) && shouldTakeFee(recipient) && shouldAutoBuyback()){ triggerAutoBuyback(); }
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
uint256 amountReceived = (shouldTakeFee(sender) && shouldTakeFee(recipient)) ? takeFee(sender, recipient, amount) : amount;
_balances[recipient] = _balances[recipient].add(amountReceived);
emit Transfer(sender, recipient, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function checkTxLimit(address sender, uint256 amount) internal view {
require(amount <= _maxTxAmount || isTxLimitExempt[sender], "TX Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function getTotalFee(bool selling) public view returns (uint256) {
if(launchedAt + 1 >= block.number){ return feeDenominator.sub(1); }
if(selling){ return getMultipliedFee(); }
return totalFee;
}
function getMultipliedFee() public view returns (uint256) {
if (launchedAtTimestamp + 1 days > block.timestamp) {
return totalFee.mul(18000).div(feeDenominator);
} else if (buybackMultiplierTriggeredAt.add(buybackMultiplierLength) > block.timestamp) {
uint256 remainingTime = buybackMultiplierTriggeredAt.add(buybackMultiplierLength).sub(block.timestamp);
uint256 feeIncrease = totalFee.mul(buybackMultiplierNumerator).div(buybackMultiplierDenominator).sub(totalFee);
return totalFee.add(feeIncrease.mul(remainingTime).div(buybackMultiplierLength));
}
return totalFee;
}
function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) {
uint256 feeAmount = amount.mul(getTotalFee(receiver == poolAddress)).div(feeDenominator);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != poolAddress && msg.sender != address(nonfungiblePositionManager) && msg.sender != address(uniswapRouter)
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function swapBack() internal swapping {
uint256 dynamicLiquidityFee = isOverLiquified(targetLiquidity, targetLiquidityDenominator) ? 0 : liquidityFee;
uint256 amountToLiquify = swapThreshold.mul(dynamicLiquidityFee).div(totalFee).div(2);
uint256 amountToSwap = swapThreshold.sub(amountToLiquify);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uint256 balanceBefore = myWETH.balanceOf(address(this));
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
path[0],
path[1],
swapFee,
address(this),
block.timestamp,
amountToSwap,
0,
0
);
uniswapRouter.exactInputSingle{ value: msg.value }(params);
uint256 amountWETH = myWETH.balanceOf(address(this)).sub(balanceBefore);
uint256 totalWETHFee = totalFee.sub(dynamicLiquidityFee.div(2));
uint256 amountWETHLiquidity = amountWETH.mul(dynamicLiquidityFee).div(totalWETHFee).div(2);
uint256 amountWETHMarketing = amountWETH.mul(marketingFee).div(totalWETHFee);
TransferHelper.safeTransfer(WETH, marketingFeeReceiver, amountWETHMarketing);
TransferHelper.safeApprove(address(this), address(lpManager), amountToLiquify);
TransferHelper.safeApprove(WETH, address(lpManager), amountWETHLiquidity);
if(amountToLiquify > 0){
emit AutoLiquify(amountWETHLiquidity, amountToLiquify,balanceBefore ,dynamicLiquidityFee,amountWETHMarketing);
lpManager.increaseLiquidityCurrentRange(
tokenId,
amountToLiquify,
address(this),
amountWETHLiquidity,
WETH
);
}
}
function shouldAutoBuyback() internal view returns (bool) {
return msg.sender != poolAddress
&& !inSwap
&& autoBuybackEnabled
&& autoBuybackBlockLast + autoBuybackBlockPeriod <= block.number // After N blocks from last buyback
&& address(this).balance >= autoBuybackAmount;
}
function triggerZeusBuyback(uint256 amount, bool triggerBuybackMultiplier) external authorized {
buyTokens(amount, DEAD);
if(triggerBuybackMultiplier){
buybackMultiplierTriggeredAt = block.timestamp;
emit BuybackMultiplierActive(buybackMultiplierLength);
}
}
function clearBuybackMultiplier() external authorized {
buybackMultiplierTriggeredAt = 0;
}
function triggerAutoBuyback() internal {
buyTokens(autoBuybackAmount, DEAD);
autoBuybackBlockLast = block.number;
autoBuybackAccumulator = autoBuybackAccumulator.add(autoBuybackAmount);
if(autoBuybackAccumulator > autoBuybackCap){ autoBuybackEnabled = false; }
}
function buyTokens(uint256 amount, address to) internal swapping {
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = address(this);
ISwapRouter.ExactInputSingleParams memory params = ISwapRouter.ExactInputSingleParams(
WETH,
address(this),
swapFee,
to,
block.timestamp,
amount,
0,
0 // sqrtPriceLimitX96
);
uniswapRouter.exactInputSingle{ value: msg.value }(params);
uniswapRouter.refundETH();
// refund leftover ETH to user
(bool success,) = msg.sender.call{ value: address(this).balance }("");
require(success, "refund failed");
}
function mint(address usr, uint wad) external onlyMintableAdmins {
_balances[usr] = _balances[usr].add(wad);
totalSupply = totalSupply.add(wad);
emit Transfer(address(0), usr, wad);
}
function setAutoBuybackSettings(bool _enabled, uint256 _cap, uint256 _amount, uint256 _period) external authorized {
autoBuybackEnabled = _enabled;
autoBuybackCap = _cap;
autoBuybackAccumulator = 0;
autoBuybackAmount = _amount;
autoBuybackBlockPeriod = _period;
autoBuybackBlockLast = block.number;
}
function setBuybackMultiplierSettings(uint256 numerator, uint256 denominator, uint256 length) external authorized {
require(numerator / denominator <= 2 && numerator > denominator);
buybackMultiplierNumerator = numerator;
buybackMultiplierDenominator = denominator;
buybackMultiplierLength = length;
}
function launched() internal view returns (bool) {
return launchedAt != 0;
}
function launch() public authorized {
require(launchedAt == 0, "Already launched boi");
launchedAt = block.number;
launchedAtTimestamp = block.timestamp;
}
function setTxLimit(uint256 amount) external authorized {
require(amount >= totalSupply / 1000);
_maxTxAmount = amount;
}
function setIsFeeExempt(address holder, bool exempt) external authorized {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external authorized {
isTxLimitExempt[holder] = exempt;
}
function setFees(uint256 _liquidityFee, uint256 _buybackFee, uint256 _marketingFee, uint256 _feeDenominator) external authorized {
liquidityFee = _liquidityFee;
buybackFee = _buybackFee;
marketingFee = _marketingFee;
totalFee = _liquidityFee.add(_buybackFee).add(_marketingFee);
feeDenominator = _feeDenominator;
require(totalFee < feeDenominator/4);
}
function setFeeReceivers(address _autoLiquidityReceiver, address _marketingFeeReceiver) external authorized {
autoLiquidityReceiver = _autoLiquidityReceiver;
marketingFeeReceiver = _marketingFeeReceiver;
}
function setSwapBackSettings(bool _enabled, uint256 _amount) external authorized {
swapEnabled = _enabled;
swapThreshold = _amount;
}
function setTargetLiquidity(uint256 _target, uint256 _denominator) external authorized {
targetLiquidity = _target;
targetLiquidityDenominator = _denominator;
}
function getCirculatingSupply() public view returns (uint256) {
return totalSupply.sub(balanceOf(DEAD)).sub(balanceOf(ZERO));
}
function getLiquidityBacking(uint256 accuracy) public view returns (uint256) {
return accuracy.mul(balanceOf(poolAddress).mul(2)).div(getCirculatingSupply());
}
function isOverLiquified(uint256 target, uint256 accuracy) public view returns (bool) {
return getLiquidityBacking(accuracy) > target;
}
event AutoLiquify(uint256 amountWETH, uint256 amountBOG,uint256 amountBOG2,uint256 amountBOG3,uint256 amountBOG4);
event BuybackMultiplierActive(uint256 duration);
// Implementing `onERC721Received` so this contract can receive custody of erc721 tokens
function onERC721Received(
address operator,
address,
uint256 _tokenId,
bytes calldata
) external override returns (bytes4) {
// get position information
_createDeposit(operator, _tokenId);
return this.onERC721Received.selector;
}
function _createDeposit(address owner, uint256 _tokenId) internal {
(, , address token0, address token1, , , , uint128 liquidity, , , , ) =
nonfungiblePositionManager.positions(_tokenId);
// set the owner and data for position
// operator is msg.sender
deposits[_tokenId] = Deposit({owner: owner, liquidity: liquidity, token0: token0, token1: token1});
}
}
|
Collects up to a maximum amount of fees owed to a specific position to the recipient params tokenId The ID of the NFT for which tokens are being collected, recipient The account that should receive the tokens, amount0Max The maximum amount of token0 to collect, amount1Max The maximum amount of token1 to collect return amount0 The amount of fees collected in token0 return amount1 The amount of fees collected in token1 Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens must be collected first. tokenId The ID of the token that is being burned
|
{
function increaseLiquidityCurrentRange(
uint256 tokenId,
uint256 amountAdd0,
address address1,
uint256 amountAdd1,
address address2
)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
}
| 14,803,236 |
./full_match/5/0xcc65Ea1d651ee8ACA6B8a0ba140221032aB73380/sources/lotto.sol
|
Calculates the winning ticket number based on the ending block hash, current ticket ID, block timestamp, block base fee, and remaining gas. return winningTicket The winning ticket number. The winning ticket number is calculated by hashing the packed encoding of the following: - The block hash of the block with the specified `_endingBlock` number. - The current ticket ID, which is the total number of tickets that have been sold so far. - The block timestamp of the current block. - The block base fee of the current block. - The remaining gas available in the current block. The resulting hash is then converted to a uint256 and reduced modulo the current ticket ID to obtain a number in the range [0, current ticket ID)./ Get the block hash for the ending block Revert if the block hash is 0 Hash the packed encoding of the block hash, current ticket ID, block timestamp, block base fee, and remaining gas
|
function _calculateWinningTicket()
internal
view
virtual
returns (uint256 winningTicket)
{
bytes32 bHash = blockhash(_endingBlock);
require(bHash != 0, "wait a few confirmations");
winningTicket =
uint256(
keccak256(
abi.encodePacked(
bHash,
currentTicketId(),
block.basefee,
gasleft()
)
)
) %
currentTicketId();
}
| 7,084,984 |
./full_match/42/0x0303582606A1E6bc3b5de7A71016F3C739ec83e9/sources/cache/solpp-generated-contracts/lib/ABDKMath64x64.sol
|
Calculate x y rounding down. Revert on overflow. x signed 64.64-bit fixed point number y signed 64.64-bit fixed point number return signed 64.64-bit fixed point number/
|
function mul(int128 x, int128 y) internal pure returns (int128) {
int256 result = (int256(x) * y) >> 64;
require(result >= MIN_64x64 && result <= MAX_64x64, "115");
return int128(result);
}
| 16,218,269 |
pragma solidity 0.6.12;
/**
* @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);
}
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev 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);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier
* available, which can be aplied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
}
interface IRewardsDistributionRecipient {
function notifyRewardAmount(address _rewardToken, uint256 reward) external;
}
interface IWrappedERC20 {
function wrap(address _to, uint _amount) external;
function unwrap(address _to, uint _amount) external;
}
// A multistakingreward contract that allows stakers to staking a single token and recieve various reward tokens.
// Forked from the Uniswap staking reward contract at https://etherscan.io/address/0x7FBa4B8Dc5E7616e59622806932DBea72537A56b#code
// with the following changes:
// - Expand from single reward token to a list of reward tokens
// - allow governance to rescue unclaimed tokens
contract MultiStakingRewards is IRewardsDistributionRecipient, ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/* ========== STRUCTS ========== */
// Info of each reward pool.
struct RewardPool {
IERC20 rewardToken; // Address of reward token.
uint256 periodFinish; // timestamp of when this reward pool finishes distribution
uint256 rewardRate; // amount of rewards distributed per unit of time
uint256 rewardsDuration; // duration of distribution
uint256 lastUpdateTime; // timestamp of when reward info was last updated
uint256 rewardPerTokenStored; // current rewards per token based on total rewards and total staked
mapping(address => uint256) userRewardPerTokenPaid; // amount of rewards per token already paided out to user
mapping(address => uint256) rewards; // amount of rewards user has earned
bool isActive; // mark if the pool is active
}
/* ========== STATE VARIABLES ========== */
address public rewardsDistribution;
address public governance;
IERC20 public stakingToken;
IWrappedERC20 public wStakingToken; // wrapped stakingToken is used to reward stakers with more stakingToken
uint256 public totalSupply;
mapping(address => uint256) public balances;
mapping(address => RewardPool) public rewardPools; // reward token to reward pool mapping
address[] public activeRewardPools; // list of reward tokens that are distributing rewards
/* ========== CONSTRUCTOR ========== */
constructor(address _stakingToken, address _wStakingToken, address _rewardsDistribution) public {
stakingToken = IERC20(_stakingToken);
wStakingToken = IWrappedERC20(_wStakingToken);
rewardsDistribution = _rewardsDistribution;
governance = msg.sender;
}
/* ========== VIEWS ========== */
function activeRewardPoolsLength() external view returns (uint256) {
return activeRewardPools.length;
}
function lastTimeRewardApplicable(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return Math.min(block.timestamp, pool.periodFinish);
}
function rewardPerToken(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
if (totalSupply == 0) {
return pool.rewardPerTokenStored;
}
return
pool.rewardPerTokenStored.add(
lastTimeRewardApplicable(_rewardToken).sub(pool.lastUpdateTime).mul(pool.rewardRate).mul(1e18).div(totalSupply)
);
}
function earned(address _rewardToken, address _account) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return balances[_account].mul(rewardPerToken(_rewardToken).sub(pool.userRewardPerTokenPaid[_account])).div(1e18).add(pool.rewards[_account]);
}
function getRewardForDuration(address _rewardToken) external view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.rewardRate.mul(pool.rewardsDuration);
}
function periodFinish(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.periodFinish;
}
function rewardRate(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.rewardRate;
}
function rewardsDuration(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.rewardsDuration;
}
function lastUpdateTime(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.lastUpdateTime;
}
function rewardPerTokenStored(address _rewardToken) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.rewardPerTokenStored;
}
function userRewardPerTokenPaid(address _rewardToken, address _account) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.userRewardPerTokenPaid[_account];
}
function rewards(address _rewardToken, address _account) public view returns (uint256) {
RewardPool storage pool = rewardPools[_rewardToken];
return pool.rewards[_account];
}
/* ========== MUTATIVE FUNCTIONS ========== */
function stake(uint256 amount) external nonReentrant updateActiveRewards(msg.sender) {
require(amount > 0, "Cannot stake 0");
totalSupply = totalSupply.add(amount);
balances[msg.sender] = balances[msg.sender].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
}
function withdraw(uint256 amount) public nonReentrant updateActiveRewards(msg.sender) {
require(amount > 0, "Cannot withdraw 0");
totalSupply = totalSupply.sub(amount);
balances[msg.sender] = balances[msg.sender].sub(amount);
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function getReward(address _rewardToken) public nonReentrant updateReward(_rewardToken, msg.sender) {
_getReward(_rewardToken);
}
function getAllActiveRewards() public nonReentrant updateActiveRewards(msg.sender) {
for (uint i = 0; i < activeRewardPools.length; i++) {
_getReward(activeRewardPools[i]);
}
}
function _getReward(address _rewardToken) internal {
RewardPool storage pool = rewardPools[_rewardToken];
require(pool.isActive, "pool is inactive");
uint256 reward = pool.rewards[msg.sender];
if (reward > 0) {
pool.rewards[msg.sender] = 0;
// If reward token is wrapped version of staking token, auto unwrap into underlying to user
if (address(pool.rewardToken) == address(wStakingToken)) {
wStakingToken.unwrap(msg.sender, reward);
} else {
pool.rewardToken.safeTransfer(msg.sender, reward);
}
emit RewardPaid(address(pool.rewardToken), msg.sender, reward);
}
}
function exit() external {
withdraw(balances[msg.sender]);
getAllActiveRewards();
}
/* ========== RESTRICTED FUNCTIONS ========== */
function notifyRewardAmount(address _rewardToken, uint256 _amount) external override onlyRewardsDistribution updateReward(_rewardToken, address(0)) {
RewardPool storage pool = rewardPools[_rewardToken];
if (block.timestamp >= pool.periodFinish) {
pool.rewardRate = _amount.div(pool.rewardsDuration);
} else {
uint256 remaining = pool.periodFinish.sub(block.timestamp);
uint256 leftover = remaining.mul(pool.rewardRate);
pool.rewardRate = _amount.add(leftover).div(pool.rewardsDuration);
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint balance = pool.rewardToken.balanceOf(address(this));
require(pool.rewardRate <= balance.div(pool.rewardsDuration), "Provided reward too high");
pool.lastUpdateTime = block.timestamp;
pool.periodFinish = block.timestamp.add(pool.rewardsDuration);
emit RewardAdded(_rewardToken, _amount);
}
// Add new reward pool to list
// NOTE: DO NOT add same pool twice while active.
function addRewardPool(
address _rewardToken,
uint256 _rewardsDuration
)
public
onlyGov
{
rewardPools[_rewardToken] = RewardPool({
rewardToken: IERC20(_rewardToken),
periodFinish: 0,
rewardRate: 0,
rewardsDuration: _rewardsDuration,
lastUpdateTime: 0,
rewardPerTokenStored: 0,
isActive: true
});
activeRewardPools.push(_rewardToken);
}
// Remove pool from active list
function inactivateRewardPool(address _rewardToken) public onlyGov {
// find the index
uint indexToDelete = 0;
bool found = false;
for (uint i = 0; i < activeRewardPools.length; i++) {
if (activeRewardPools[i] == _rewardToken) {
indexToDelete = i;
found = true;
break;
}
}
require(found, "element not found");
_inactivateRewardPool(indexToDelete);
}
// In case the list gets so large and make iteration impossible
function inactivateRewardPoolByIndex(uint256 _index) public onlyGov {
_inactivateRewardPool(_index);
}
function _inactivateRewardPool(uint256 _index) internal {
RewardPool storage pool = rewardPools[activeRewardPools[_index]];
pool.isActive = false;
// we don't care about the ordering of the active reward pool array
// so we can just swap the element to delete with the last element
activeRewardPools[_index] = activeRewardPools[activeRewardPools.length - 1];
activeRewardPools.pop();
}
// Allow governance to rescue unclaimed inactive rewards
function rescue(address _rewardToken) public onlyGov {
require(_rewardToken != address(stakingToken), "Cannot withdraw staking token");
RewardPool storage pool = rewardPools[_rewardToken];
require(pool.isActive == false, "Cannot withdraw active reward token");
uint _balance = IERC20(_rewardToken).balanceOf(address(this));
IERC20(_rewardToken).safeTransfer(governance, _balance);
}
/* ========== RESTRICTED FUNCTIONS ========== */
function setRewardsDistribution(address _rewardsDistribution) external {
require(msg.sender == governance, "!governance");
rewardsDistribution = _rewardsDistribution;
}
function setGov(address _gov) external {
require(msg.sender == governance, "!governance");
governance = _gov;
}
/* ========== MODIFIERS ========== */
modifier updateActiveRewards(address _account) {
for (uint i = 0; i < activeRewardPools.length; i++) {
RewardPool storage pool = rewardPools[activeRewardPools[i]];
pool.rewardPerTokenStored = rewardPerToken(address(pool.rewardToken));
pool.lastUpdateTime = lastTimeRewardApplicable(address(pool.rewardToken));
if (_account != address(0)) {
pool.rewards[_account] = earned(address(pool.rewardToken), _account);
pool.userRewardPerTokenPaid[_account] = pool.rewardPerTokenStored;
}
}
_;
}
modifier updateReward(address _rewardToken, address _account) {
RewardPool storage pool = rewardPools[_rewardToken];
pool.rewardPerTokenStored = rewardPerToken(address(pool.rewardToken));
pool.lastUpdateTime = lastTimeRewardApplicable(address(pool.rewardToken));
if (_account != address(0)) {
pool.rewards[_account] = earned(address(pool.rewardToken), _account);
pool.userRewardPerTokenPaid[_account] = pool.rewardPerTokenStored;
}
_;
}
modifier onlyGov() {
require(msg.sender == governance, "!governance");
_;
}
modifier onlyRewardsDistribution() {
require(msg.sender == rewardsDistribution, "!rewardsDistribution");
_;
}
/* ========== EVENTS ========== */
event RewardAdded(address indexed rewardToken, uint256 amount);
event Staked(address indexed user, uint256 amount);
event Withdrawn(address indexed user, uint256 amount);
event RewardPaid(address indexed rewardToken, address indexed user, uint256 reward);
}
|
Allow governance to rescue unclaimed inactive rewards
|
function rescue(address _rewardToken) public onlyGov {
require(_rewardToken != address(stakingToken), "Cannot withdraw staking token");
RewardPool storage pool = rewardPools[_rewardToken];
require(pool.isActive == false, "Cannot withdraw active reward token");
uint _balance = IERC20(_rewardToken).balanceOf(address(this));
IERC20(_rewardToken).safeTransfer(governance, _balance);
}
| 6,982,265 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "./../interfaces/compound/Comptroller.sol";
import "./../interfaces/compound/CErc20.sol";
import "./../interfaces/erc20/Erc20.sol";
import "./IRouter.sol";
import "./../dex/Uniswap.sol";
import "./../math/SafeMath.sol";
import "./../math/SignedSafeMath.sol";
import "./../math/DSMath.sol";
contract CompoundRouter is IRouter, Uniswap {
Comptroller private _comptroller;
Erc20 private _underlyingAsset;
CErc20 private _cToken;
Erc20 private _compToken;
/// @dev Logging and debugging event
// event Log(string, uint256);
constructor(
address _comptrollerAddress,
address _underlyingAssetAddress,
address _cTokenAddress,
address _uniswapRouterAddress
) public Uniswap(_uniswapRouterAddress) {
_comptroller = Comptroller(_comptrollerAddress);
_underlyingAsset = Erc20(_underlyingAssetAddress);
_cToken = CErc20(_cTokenAddress);
address compTokenAddress = _comptroller.getCompAddress();
_compToken = Erc20(compTokenAddress);
_enterMarkets();
}
/// @dev Enter the Compound market to provide liquidity
function _enterMarkets() internal {
address[] memory cTokens = new address[](1);
cTokens[0] = address(_cToken);
uint256[] memory errors = _comptroller.enterMarkets(cTokens);
if (errors[0] != 0) {
revert("Comptroller.enterMarkets Error");
}
}
/// @dev Supply underlying asset to protocol
function _supplyUnderlying(uint256 _amount) internal {
_underlyingAsset.approve(address(_cToken), _amount);
uint256 mintError = _cToken.mint(_amount);
require(mintError == 0, "CErc20.mint Error");
// emit Log("Supplied", _amount);
}
/// @dev Redeem cTokens for underlying asset
function _redeemUnderlying(uint256 _amount) internal {
uint256 redeemError = _cToken.redeem(_amount);
require(redeemError == 0, "CErc20.redeem Error");
// emit Log("Redeemed", _amount);
}
/**
* @dev Get the current APY
*
* Rate = cToken.supplyRatePerBlock();
* ETH Mantissa = 1 * 10 ^ 18 (ETH has 18 decimal places)
* Blocks Per Day = 4 * 60 * 24 (based on 4 blocks occurring every minute)
* Days Per Year = 365
*
* APY in RAY units = ((((Rate / ETH Mantissa * Blocks Per Day + 1) ^ Days Per Year)) - 1)
* APY percentage in RAY units = ((((Rate / ETH Mantissa * Blocks Per Day + 1) ^ Days Per Year)) - 1) * 100
*/
function getCurrentAPY() external view override returns (uint256) {
uint256 supplyRate = _cToken.supplyRatePerBlock();
uint256 mantissa = 10**18;
uint256 blocksPerDay = 4 * 60 * 24; // 4 blocks per minute
uint256 daysPerYear = 365;
uint256 base =
DSMath.mul(DSMath.rdiv(supplyRate, mantissa), blocksPerDay);
base = DSMath.add(base, DSMath.RAY);
uint256 power = DSMath.rpow(base, daysPerYear);
uint256 apy = DSMath.sub(power, DSMath.RAY);
return apy;
}
function getUnderlyingAsset() external view override returns (address) {
return address(_underlyingAsset);
}
function getUnderlyingDecimals() external view override returns (uint256) {
return _underlyingAsset.decimals();
}
function deposit(uint256 _amount) external override {
// Caller must approve contract before calling this function
require(
_underlyingAsset.transferFrom(msg.sender, address(this), _amount),
"Transfer failed"
);
_supplyUnderlying(_amount);
emit Deposit(_amount);
}
function withdraw() external override {
uint256 balancecToken = _cToken.balanceOf(address(this));
_redeemUnderlying(balancecToken);
this.harvest();
uint256 balance = _underlyingAsset.balanceOf(address(this));
require(
_underlyingAsset.transfer(msg.sender, balance),
"Transfer failed"
);
emit Withdrawal(balance);
}
function harvest() external override {
_comptroller.claimComp(address(this));
uint256 amountIn = _compToken.balanceOf(address(this));
this.swapTokensAForTokensB(
address(_compToken),
address(_underlyingAsset),
amountIn
);
emit Harvest(amountIn);
}
}
|
Caller must approve contract before calling this function
|
function deposit(uint256 _amount) external override {
require(
_underlyingAsset.transferFrom(msg.sender, address(this), _amount),
"Transfer failed"
);
_supplyUnderlying(_amount);
emit Deposit(_amount);
}
| 6,477,980 |
/*
* Copyright 2018 ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/
pragma solidity ^0.5.0;
contract Crosschain {
uint256 constant private LENGTH_OF_LENGTH_FIELD = 4;
uint256 constant private LENGTH_OF_UINT32 = 4;
uint256 constant private LENGTH_OF_UINT256 = 0x20;
uint256 constant private LENGTH_OF_BYTES32 = 0x20;
uint256 constant private LENGTH_OF_ADDRESS = 20;
// Value to be passed ot the getInfo precompile.
uint32 constant private GET_INFO_CROSSCHAIN_TRANSACTION_TYPE = 0;
uint32 constant private GET_INFO_BLOCKCHAIN_ID = 1;
uint32 constant private GET_INFO_COORDINAITON_BLOCKHCAIN_ID = 2;
uint32 constant private GET_INFO_COORDINAITON_CONTRACT_ADDRESS = 3;
uint32 constant private GET_INFO_ORIGINATING_BLOCKCHAIN_ID = 4;
uint32 constant private GET_INFO_FROM_BLOCKCHAIN_ID = 5;
uint32 constant private GET_INFO_FROM_CONTRACT_ADDRESS = 6;
uint32 constant private GET_INFO_CROSSCHAIN_TRANSACTION_ID = 7;
/** Generic calling of functions across chains.
* Combined with abi.encodeWithSelector, allows to use Solidity function types and arbitrary arguments.
* @param encodedFunctionCall = abi.encodeWithSelector(function.selector, ...)
*/
function crosschainTransaction(uint256 sidechainId, address addr, bytes memory encodedFunctionCall) internal {
bytes memory dataBytes = abi.encode(sidechainId, addr, encodedFunctionCall);
// The "bytes" type has a 32 byte header containing the size in bytes of the actual data,
// which is transparent to Solidity, so the bytes.length property doesn't report it.
// But the assembly "call" instruction gets the underlying bytes of the "bytes" data type, so the length needs
// to be corrected.
// Also, as of Solidity 0.5.11 there is no sane way to convert a dynamic type to a static array.
// Therefore we hackishly compensate the "bytes" length and deal with it inside the precompile.
uint256 dataBytesRawLength = dataBytes.length + LENGTH_OF_LENGTH_FIELD;
// Note: the tuple being encoded contains a dynamic type itself, which changes its internal representation;
// but since it is abi.encoded in Solidity, it's transparent.
// The problem only appears when using the wrapping "bytes" in Assembly.
assembly {
// Read: https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
//call(gasLimit, to, value, inputOffset, inputSize, outputOffset, outputSize)
// SUBORDINATE_TRANSACTION_PRECOMPILE = 10. Inline assembler doesn't support constants.
if iszero(call(not(0), 10, 0, dataBytes, dataBytesRawLength, 0, 0)) {
revert(0, 0)
}
}
}
function crosschainViewUint256(uint256 sidechainId, address addr, bytes memory encodedFunctionCall) internal view returns (uint256) {
bytes memory dataBytes = abi.encode(sidechainId, addr, encodedFunctionCall);
// The "bytes" type has a 32 byte header containing the size in bytes of the actual data,
// which is transparent to Solidity, so the bytes.length property doesn't report it.
// But the assembly "call" instruction gets the underlying bytes of the "bytes" data type, so the length needs
// to be corrected.
// Also, as of Solidity 0.5.11 there is no sane way to convert a dynamic type to a static array.
// Therefore we hackishly compensate the "bytes" length and deal with it inside the precompile.
uint256 dataBytesRawLength = dataBytes.length + LENGTH_OF_LENGTH_FIELD;
// Note: the tuple being encoded contains a dynamic type itself, which changes its internal representation;
// but since it is abi.encoded in Solidity, it's transparent.
// The problem only appears when using the wrapping "bytes" in Assembly.
uint256[1] memory result;
uint256 resultLength = LENGTH_OF_UINT256;
assembly {
// Read: https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
// and
// https://www.reddit.com/r/ethdev/comments/7p8b86/it_is_possible_to_call_a_precompiled_contracts/
// staticcall(gasLimit, to, inputOffset, inputSize, outputOffset, outputSize)
// SUBORDINATE_VIEW_PRECOMPILE = 11. Inline assembler doesn't support constants.
if iszero(staticcall(not(0), 11, dataBytes, dataBytesRawLength, result, resultLength)) {
revert(0, 0)
}
}
return result[0];
}
/**
* Determine the type of crosschain transaction being executed.
*
* The return value will be one of:
* NON_CROSSCHAIN_TRANSACTION = 0
* ORIGINATING_TRANSACTION = 1
* SUBORDINATE_TRANSACTION = 2
* SUBORDINATE_VIEW = 3
* ORIGINATING_LOCKABLE_CONTRACT_DEPLOY = 4
* SUBORDINATE_LOCKABLE_CONTRACT_DEPLOY = 5
* SINGLECHAIN_LOCKABLE_CONTRACT_DEPLOY = 6
* UNLOCK_COMMIT_SIGNALLING_TRANSACTION = 7
* UNLOCK_IGNORE_SIGNALLING_TRANSACTION = 8
*
* @return the type of crosschain transaction.
*/
function crosschainGetInfoTransactionType() internal view returns (uint256) {
uint256 inputLength = LENGTH_OF_UINT256;
uint256[1] memory input;
input[0] = GET_INFO_CROSSCHAIN_TRANSACTION_TYPE;
uint256[1] memory result;
uint256 resultLength = LENGTH_OF_UINT256;
assembly {
// Read: https://medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4
// and
// https://www.reddit.com/r/ethdev/comments/7p8b86/it_is_possible_to_call_a_precompiled_contracts/
// staticcall(gasLimit, to, inputOffset, inputSize, outputOffset, outputSize)
// GET_INFO_PRECOMPILE = 120. Inline assembler doesn't support constants.
if iszero(staticcall(not(0), 120, input, inputLength, result, resultLength)) {
revert(0, 0)
}
}
return result[0];
}
/**
* Get information about the transaction currently executing.
*
* @return Blockchain ID of this blockchain.
*/
function crosschainGetInfoBlockchainId() internal view returns (uint256) {
return getInfoBlockchainId(GET_INFO_BLOCKCHAIN_ID);
}
/**
* Get information about the transaction currently executing.
*
* @return Blockchain ID of the Coordination Blockchain.
* 0x00 is returned it the current transaction is a Single Blockchain Lockable
* Contract Deploy.
*/
function crosschainGetInfoCoordinationBlockchainId() internal view returns (uint256) {
return getInfoBlockchainId(GET_INFO_COORDINAITON_BLOCKHCAIN_ID);
}
/**
* Get information about the transaction currently executing.
*
* @return Blockchain ID of the Originating Blockchain.
* 0x00 is returned it the current transaction is an Originating Transaction or a
* Single Blockchain Lockable Contract Deploy.
*/
function crosschainGetInfoOriginatingBlockchainId() internal view returns (uint256) {
return getInfoBlockchainId(GET_INFO_ORIGINATING_BLOCKCHAIN_ID);
}
/**
* Get information about the transaction currently executing.
*
* @return Blockchain ID of the blockchain from which this function was called.
* 0x00 is returned it the current transaction is an Originating Transaction or a
* Single Blockchain Lockable Contract Deploy.
*/
function crosschainGetInfoFromBlockchainId() internal view returns (uint256) {
return getInfoBlockchainId(GET_INFO_FROM_BLOCKCHAIN_ID);
}
/**
* Get information about the transaction currently executing.
*
* @return Crosschain Transaction Identifier.
* 0x00 is returned it the current transaction is a Single Blockchain Lockable
* Contract Deploy.
*/
function crosschainGetInfoCrosschainTransactionId() internal view returns (uint256) {
return getInfoBlockchainId(GET_INFO_CROSSCHAIN_TRANSACTION_ID);
}
function getInfoBlockchainId(uint256 _requestedId) private view returns (uint256) {
uint256 inputLength = LENGTH_OF_UINT256;
uint256[1] memory input;
input[0] = _requestedId;
uint256[1] memory result;
uint256 resultLength = LENGTH_OF_UINT256;
assembly {
// GET_INFO_PRECOMPILE = 120. Inline assembler doesn't support constants.
if iszero(staticcall(not(0), 120, input, inputLength, result, resultLength)) {
revert(0, 0)
}
}
return result[0];
}
/**
* Get information about the transaction currently executing.
*
* @return Crosschain Coordination Contract address.
* 0x00 is returned it the current transaction is a Single Blockchain Lockable
* Contract Deploy.
*/
function crosschainGetInfoCoordinationContractAddress() internal view returns (address) {
return getInfoAddress(GET_INFO_COORDINAITON_CONTRACT_ADDRESS);
}
/**
* Get information about the transaction currently executing.
*
* @return Address of contract from which this function was called.
* 0x00 is returned it the current transaction is an Originating Transaction or a
* Single Blockchain Lockable Contract Deploy.
*/
function crosschainGetInfoFromAddress() internal view returns (address) {
return getInfoAddress(GET_INFO_FROM_CONTRACT_ADDRESS);
}
function getInfoAddress(uint256 _requestedAddress) private view returns (address) {
uint256 inputLength = LENGTH_OF_UINT256;
uint256[1] memory input;
input[0] = _requestedAddress;
// The return type is an address. However, we need to specify that we want a whole
// Ethereum word copied or we will end up with 20 bytes of the address being masked off.
address[1] memory result;
uint256 resultLength = LENGTH_OF_UINT256;
assembly {
// GET_INFO_PRECOMPILE = 120. Inline assembler doesn't support constants.
if iszero(staticcall(not(0), 120, input, inputLength, result, resultLength)) {
revert(0, 0)
}
}
return result[0];
}
}
|
The "bytes" type has a 32 byte header containing the size in bytes of the actual data, which is transparent to Solidity, so the bytes.length property doesn't report it. But the assembly "call" instruction gets the underlying bytes of the "bytes" data type, so the length needs to be corrected. Also, as of Solidity 0.5.11 there is no sane way to convert a dynamic type to a static array. Therefore we hackishly compensate the "bytes" length and deal with it inside the precompile. Note: the tuple being encoded contains a dynamic type itself, which changes its internal representation; but since it is abi.encoded in Solidity, it's transparent. The problem only appears when using the wrapping "bytes" in Assembly. Read: https:medium.com/@rbkhmrcr/precompiles-solidity-e5d29bd428c4 and https:www.reddit.com/r/ethdev/comments/7p8b86/it_is_possible_to_call_a_precompiled_contracts/ staticcall(gasLimit, to, inputOffset, inputSize, outputOffset, outputSize) SUBORDINATE_VIEW_PRECOMPILE = 11. Inline assembler doesn't support constants.
|
function crosschainViewUint256(uint256 sidechainId, address addr, bytes memory encodedFunctionCall) internal view returns (uint256) {
bytes memory dataBytes = abi.encode(sidechainId, addr, encodedFunctionCall);
uint256 dataBytesRawLength = dataBytes.length + LENGTH_OF_LENGTH_FIELD;
uint256[1] memory result;
uint256 resultLength = LENGTH_OF_UINT256;
assembly {
if iszero(staticcall(not(0), 11, dataBytes, dataBytesRawLength, result, resultLength)) {
revert(0, 0)
}
}
return result[0];
}
| 12,837,007 |
./full_match/1/0x21c2F2e8462D1090ac33d5A65cc03afFB18bB504/sources/browser/contract.sol
|
Set an upgrade agent that handles/ Only a master can designate the next agent Upgrade has already begun for an agent Bad interface Make sure that token supplies match in source and target
|
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != address(0));
require(_msgSender() == upgradeMaster);
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
require(upgradeAgent.isUpgradeAgent());
require(upgradeAgent.originalSupply() == totalSupply());
emit UpgradeAgentSet(address(upgradeAgent));
}
| 9,662,247 |
./full_match/42/0x07776b0149e3F9079324c22b4079DB52f4ECeb49/sources/tests/price_Oracle.sol
|
produces the cumulative price using counterfactuals to save gas and avoid a call to sync. if time has elapsed since the last update on the pair, mock the accumulated price values subtraction overflow is desired addition overflow is desired counterfactual counterfactual
|
function currentCumulativePrices(
address pair
) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) {
blockTimestamp = currentBlockTimestamp();
price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast();
price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast();
(uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves();
if (blockTimestampLast != blockTimestamp) {
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed;
price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed;
}
}
| 9,582,241 |
./partial_match/421613/0xd6a6C208B677aa41a0a9365CdAC17dd14F933E63/sources/TestContract.sol
|
Getter function to retrieve the current value of `myNumber`
|
function getNumber() public view returns (uint256) {
return myNumber;
}
| 16,826,232 |
./full_match/43114/0x719440e4201c290d279a083EB25Fd77463809A0C/sources/contracts/protocol/Controller.sol
|
PRIVILEGED GOVERNANCE FUNCTION. Allows governance to remove a module _module Address of the module contract to remove/
|
function removeModule(address _module) external onlyInitialized onlyOwner {
require(isModule[_module], "Module does not exist");
modules = modules.remove(_module);
isModule[_module] = false;
emit ModuleRemoved(_module);
}
| 4,555,519 |
./partial_match/56/0x23979985d63c6d14F59B348De11f7200b469e967/sources/LoanTokenLogicWeth.sol
|
ensures authorized use of existing loan
|
function _borrow(
uint256 withdrawAmount,
address borrower,
address receiver,
internal
pausable(msg.sig)
settlesInterest
returns (ProtocolLike.LoanOpenData memory)
{
require(withdrawAmount != 0, "6");
require(msg.value == 0 || msg.value == collateralTokenSent, "7");
require(collateralTokenSent != 0 || loanId != 0, "8");
require(collateralTokenAddress != address(0) || msg.value != 0 || loanId != 0, "9");
require(loanId == 0 || msg.sender == borrower, "13");
if (collateralTokenAddress == address(0)) {
collateralTokenAddress = wethToken;
}
require(collateralTokenAddress != loanTokenAddress, "10");
address[4] memory sentAddresses;
uint256[5] memory sentAmounts;
sentAddresses[1] = borrower;
sentAddresses[2] = receiver;
withdrawAmount,
initialLoanDuration
);
return _borrowOrTrade(
loanId,
withdrawAmount,
collateralTokenAddress,
sentAddresses,
sentAmounts,
);
}
| 11,053,408 |
/**************************************************************************
* ____ _
* / ___| | | __ _ _ _ ___ _ __
* | | _____ | | / _` || | | | / _ \| '__|
* | |___|_____|| |___| (_| || |_| || __/| |
* \____| |_____|\__,_| \__, | \___||_|
* |___/
*
**************************************************************************
*
* The MIT License (MIT)
*
* Copyright (c) 2016-2019 Cyril Lapinte
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************
*
* Flatten Contract: UserRegistry
*
* Git Commit:
* https://github.com/c-layer/contracts/tree/43925ba24cc22f42d0ff7711d0e169e8c2a0e09f
*
**************************************************************************/
// File: contracts/interface/IUserRegistry.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title IUserRegistry
* @dev IUserRegistry interface
* @author Cyril Lapinte - <[email protected]>
**/
contract IUserRegistry {
event UserRegistered(uint256 indexed userId, address address_, uint256 validUntilTime);
event AddressAttached(uint256 indexed userId, address address_);
event AddressDetached(uint256 indexed userId, address address_);
event UserSuspended(uint256 indexed userId);
event UserRestored(uint256 indexed userId);
event UserValidity(uint256 indexed userId, uint256 validUntilTime);
event UserExtendedKey(uint256 indexed userId, uint256 key, uint256 value);
event UserExtendedKeys(uint256 indexed userId, uint256[] values);
event ExtendedKeysDefinition(uint256[] keys);
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external returns (bool);
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external returns (bool);
function attachManyAddressesExternal(uint256[] calldata _userIds, address[] calldata _addresses)
external returns (bool);
function detachManyAddressesExternal(address[] calldata _addresses)
external returns (bool);
function suspendManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function restoreManyUsersExternal(uint256[] calldata _userIds) external returns (bool);
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external returns (bool);
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external returns (bool);
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external returns (bool);
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external returns (bool);
function name() public view returns (string memory);
function currency() public view returns (bytes32);
function userCount() public view returns (uint256);
function userId(address _address) public view returns (uint256);
function validUserId(address _address) public view returns (uint256);
function validUser(address _address, uint256[] memory _keys)
public view returns (uint256, uint256[] memory);
function validity(uint256 _userId) public view returns (uint256, bool);
function extendedKeys() public view returns (uint256[] memory);
function extended(uint256 _userId, uint256 _key)
public view returns (uint256);
function manyExtended(uint256 _userId, uint256[] memory _key)
public view returns (uint256[] memory);
function isAddressValid(address _address) public view returns (bool);
function isValid(uint256 _userId) public view returns (bool);
function defineExtendedKeys(uint256[] memory _extendedKeys) public returns (bool);
function registerUser(address _address, uint256 _validUntilTime)
public returns (bool);
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public returns (bool);
function attachAddress(uint256 _userId, address _address) public returns (bool);
function detachAddress(address _address) public returns (bool);
function detachSelf() public returns (bool);
function detachSelfAddress(address _address) public returns (bool);
function suspendUser(uint256 _userId) public returns (bool);
function restoreUser(uint256 _userId) public returns (bool);
function updateUser(uint256 _userId, uint256 _validUntilTime, bool _suspended)
public returns (bool);
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public returns (bool);
function updateUserAllExtended(uint256 _userId, uint256[] memory _values)
public returns (bool);
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public returns (bool);
}
// File: contracts/util/governance/Ownable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: contracts/util/governance/Operable.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title Operable
* @dev The Operable contract enable the restrictions of operations to a set of operators
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* OP01: Message sender must be an operator
* OP02: Address must be an operator
* OP03: Address must not be an operator
*/
contract Operable is Ownable {
mapping (address => bool) private operators_;
/**
* @dev Throws if called by any account other than the operator
*/
modifier onlyOperator {
require(operators_[msg.sender], "OP01");
_;
}
/**
* @dev constructor
*/
constructor() public {
defineOperator("Owner", msg.sender);
}
/**
* @dev isOperator
* @param _address operator address
*/
function isOperator(address _address) public view returns (bool) {
return operators_[_address];
}
/**
* @dev removeOperator
* @param _address operator address
*/
function removeOperator(address _address) public onlyOwner {
require(operators_[_address], "OP02");
operators_[_address] = false;
emit OperatorRemoved(_address);
}
/**
* @dev defineOperator
* @param _role operator role
* @param _address operator address
*/
function defineOperator(string memory _role, address _address)
public onlyOwner
{
require(!operators_[_address], "OP03");
operators_[_address] = true;
emit OperatorDefined(_role, _address);
}
event OperatorRemoved(address address_);
event OperatorDefined(
string role,
address address_
);
}
// File: contracts/UserRegistry.sol
pragma solidity >=0.5.0 <0.6.0;
/**
* @title UserRegistry
* @dev UserRegistry contract
* Configure and manage users
* Extended may be used externaly to store data within a user context
*
* @author Cyril Lapinte - <[email protected]>
*
* Error messages
* UR01: UserId is invalid
* UR02: WalletOwner is already known
* UR03: Users length does not match with addresses
* UR04: WalletOwner is unknown
* UR05: Sender is not the wallet owner
* UR06: User is already suspended
* UR07: User is not suspended
* UR08: Extended keys must exists for values
*/
contract UserRegistry is IUserRegistry, Operable {
struct User {
uint256 validUntilTime;
bool suspended;
mapping(uint256 => uint256) extended;
}
uint256[] internal extendedKeys_ = [ 0, 1, 2 ];
mapping(uint256 => User) internal users;
mapping(address => uint256) internal walletOwners;
uint256 internal userCount_;
string internal name_;
bytes32 internal currency_;
/**
* @dev contructor
**/
constructor(
string memory _name,
bytes32 _currency,
address[] memory _addresses,
uint256 _validUntilTime) public
{
name_ = _name;
currency_ = _currency;
for (uint256 i = 0; i < _addresses.length; i++) {
registerUserPrivate(_addresses[i], _validUntilTime);
}
}
/**
* @dev register many users
*/
function registerManyUsersExternal(address[] calldata _addresses, uint256 _validUntilTime)
external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _addresses.length; i++) {
registerUserPrivate(_addresses[i], _validUntilTime);
}
return true;
}
/**
* @dev register many users
*/
function registerManyUsersFullExternal(
address[] calldata _addresses,
uint256 _validUntilTime,
uint256[] calldata _values) external onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
for (uint256 i = 0; i < _addresses.length; i++) {
registerUserPrivate(_addresses[i], _validUntilTime);
updateUserExtendedPrivate(userCount_, _values);
}
return true;
}
/**
* @dev attach many addresses to many users
*/
function attachManyAddressesExternal(
uint256[] calldata _userIds,
address[] calldata _addresses)
external onlyOperator returns (bool)
{
require(_addresses.length == _userIds.length, "UR03");
for (uint256 i = 0; i < _addresses.length; i++) {
attachAddress(_userIds[i], _addresses[i]);
}
return true;
}
/**
* @dev detach many addresses association between addresses and their respective users
*/
function detachManyAddressesExternal(address[] calldata _addresses)
external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _addresses.length; i++) {
detachAddressPrivate(_addresses[i]);
}
return true;
}
/**
* @dev suspend many users
*/
function suspendManyUsersExternal(uint256[] calldata _userIds)
external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
suspendUser(_userIds[i]);
}
return true;
}
/**
* @dev restore many users
*/
function restoreManyUsersExternal(uint256[] calldata _userIds)
external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
restoreUser(_userIds[i]);
}
return true;
}
/**
* @dev update many users
*/
function updateManyUsersExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended) external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUser(_userIds[i], _validUntilTime, _suspended);
}
return true;
}
/**
* @dev update many user extended informations
*/
function updateManyUsersExtendedExternal(
uint256[] calldata _userIds,
uint256 _key, uint256 _value) external onlyOperator returns (bool)
{
for (uint256 i = 0; i < _userIds.length; i++) {
updateUserExtended(_userIds[i], _key, _value);
}
return true;
}
/**
* @dev update many user all extended informations
*/
function updateManyUsersAllExtendedExternal(
uint256[] calldata _userIds,
uint256[] calldata _values) external onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
for (uint256 i = 0; i < _userIds.length; i++) {
updateUserExtendedPrivate(_userIds[i], _values);
}
return true;
}
/**
* @dev update many users full
*/
function updateManyUsersFullExternal(
uint256[] calldata _userIds,
uint256 _validUntilTime,
bool _suspended,
uint256[] calldata _values) external onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
for (uint256 i = 0; i < _userIds.length; i++) {
updateUser(_userIds[i], _validUntilTime, _suspended);
updateUserExtendedPrivate(_userIds[i], _values);
}
return true;
}
/**
* @dev user registry name
*/
function name() public view returns (string memory) {
return name_;
}
/**
* @dev user registry currency
*/
function currency() public view returns (bytes32) {
return currency_;
}
/**
* @dev number of user registered
*/
function userCount() public view returns (uint256) {
return userCount_;
}
/**
* @dev the userId associated to the provided address
*/
function userId(address _address) public view returns (uint256) {
return walletOwners[_address];
}
/**
* @dev the userId associated to the provided address if the user is valid
*/
function validUserId(address _address) public view returns (uint256) {
uint256 addressUserId = walletOwners[_address];
if (isValidPrivate(users[addressUserId])) {
return addressUserId;
}
return 0;
}
/**
* @dev the user associated to the provided address if the user is valid
*/
function validUser(address _address, uint256[] memory _keys) public view returns (uint256, uint256[] memory) {
uint256 addressUserId = walletOwners[_address];
if (isValidPrivate(users[addressUserId])) {
uint256[] memory values = new uint256[](_keys.length);
for (uint256 i=0; i < _keys.length; i++) {
values[i] = users[addressUserId].extended[_keys[i]];
}
return (addressUserId, values);
}
return (0, new uint256[](0));
}
/**
* @dev returns the time at which user validity ends
*/
function validity(uint256 _userId) public view returns (uint256, bool) {
User memory user = users[_userId];
return (user.validUntilTime, user.suspended);
}
/**
* @dev extended keys
*/
function extendedKeys() public view returns (uint256[] memory) {
return extendedKeys_;
}
/**
* @dev access to extended user data
*/
function extended(uint256 _userId, uint256 _key)
public view returns (uint256)
{
return users[_userId].extended[_key];
}
/**
* @dev access to extended user data
*/
function manyExtended(uint256 _userId, uint256[] memory _keys)
public view returns (uint256[] memory values)
{
values = new uint256[](_keys.length);
for (uint256 i=0; i < _keys.length; i++) {
values[i] = users[_userId].extended[_keys[i]];
}
}
/**
* @dev validity of the current user
*/
function isAddressValid(address _address) public view returns (bool) {
return isValidPrivate(users[walletOwners[_address]]);
}
/**
* @dev validity of the current user
*/
function isValid(uint256 _userId) public view returns (bool) {
return isValidPrivate(users[_userId]);
}
/**
* @dev define extended keys
*/
function defineExtendedKeys(uint256[] memory _extendedKeys)
public onlyOperator returns (bool)
{
extendedKeys_ = _extendedKeys;
emit ExtendedKeysDefinition(_extendedKeys);
return true;
}
/**
* @dev register a user
*/
function registerUser(address _address, uint256 _validUntilTime)
public onlyOperator returns (bool)
{
registerUserPrivate(_address, _validUntilTime);
return true;
}
/**
* @dev register a user full
*/
function registerUserFull(
address _address,
uint256 _validUntilTime,
uint256[] memory _values) public onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
registerUserPrivate(_address, _validUntilTime);
updateUserExtendedPrivate(userCount_, _values);
return true;
}
/**
* @dev attach an address with a user
*/
function attachAddress(uint256 _userId, address _address)
public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
require(walletOwners[_address] == 0, "UR02");
walletOwners[_address] = _userId;
emit AddressAttached(_userId, _address);
return true;
}
/**
* @dev detach the association between an address and its user
*/
function detachAddress(address _address)
public onlyOperator returns (bool)
{
detachAddressPrivate(_address);
return true;
}
/**
* @dev detach the association between an address and its user
*/
function detachSelf() public returns (bool) {
detachAddressPrivate(msg.sender);
return true;
}
/**
* @dev detach the association between an address and its user
*/
function detachSelfAddress(address _address)
public returns (bool)
{
require(
walletOwners[_address] == walletOwners[msg.sender],
"UR05");
detachAddressPrivate(_address);
return true;
}
/**
* @dev suspend a user
*/
function suspendUser(uint256 _userId)
public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
require(!users[_userId].suspended, "UR06");
users[_userId].suspended = true;
emit UserSuspended(_userId);
return true;
}
/**
* @dev restore a user
*/
function restoreUser(uint256 _userId)
public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
require(users[_userId].suspended, "UR07");
users[_userId].suspended = false;
emit UserRestored(_userId);
return true;
}
/**
* @dev update a user
*/
function updateUser(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended) public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
if (users[_userId].validUntilTime != _validUntilTime) {
users[_userId].validUntilTime = _validUntilTime;
emit UserValidity(_userId, _validUntilTime);
}
if (users[_userId].suspended != _suspended) {
users[_userId].suspended = _suspended;
if (_suspended) {
emit UserSuspended(_userId);
} else {
emit UserRestored(_userId);
}
}
return true;
}
/**
* @dev update user extended information
*/
function updateUserExtended(uint256 _userId, uint256 _key, uint256 _value)
public onlyOperator returns (bool)
{
require(_userId > 0 && _userId <= userCount_, "UR01");
users[_userId].extended[_key] = _value;
emit UserExtendedKey(_userId, _key, _value);
return true;
}
/**
* @dev update user all extended information
*/
function updateUserAllExtended(
uint256 _userId,
uint256[] memory _values) public onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
updateUserExtendedPrivate(_userId, _values);
return true;
}
/**
* @dev update a user full
*/
function updateUserFull(
uint256 _userId,
uint256 _validUntilTime,
bool _suspended,
uint256[] memory _values) public onlyOperator returns (bool)
{
require(_values.length <= extendedKeys_.length, "UR08");
updateUser(_userId, _validUntilTime, _suspended);
updateUserExtendedPrivate(_userId, _values);
return true;
}
/**
* @dev register a user private
*/
function registerUserPrivate(address _address, uint256 _validUntilTime)
private
{
require(walletOwners[_address] == 0, "UR03");
users[++userCount_] = User(_validUntilTime, false);
walletOwners[_address] = userCount_;
emit UserRegistered(userCount_, _address, _validUntilTime);
}
/**
* @dev update user extended private
*/
function updateUserExtendedPrivate(uint256 _userId, uint256[] memory _values)
private
{
require(_userId > 0 && _userId <= userCount_, "UR01");
for (uint256 i = 0; i < _values.length; i++) {
users[_userId].extended[extendedKeys_[i]] = _values[i];
}
emit UserExtendedKeys(_userId, _values);
}
/**
* @dev detach the association between an address and its user
*/
function detachAddressPrivate(address _address) private {
uint256 addressUserId = walletOwners[_address];
require(addressUserId != 0, "UR04");
emit AddressDetached(addressUserId, _address);
delete walletOwners[_address];
}
/**
* @dev validity of the current user
*/
function isValidPrivate(User storage user) private view returns (bool) {
// solhint-disable-next-line not-rely-on-time
return !user.suspended && user.validUntilTime > now;
}
}
|
detach the association between an address and its user/
|
function detachSelfAddress(address _address)
public returns (bool)
{
require(
walletOwners[_address] == walletOwners[msg.sender],
"UR05");
detachAddressPrivate(_address);
return true;
}
| 6,414,786 |
pragma solidity ^0.4.8;
// ----------------------------------------------------------------------------------------------
// Unique deposit contacts for customers to deposit ethers that are sent to different wallets
//
// Enjoy. (c) Bok Consulting Pty Ltd & Incent Rewards 2017. The MIT Licence.
// ----------------------------------------------------------------------------------------------
contract Config {
// Cannot receive funds before this date. DO NOT USE `now`
uint256 public constant DEPOSIT_DATE_FROM = 1491553792;
// Cannot receive funds after this date. DO NOT USE `now`
uint256 public constant DEPOSIT_DATE_TO = 1491553912;
// Incent account - 0.5%
uint256 public constant INCENT_RATE_PER_THOUSAND = 5;
address public incentAccount = 0x0020017ba4c67f76c76b1af8c41821ee54f37171;
// Fees - 0.5%
uint256 public constant FEE_RATE_PER_THOUSAND = 5;
address public constant feeAccount = 0x0036f6addb6d64684390f55a92f0f4988266901b;
// Client account - remainder of sent amount
address public constant clientAccount = 0x004e64833635cd1056b948b57286b7c91e62731c;
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() {
owner = msg.sender;
}
modifier onlyOwner {
if (msg.sender != owner) throw;
_;
}
function transferOwnership(address newOwner) onlyOwner {
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract CustomerDeposit {
uint256 public totalDeposit = 0;
CustomerDepositFactory public factory;
function CustomerDeposit(CustomerDepositFactory _factory) {
factory = _factory;
}
function () payable {
totalDeposit += msg.value;
factory.receiveDeposit.value(msg.value)(msg.sender);
}
}
contract CustomerDepositFactory is Owned, Config {
uint256 public totalDeposits = 0;
bool public fundingClosed = false;
CustomerDeposit[] public depositContracts;
mapping (address => bool) public isDepositContract;
modifier fundingPeriodActive() {
if (now < DEPOSIT_DATE_FROM || now > DEPOSIT_DATE_TO) throw;
_;
}
// NOTE: Remix does not handle indexed addresses correctly
event DepositContractCreated(address indexed depositContract, uint256 number);
event DepositReceived(address indexed depositOrigin, address indexed depositContract, uint _value);
event FundingClosed(bool fundingClosed);
function createDepositContracts(uint256 number) onlyOwner {
for (uint256 i = 0; i < number; i++) {
CustomerDeposit customerDeposit = new CustomerDeposit(this);
depositContracts.push(customerDeposit);
isDepositContract[customerDeposit] = true;
DepositContractCreated(customerDeposit, depositContracts.length);
}
}
function numberOfDepositContracts() constant returns (uint) {
return depositContracts.length;
}
function receiveDeposit(address depositOrigin) fundingPeriodActive payable {
// Can only receive ethers from deposit contracts created by this factory
if (!isDepositContract[msg.sender]) throw;
// Don't accept ethers from deposit contracts after the funding is closed
if (fundingClosed) throw;
// Record total deposits
totalDeposits += msg.value;
// Send amount to incent address
uint256 value1 = msg.value * INCENT_RATE_PER_THOUSAND / 1000;
if (!incentAccount.send(value1)) throw;
// Send fee to the fee address
uint256 value2 = msg.value * FEE_RATE_PER_THOUSAND / 1000;
if (!feeAccount.send(value2)) throw;
// Send the remainder to the client's wallet
uint256 value3 = msg.value - value1 - value2;
if (!clientAccount.send(value3)) throw;
DepositReceived(depositOrigin, msg.sender, msg.value);
}
// Set to true when funding is completed. No more more deposits will be accepted
function setFundingClosed(bool _fundingClosed) onlyOwner {
fundingClosed = _fundingClosed;
FundingClosed(fundingClosed);
}
// Prevent accidental sending of ethers to the factory
function () {
throw;
}
}
|
Set to true when funding is completed. No more more deposits will be accepted
|
function setFundingClosed(bool _fundingClosed) onlyOwner {
fundingClosed = _fundingClosed;
FundingClosed(fundingClosed);
}
| 14,075,220 |
./partial_match/1/0x7FEba38C9479d0efeE1e4338BF312c46317c17C9/sources/contracts/implementations/HeyMintERC1155ExtensionD.sol
|
Creates or updates a token based on the tokenId/ add the token id to the tokenIds array if it doesn't already exist
|
function upsertToken(TokenConfig memory _tokenConfig) external onlyOwner {
HeyMintStorage.State storage state = HeyMintStorage.state();
require(
_tokenConfig.maxSupply >=
state.data.totalSupply[_tokenConfig.tokenId],
"MAX_SUPPLY_LESS_THAN_TOTAL_SUPPLY"
);
require(
_tokenConfig.presaleMaxSupply >=
state.data.totalSupply[_tokenConfig.tokenId],
"MAX_SUPPLY_LESS_THAN_TOTAL_SUPPLY"
);
require(
_tokenConfig.publicSaleStartTime == 0 ||
_tokenConfig.publicSaleStartTime > block.timestamp,
"TIME_IN_PAST"
);
require(
_tokenConfig.publicSaleEndTime == 0 ||
_tokenConfig.publicSaleEndTime > block.timestamp,
"TIME_IN_PAST"
);
require(
_tokenConfig.presaleStartTime == 0 ||
_tokenConfig.presaleStartTime > block.timestamp,
"TIME_IN_PAST"
);
require(
_tokenConfig.presaleEndTime == 0 ||
_tokenConfig.presaleEndTime > block.timestamp,
"TIME_IN_PAST"
);
require(
!state.data.tokenMetadataFrozen[_tokenConfig.tokenId] &&
!state.data.allMetadataFrozen,
"ALL_METADATA_FROZEN"
);
require(
!state.data.tokenMetadataFrozen[_tokenConfig.tokenId] ||
keccak256(bytes(_tokenConfig.tokenUri)) ==
keccak256(bytes(state.tokens[_tokenConfig.tokenId].tokenUri)),
"METADATA_FROZEN"
);
require(
_tokenConfig.refundEndsAt >=
state.tokens[_tokenConfig.tokenId].refundEndsAt,
"REFUND_DURATION_CANNOT_BE_DECREASED"
);
require(
state.tokens[_tokenConfig.tokenId].refundPrice == 0 ||
state.tokens[_tokenConfig.tokenId].refundPrice ==
_tokenConfig.refundPrice,
"REFUND_PRICE_CANNOT_BE_CHANGED"
);
state.tokens[_tokenConfig.tokenId] = _tokenConfig;
for (uint256 i = 0; i < state.data.tokenIds.length; i++) {
if (state.data.tokenIds[i] == _tokenConfig.tokenId) {
return;
}
}
state.data.tokenIds.push(_tokenConfig.tokenId);
}
| 3,933,770 |
./full_match/8453/0xBDbD30aF7E3ecB6D88a75b2884BB0253E93D61F7/sources/contracts/TrustEventLog.sol
|
registerTrustEvent Event dispatchers will call this when it's time to register an event. This is usually done when a root key holder configures an event. This call assumes the message sender is a dispatcher. Key holders cannot call this method unless they will also act as the event dispatcher. trustId the trust to associate the event with eventHash the event hash to register description a small description of the event return the final event hash that needs to be used/ generate the counterfactual registration hash, this is to prevent other dispatchers from registering the same hash, ever. we will enable duplicate hashes from within a dispatcher, because that's up to the dispatcher to salt to prevent hash collisions. we want to tell the notary about this to prevent unauthorized event spam. this will revert if the trust owner hasn't approved it. make sure the hash isn't already registered invariant: make sure the event hasn't fired register the event the event is really bound to dispatchers, but we want to keep track of a trust ID for introspection emit the event
|
function registerTrustEvent(uint256 trustId, bytes32 eventHash, bytes32 description) external returns (bytes32) {
bytes32 finalHash = keccak256(abi.encode(msg.sender, eventHash));
INotary(notary).notarizeEventRegistration(msg.sender, trustId, finalHash, description);
require(address(0) == eventDispatchers[finalHash],
"DUPLICATE_REGISTRATION");
assert(!firedEvents[finalHash]);
eventDispatchers[finalHash] = msg.sender;
eventDescriptions[finalHash] = description;
trustEventRegistry[trustId].push(finalHash);
trustDispatcherEvents[trustId][msg.sender].push(finalHash);
emit trustEventRegistered(msg.sender, trustId, finalHash, description);
return finalHash;
}
| 11,558,944 |
./partial_match/1/0x00000000Ede6d8D217c60f93191C060747324bca/sources/node_modules/@aperture_finance/uni-v3-lib/src/TernaryLib.sol
|
Equivalent to the ternary operator: `condition ? a : b`
|
function ternary(bool condition, uint256 a, uint256 b) internal pure returns (uint256 res) {
assembly {
res := xor(b, mul(xor(a, b), condition))
}
}
| 15,622,005 |
// SPDX-License-Identifier: MIT
// Created by justin
pragma solidity 0.6.12;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./DigitalaxAccessControls.sol";
import "./garment/IDigitalaxGarmentNFT.sol";
/**
* @notice Primary sale auction contract for Digitalax NFTs
*/
contract DigitalaxAuction is Context, ReentrancyGuard {
using SafeMath for uint256;
using Address for address payable;
/// @notice Event emitted only on construction. To be used by indexers
event DigitalaxAuctionContractDeployed();
event PauseToggled(
bool isPaused
);
event AuctionCreated(
uint256 indexed garmentTokenId
);
event UpdateAuctionEndTime(
uint256 indexed garmentTokenId,
uint256 endTime
);
event UpdateAuctionStartTime(
uint256 indexed garmentTokenId,
uint256 startTime
);
event UpdateAuctionReservePrice(
uint256 indexed garmentTokenId,
uint256 reservePrice
);
event UpdateAccessControls(
address indexed accessControls
);
event UpdatePlatformFee(
uint256 platformFee
);
event UpdatePlatformFeeRecipient(
address payable platformFeeRecipient
);
event UpdateMinBidIncrement(
uint256 minBidIncrement
);
event UpdateBidWithdrawalLockTime(
uint256 bidWithdrawalLockTime
);
event BidPlaced(
uint256 indexed garmentTokenId,
address indexed bidder,
uint256 bid
);
event BidWithdrawn(
uint256 indexed garmentTokenId,
address indexed bidder,
uint256 bid
);
event BidRefunded(
address indexed bidder,
uint256 bid
);
event AuctionResulted(
uint256 indexed garmentTokenId,
address indexed winner,
uint256 winningBid
);
event AuctionCancelled(
uint256 indexed garmentTokenId
);
/// @notice Parameters of an auction
struct Auction {
uint256 reservePrice;
uint256 startTime;
uint256 endTime;
bool resulted;
}
/// @notice Information about the sender that placed a bit on an auction
struct HighestBid {
address payable bidder;
uint256 bid;
uint256 lastBidTime;
}
/// @notice Garment ERC721 Token ID -> highest bidder info (if a bid has been received)
mapping(uint256 => HighestBid) public highestBids;
/// @notice Garment ERC721 Token ID -> Auction Parameters
mapping(uint256 => Auction) public auctions;
/// @notice Garment ERC721 NFT - the only NFT that can be auctioned in this contract
IDigitalaxGarmentNFT public garmentNft;
// @notice responsible for enforcing admin access
DigitalaxAccessControls public accessControls;
/// @notice globally and across all auctions, the amount by which a bid has to increase
uint256 public minBidIncrement = 0.1 ether;
/// @notice global bid withdrawal lock time
uint256 public bidWithdrawalLockTime = 20 minutes;
/// @notice global platform fee, assumed to always be to 1 decimal place i.e. 120 = 12.0%
uint256 public platformFee = 120;
/// @notice where to send platform fee funds to
address payable public platformFeeRecipient;
/// @notice for switching off auction creations, bids and withdrawals
bool public isPaused;
modifier whenNotPaused() {
require(!isPaused, "Function is currently paused");
_;
}
constructor(
DigitalaxAccessControls _accessControls,
IDigitalaxGarmentNFT _garmentNft,
address payable _platformFeeRecipient
) public {
require(address(_accessControls) != address(0), "DigitalaxAuction: Invalid Access Controls");
require(address(_garmentNft) != address(0), "DigitalaxAuction: Invalid NFT");
require(_platformFeeRecipient != address(0), "DigitalaxAuction: Invalid Platform Fee Recipient");
accessControls = _accessControls;
garmentNft = _garmentNft;
platformFeeRecipient = _platformFeeRecipient;
emit DigitalaxAuctionContractDeployed();
}
/**
@notice Creates a new auction for a given garment
@dev Only the owner of a garment can create an auction and must have approved the contract
@dev In addition to owning the garment, the sender also has to have the MINTER role.
@dev End time for the auction must be in the future.
@param _garmentTokenId Token ID of the garment being auctioned
@param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher
@param _startTimestamp Unix epoch in seconds for the auction start time
@param _endTimestamp Unix epoch in seconds for the auction end time.
*/
function createAuction(
uint256 _garmentTokenId,
uint256 _reservePrice,
uint256 _startTimestamp,
uint256 _endTimestamp
) external whenNotPaused {
// Ensure caller has privileges
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxAuction.createAuction: Sender must have the minter role"
);
// Check owner of the token is the creator and approved
require(
garmentNft.ownerOf(_garmentTokenId) == _msgSender() && garmentNft.isApproved(_garmentTokenId, address(this)),
"DigitalaxAuction.createAuction: Not owner and or contract not approved"
);
_createAuction(
_garmentTokenId,
_reservePrice,
_startTimestamp,
_endTimestamp
);
}
/**
@notice Admin or smart contract can list approved Garments
@dev Sender must have admin or smart contract role
@dev Owner must have approved this contract for the garment or all garments they own
@dev End time for the auction must be in the future.
@param _garmentTokenId Token ID of the garment being auctioned
@param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher
@param _startTimestamp Unix epoch in seconds for the auction start time
@param _endTimestamp Unix epoch in seconds for the auction end time.
*/
function createAuctionOnBehalfOfOwner(
uint256 _garmentTokenId,
uint256 _reservePrice,
uint256 _startTimestamp,
uint256 _endTimestamp
) external {
// Ensure caller has privileges
require(
accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxAuction.createAuctionOnBehalfOfOwner: Sender must have admin or smart contract role"
);
require(
garmentNft.isApproved(_garmentTokenId, address(this)),
"DigitalaxAuction.createAuctionOnBehalfOfOwner: Cannot create an auction if you do not have approval"
);
_createAuction(
_garmentTokenId,
_reservePrice,
_startTimestamp,
_endTimestamp
);
}
/**
@notice Places a new bid, out bidding the existing bidder if found and criteria is reached
@dev Only callable when the auction is open
@dev Bids from smart contracts are prohibited to prevent griefing with always reverting receiver
@param _garmentTokenId Token ID of the garment being auctioned
*/
function placeBid(uint256 _garmentTokenId) external payable nonReentrant whenNotPaused {
require(_msgSender().isContract() == false, "DigitalaxAuction.placeBid: No contracts permitted");
// Check the auction to see if this is a valid bid
Auction storage auction = auctions[_garmentTokenId];
// Ensure auction is in flight
require(
_getNow() >= auction.startTime && _getNow() <= auction.endTime,
"DigitalaxAuction.placeBid: Bidding outside of the auction window"
);
uint256 bidAmount = msg.value;
// Ensure bid adheres to outbid increment and threshold
HighestBid storage highestBid = highestBids[_garmentTokenId];
uint256 minBidRequired = highestBid.bid.add(minBidIncrement);
require(bidAmount >= minBidRequired, "DigitalaxAuction.placeBid: Failed to outbid highest bidder");
// Refund existing top bidder if found
if (highestBid.bidder != address(0)) {
_refundHighestBidder(highestBid.bidder, highestBid.bid);
}
// assign top bidder and bid time
highestBid.bidder = _msgSender();
highestBid.bid = bidAmount;
highestBid.lastBidTime = _getNow();
emit BidPlaced(_garmentTokenId, _msgSender(), bidAmount);
}
/**
@notice Given a sender who has the highest bid on a garment, allows them to withdraw their bid
@dev Only callable by the existing top bidder
@param _garmentTokenId Token ID of the garment being auctioned
*/
function withdrawBid(uint256 _garmentTokenId) external nonReentrant whenNotPaused {
HighestBid storage highestBid = highestBids[_garmentTokenId];
// Ensure highest bidder is the caller
require(highestBid.bidder == _msgSender(), "DigitalaxAuction.withdrawBid: You are not the highest bidder");
// Check withdrawal after delay time
require(
_getNow() >= highestBid.lastBidTime.add(bidWithdrawalLockTime),
"DigitalaxAuction.withdrawBid: Cannot withdraw until lock time has passed"
);
require(_getNow() < auctions[_garmentTokenId].endTime, "DigitalaxAuction.withdrawBid: Past auction end");
uint256 previousBid = highestBid.bid;
// Clean up the existing top bid
delete highestBids[_garmentTokenId];
// Refund the top bidder
_refundHighestBidder(_msgSender(), previousBid);
emit BidWithdrawn(_garmentTokenId, _msgSender(), previousBid);
}
//////////
// Admin /
//////////
/**
@notice Results a finished auction
@dev Only admin or smart contract
@dev Auction can only be resulted if there has been a bidder and reserve met.
@dev If there have been no bids, the auction needs to be cancelled instead using `cancelAuction()`
@param _garmentTokenId Token ID of the garment being auctioned
*/
function resultAuction(uint256 _garmentTokenId) external nonReentrant {
require(
accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxAuction.resultAuction: Sender must be admin or smart contract"
);
// Check the auction to see if it can be resulted
Auction storage auction = auctions[_garmentTokenId];
// Check the auction real
require(auction.endTime > 0, "DigitalaxAuction.resultAuction: Auction does not exist");
// Check the auction has ended
require(_getNow() > auction.endTime, "DigitalaxAuction.resultAuction: The auction has not ended");
// Ensure auction not already resulted
require(!auction.resulted, "DigitalaxAuction.resultAuction: auction already resulted");
// Ensure this contract is approved to move the token
require(garmentNft.isApproved(_garmentTokenId, address(this)), "DigitalaxAuction.resultAuction: auction not approved");
// Get info on who the highest bidder is
HighestBid storage highestBid = highestBids[_garmentTokenId];
address winner = highestBid.bidder;
uint256 winningBid = highestBid.bid;
// Ensure auction not already resulted
require(winningBid >= auction.reservePrice, "DigitalaxAuction.resultAuction: reserve not reached");
// Ensure there is a winner
require(winner != address(0), "DigitalaxAuction.resultAuction: no open bids");
// Result the auction
auctions[_garmentTokenId].resulted = true;
// Clean up the highest bid
delete highestBids[_garmentTokenId];
// Record the primary sale price for the garment
garmentNft.setPrimarySalePrice(_garmentTokenId, winningBid);
if (winningBid > auction.reservePrice) {
// Work out total above the reserve
uint256 aboveReservePrice = winningBid.sub(auction.reservePrice);
// Work out platform fee from above reserve amount
uint256 platformFeeAboveReserve = aboveReservePrice.mul(platformFee).div(1000);
// Send platform fee
(bool platformTransferSuccess,) = platformFeeRecipient.call{value : platformFeeAboveReserve}("");
require(platformTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send platform fee");
// Send remaining to designer
(bool designerTransferSuccess,) = garmentNft.garmentDesigners(_garmentTokenId).call{value : winningBid.sub(platformFeeAboveReserve)}("");
require(designerTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send the designer their royalties");
} else {
// Send all to the designer
(bool designerTransferSuccess,) = garmentNft.garmentDesigners(_garmentTokenId).call{value : winningBid}("");
require(designerTransferSuccess, "DigitalaxAuction.resultAuction: Failed to send the designer their royalties");
}
// Transfer the token to the winner
garmentNft.safeTransferFrom(garmentNft.ownerOf(_garmentTokenId), winner, _garmentTokenId);
emit AuctionResulted(_garmentTokenId, winner, winningBid);
}
/**
@notice Cancels and inflight and un-resulted auctions, returning the funds to the top bidder if found
@dev Only admin
@param _garmentTokenId Token ID of the garment being auctioned
*/
function cancelAuction(uint256 _garmentTokenId) external nonReentrant {
// Admin only resulting function
require(
accessControls.hasAdminRole(_msgSender()) || accessControls.hasSmartContractRole(_msgSender()),
"DigitalaxAuction.cancelAuction: Sender must be admin or smart contract"
);
// Check valid and not resulted
Auction storage auction = auctions[_garmentTokenId];
// Check auction is real
require(auction.endTime > 0, "DigitalaxAuction.cancelAuction: Auction does not exist");
// Check auction not already resulted
require(!auction.resulted, "DigitalaxAuction.cancelAuction: auction already resulted");
// refund existing top bidder if found
HighestBid storage highestBid = highestBids[_garmentTokenId];
if (highestBid.bidder != address(0)) {
_refundHighestBidder(highestBid.bidder, highestBid.bid);
// Clear up highest bid
delete highestBids[_garmentTokenId];
}
// Remove auction and top bidder
delete auctions[_garmentTokenId];
emit AuctionCancelled(_garmentTokenId);
}
/**
@notice Toggling the pause flag
@dev Only admin
*/
function toggleIsPaused() external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.toggleIsPaused: Sender must be admin");
isPaused = !isPaused;
emit PauseToggled(isPaused);
}
/**
@notice Update the amount by which bids have to increase, across all auctions
@dev Only admin
@param _minBidIncrement New bid step in WEI
*/
function updateMinBidIncrement(uint256 _minBidIncrement) external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateMinBidIncrement: Sender must be admin");
minBidIncrement = _minBidIncrement;
emit UpdateMinBidIncrement(_minBidIncrement);
}
/**
@notice Update the global bid withdrawal lockout time
@dev Only admin
@param _bidWithdrawalLockTime New bid withdrawal lock time
*/
function updateBidWithdrawalLockTime(uint256 _bidWithdrawalLockTime) external {
require(accessControls.hasAdminRole(_msgSender()), "DigitalaxAuction.updateBidWithdrawalLockTime: Sender must be admin");
bidWithdrawalLockTime = _bidWithdrawalLockTime;
emit UpdateBidWithdrawalLockTime(_bidWithdrawalLockTime);
}
/**
@notice Update the current reserve price for an auction
@dev Only admin
@dev Auction must exist
@param _garmentTokenId Token ID of the garment being auctioned
@param _reservePrice New Ether reserve price (WEI value)
*/
function updateAuctionReservePrice(uint256 _garmentTokenId, uint256 _reservePrice) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updateAuctionReservePrice: Sender must be admin"
);
require(
auctions[_garmentTokenId].endTime > 0,
"DigitalaxAuction.updateAuctionReservePrice: No Auction exists"
);
auctions[_garmentTokenId].reservePrice = _reservePrice;
emit UpdateAuctionReservePrice(_garmentTokenId, _reservePrice);
}
/**
@notice Update the current start time for an auction
@dev Only admin
@dev Auction must exist
@param _garmentTokenId Token ID of the garment being auctioned
@param _startTime New start time (unix epoch in seconds)
*/
function updateAuctionStartTime(uint256 _garmentTokenId, uint256 _startTime) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updateAuctionStartTime: Sender must be admin"
);
require(
auctions[_garmentTokenId].endTime > 0,
"DigitalaxAuction.updateAuctionStartTime: No Auction exists"
);
auctions[_garmentTokenId].startTime = _startTime;
emit UpdateAuctionStartTime(_garmentTokenId, _startTime);
}
/**
@notice Update the current end time for an auction
@dev Only admin
@dev Auction must exist
@param _garmentTokenId Token ID of the garment being auctioned
@param _endTimestamp New end time (unix epoch in seconds)
*/
function updateAuctionEndTime(uint256 _garmentTokenId, uint256 _endTimestamp) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updateAuctionEndTime: Sender must be admin"
);
require(
auctions[_garmentTokenId].endTime > 0,
"DigitalaxAuction.updateAuctionEndTime: No Auction exists"
);
require(
auctions[_garmentTokenId].startTime < _endTimestamp,
"DigitalaxAuction.updateAuctionEndTime: End time must be greater than start"
);
require(
_endTimestamp > _getNow(),
"DigitalaxAuction.updateAuctionEndTime: End time passed. Nobody can bid"
);
auctions[_garmentTokenId].endTime = _endTimestamp;
emit UpdateAuctionEndTime(_garmentTokenId, _endTimestamp);
}
/**
@notice Method for updating the access controls contract used by the NFT
@dev Only admin
@param _accessControls Address of the new access controls contract (Cannot be zero address)
*/
function updateAccessControls(DigitalaxAccessControls _accessControls) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updateAccessControls: Sender must be admin"
);
require(address(_accessControls) != address(0), "DigitalaxAuction.updateAccessControls: Zero Address");
accessControls = _accessControls;
emit UpdateAccessControls(address(_accessControls));
}
/**
@notice Method for updating platform fee
@dev Only admin
@param _platformFee uint256 the platform fee to set
*/
function updatePlatformFee(uint256 _platformFee) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updatePlatformFee: Sender must be admin"
);
platformFee = _platformFee;
emit UpdatePlatformFee(_platformFee);
}
/**
@notice Method for updating platform fee address
@dev Only admin
@param _platformFeeRecipient payable address the address to sends the funds to
*/
function updatePlatformFeeRecipient(address payable _platformFeeRecipient) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.updatePlatformFeeRecipient: Sender must be admin"
);
require(_platformFeeRecipient != address(0), "DigitalaxAuction.updatePlatformFeeRecipient: Zero address");
platformFeeRecipient = _platformFeeRecipient;
emit UpdatePlatformFeeRecipient(_platformFeeRecipient);
}
///////////////
// Accessors //
///////////////
/**
@notice Method for getting all info about the auction
@param _garmentTokenId Token ID of the garment being auctioned
*/
function getAuction(uint256 _garmentTokenId)
external
view
returns (uint256 _reservePrice, uint256 _startTime, uint256 _endTime, bool _resulted) {
Auction storage auction = auctions[_garmentTokenId];
return (
auction.reservePrice,
auction.startTime,
auction.endTime,
auction.resulted
);
}
/**
@notice Method for getting all info about the highest bidder
@param _garmentTokenId Token ID of the garment being auctioned
*/
function getHighestBidder(uint256 _garmentTokenId) external view returns (
address payable _bidder,
uint256 _bid,
uint256 _lastBidTime
) {
HighestBid storage highestBid = highestBids[_garmentTokenId];
return (
highestBid.bidder,
highestBid.bid,
highestBid.lastBidTime
);
}
/////////////////////////
// Internal and Private /
/////////////////////////
function _getNow() internal virtual view returns (uint256) {
return block.timestamp;
}
/**
@notice Private method doing the heavy lifting of creating an auction
@param _garmentTokenId Token ID of the garment being auctioned
@param _reservePrice Garment cannot be sold for less than this or minBidIncrement, whichever is higher
@param _startTimestamp Unix epoch in seconds for the auction start time
@param _endTimestamp Unix epoch in seconds for the auction end time.
*/
function _createAuction(
uint256 _garmentTokenId,
uint256 _reservePrice,
uint256 _startTimestamp,
uint256 _endTimestamp
) private {
// Ensure a token cannot be re-listed if previously successfully sold
require(auctions[_garmentTokenId].endTime == 0, "DigitalaxAuction.createAuction: Cannot relist");
// Check end time not before start time and that end is in the future
require(_endTimestamp > _startTimestamp, "DigitalaxAuction.createAuction: End time must be greater than start");
require(_endTimestamp > _getNow(), "DigitalaxAuction.createAuction: End time passed. Nobody can bid.");
// Setup the auction
auctions[_garmentTokenId] = Auction({
reservePrice : _reservePrice,
startTime : _startTimestamp,
endTime : _endTimestamp,
resulted : false
});
emit AuctionCreated(_garmentTokenId);
}
/**
@notice Used for sending back escrowed funds from a previous bid
@param _currentHighestBidder Address of the last highest bidder
@param _currentHighestBid Ether amount in WEI that the bidder sent when placing their bid
*/
function _refundHighestBidder(address payable _currentHighestBidder, uint256 _currentHighestBid) private {
// refund previous best (if bid exists)
(bool successRefund,) = _currentHighestBidder.call{value : _currentHighestBid}("");
require(successRefund, "DigitalaxAuction._refundHighestBidder: failed to refund previous bidder");
emit BidRefunded(_currentHighestBidder, _currentHighestBid);
}
/**
* @notice Reclaims ERC20 Compatible tokens for entire balance
* @dev Only access controls admin
* @param _tokenContract The address of the token contract
*/
function reclaimERC20(address _tokenContract) external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.reclaimERC20: Sender must be admin"
);
require(_tokenContract != address(0), "Invalid address");
IERC20 token = IERC20(_tokenContract);
uint256 balance = token.balanceOf(address(this));
require(token.transfer(msg.sender, balance), "Transfer failed");
}
/**
* @notice Reclaims ETH
* @dev Only access controls admin can access
* @dev ONLY FOR EMERGENCY - THIS WILL DRAIN ALL ETH IN THE ACCOUNT and send it to the calling Admin
* @dev Technically, an admin can already change platformFeeRecipient, auction end time and resultAuction,
* @dev ...so the admin is always in control of funds on the contract anyways. This convenience method allows
* @dev ...the admin to recover extra eth sent to the account after auctions complete, or recover all funds in
* @dev ...case there is a malfunction in the auction operation.
*/
function reclaimETH() external {
require(
accessControls.hasAdminRole(_msgSender()),
"DigitalaxAuction.reclaimETH: Sender must be admin"
);
msg.sender.transfer(address(this).balance);
}
}
|
/ refund previous best (if bid exists)
|
function _refundHighestBidder(address payable _currentHighestBidder, uint256 _currentHighestBid) private {
require(successRefund, "DigitalaxAuction._refundHighestBidder: failed to refund previous bidder");
emit BidRefunded(_currentHighestBidder, _currentHighestBid);
}
| 12,974,281 |
pragma solidity ^0.4.20;
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Common uitility functions
// ----------------------------------------------------------------------------
contract Common {
function Common() internal {
}
function getIndexOfTarget(address[] list, address addr) internal pure returns (int) {
for (uint i = 0; i < list.length; i++) {
if (list[i] == addr) {
return int(i);
}
}
return -1;
}
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
address public operator;
event OwnershipTransferred(address indexed _from, address indexed _to);
event OperatorTransfered(address indexed _from, address indexed _to);
function Owned() internal {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyOwnerOrOperator {
require(msg.sender == owner || msg.sender == operator);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function transferOperator(address _newOperator) public onlyOwner {
address originalOperator = operator;
operator = _newOperator;
OperatorTransfered(originalOperator, _newOperator);
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
contract TokenHeld {
address[] public addressIndices;
event OnPushedAddress(address addr, uint index);
function TokenHeld() internal {
}
// ------------------------------------------------------------------------
// Scan the addressIndices for ensuring the target address is included
// ------------------------------------------------------------------------
function scanAddresses(address addr) internal {
bool isAddrExist = false;
for (uint i = 0;i < addressIndices.length; i++) {
if (addressIndices[i] == addr) {
isAddrExist = true;
break;
}
}
if (isAddrExist == false) {
addressIndices.push(addr);
OnPushedAddress(addr, addressIndices.length);
}
}
}
contract Restricted is Common, Owned {
bool isChargingTokenTransferFee;
bool isAllocatingInterest;
bool isChargingManagementFee;
bool isTokenTransferOpen;
address[] tokenTransferDisallowedAddresses;
event OnIsChargingTokenTransferFeeUpdated(bool from, bool to);
event OnIsAllocatingInterestUpdated(bool from, bool to);
event OnIsChargingManagementFeeUpdated(bool from, bool to);
event OnIsTokenTransferOpenUpdated(bool from, bool to);
event OnTransferDisallowedAddressesChanged(string action, address indexed addr);
modifier onlyWhenAllocatingInterestOpen {
require(isAllocatingInterest == true);
_;
}
modifier onlyWhenChargingManagementFeeOpen {
require(isChargingManagementFee == true);
_;
}
modifier onlyWhenTokenTransferOpen {
require(isTokenTransferOpen == true);
_;
}
modifier shouldBeAllowed(address[] list, address addr) {
require(getIndexOfTarget(list, addr) == -1);
_;
}
function Restricted() internal {
isChargingTokenTransferFee = false;
isAllocatingInterest = false;
isChargingManagementFee = false;
isTokenTransferOpen = true;
}
function setIsChargingTokenTransferFee(bool onOff) public onlyOwnerOrOperator {
bool original = isChargingTokenTransferFee;
isChargingTokenTransferFee = onOff;
OnIsChargingTokenTransferFeeUpdated(original, onOff);
}
function setIsAllocatingInterest(bool onOff) public onlyOwnerOrOperator {
bool original = isAllocatingInterest;
isAllocatingInterest = onOff;
OnIsAllocatingInterestUpdated(original, onOff);
}
function setIsChargingManagementFee(bool onOff) public onlyOwnerOrOperator {
bool original = isChargingManagementFee;
isChargingManagementFee = onOff;
OnIsChargingManagementFeeUpdated(original, onOff);
}
function setIsTokenTransferOpen(bool onOff) public onlyOwnerOrOperator {
bool original = isTokenTransferOpen;
isTokenTransferOpen = onOff;
OnIsTokenTransferOpenUpdated(original, onOff);
}
function addToTokenTransferDisallowedList(address addr) public onlyOwnerOrOperator {
int idx = getIndexOfTarget(tokenTransferDisallowedAddresses, addr);
if (idx == -1) {
tokenTransferDisallowedAddresses.push(addr);
OnTransferDisallowedAddressesChanged("add", addr);
}
}
function removeFromTokenTransferDisallowedAddresses(address addr) public onlyOwnerOrOperator {
int idx = getIndexOfTarget(tokenTransferDisallowedAddresses, addr);
if (idx >= 0) {
uint uidx = uint(idx);
delete tokenTransferDisallowedAddresses[uidx];
OnTransferDisallowedAddressesChanged("remove", addr);
}
}
}
contract TokenTransaction is Common, Owned {
bool isTokenTransactionOpen;
address[] transactionDisallowedAddresses;
uint exchangeRateFor1Eth;
event OnIsTokenTransactionOpenUpdated(bool from, bool to);
event OnTransactionDisallowedAddressesChanged(string action, address indexed addr);
event OnExchangeRateUpdated(uint from, uint to);
modifier onlyWhenTokenTransactionOpen {
require(isTokenTransactionOpen == true);
_;
}
function TokenTransaction() internal {
isTokenTransactionOpen = true;
exchangeRateFor1Eth = 1000;
}
function setIsTokenTransactionOpen(bool onOff) public onlyOwnerOrOperator {
bool original = isTokenTransactionOpen;
isTokenTransactionOpen = onOff;
OnIsTokenTransactionOpenUpdated(original, onOff);
}
function addToTransactionDisallowedList(address addr) public constant onlyOwnerOrOperator {
int idx = getIndexOfTarget(transactionDisallowedAddresses, addr);
if (idx == -1) {
transactionDisallowedAddresses.push(addr);
OnTransactionDisallowedAddressesChanged("add", addr);
}
}
function removeFromTransactionDisallowedList(address addr) public constant onlyOwnerOrOperator {
int idx = getIndexOfTarget(transactionDisallowedAddresses, addr);
if (idx >= 0) {
uint uidx = uint(idx);
delete transactionDisallowedAddresses[uidx];
OnTransactionDisallowedAddressesChanged("remove", addr);
}
}
function updateExchangeRate(uint newExchangeRate) public onlyOwner {
uint originalRate = exchangeRateFor1Eth;
exchangeRateFor1Eth = newExchangeRate;
OnExchangeRateUpdated(originalRate, newExchangeRate);
}
}
contract Distributed is Owned {
using SafeMath for uint;
// Allocation related
uint tokenTransferPercentageNumerator;
uint tokenTransferPercentageDenominator;
uint interestAllocationPercentageNumerator;
uint interestAllocationPercentageDenominator;
uint managementFeeChargePercentageNumerator;
uint managementFeeChargePercentageDenominator;
uint distCompanyPercentage;
uint distTeamPercentage;
uint distOfferPercentage;
event OnPercentageChanged(string state, uint _m, uint _d, uint m, uint d);
event OnDistributionChanged(uint _c, uint _t, uint _o, uint c, uint t, uint o);
modifier onlyWhenPercentageSettingIsValid(uint c, uint t, uint o) {
require((c.add(t).add(o)) == 100);
_;
}
function Distributed() internal {
tokenTransferPercentageNumerator = 1;
tokenTransferPercentageDenominator = 100;
interestAllocationPercentageNumerator = 1;
interestAllocationPercentageDenominator = 100;
managementFeeChargePercentageNumerator = 1;
managementFeeChargePercentageDenominator = 100;
distCompanyPercentage = 20;
distTeamPercentage = 10;
distOfferPercentage = 70;
}
function setTokenTransferPercentage(uint numerator, uint denominator) public onlyOwnerOrOperator {
uint m = tokenTransferPercentageNumerator;
uint d = tokenTransferPercentageDenominator;
tokenTransferPercentageNumerator = numerator;
tokenTransferPercentageDenominator = denominator;
OnPercentageChanged("TokenTransferFee", m, d, numerator, denominator);
}
function setInterestAllocationPercentage(uint numerator, uint denominator) public onlyOwnerOrOperator {
uint m = interestAllocationPercentageNumerator;
uint d = interestAllocationPercentageDenominator;
interestAllocationPercentageNumerator = numerator;
interestAllocationPercentageDenominator = denominator;
OnPercentageChanged("InterestAllocation", m, d, numerator, denominator);
}
function setManagementFeeChargePercentage(uint numerator, uint denominator) public onlyOwnerOrOperator {
uint m = managementFeeChargePercentageNumerator;
uint d = managementFeeChargePercentageDenominator;
managementFeeChargePercentageNumerator = numerator;
managementFeeChargePercentageDenominator = denominator;
OnPercentageChanged("ManagementFee", m, d, numerator, denominator);
}
function setDistributionPercentage(uint c, uint t, uint o) public onlyWhenPercentageSettingIsValid(c, t, o) onlyOwner {
uint _c = distCompanyPercentage;
uint _t = distTeamPercentage;
uint _o = distOfferPercentage;
distCompanyPercentage = c;
distTeamPercentage = t;
distOfferPercentage = o;
OnDistributionChanged(_c, _t, _o, distCompanyPercentage, distTeamPercentage, distOfferPercentage);
}
}
contract FeeCalculation {
using SafeMath for uint;
function FeeCalculation() internal {
}
// ------------------------------------------------------------------------
// Calculate the fee tokens for transferring.
// ------------------------------------------------------------------------
function calculateTransferFee(uint tokens) internal pure returns (uint) {
uint calFee = 0;
if (tokens > 0 && tokens <= 1000)
calFee = 1;
else if (tokens > 1000 && tokens <= 5000)
calFee = tokens.mul(1).div(1000);
else if (tokens > 5000 && tokens <= 10000)
calFee = tokens.mul(2).div(1000);
else if (tokens > 10000)
calFee = 30;
return calFee;
}
}
// ----------------------------------------------------------------------------
// initial fixed supply
// ----------------------------------------------------------------------------
contract FixedSupplyToken is ERC20Interface, Distributed, TokenHeld, Restricted, TokenTransaction, FeeCalculation {
using SafeMath for uint;
// Token information related
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
event OnAllocated(address indexed addr, uint allocatedTokens);
event OnCharged(address indexed addr, uint chargedTokens);
modifier onlyWhenOfferredIsLowerThanDistOfferPercentage {
uint expectedTokens = msg.value.mul(1000);
uint totalOfferredTokens = 0;
for (uint i = 0; i < addressIndices.length; i++) {
totalOfferredTokens += balances[addressIndices[i]];
}
require(_totalSupply.mul(distOfferPercentage).div(100) - expectedTokens >= 0);
_;
}
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function FixedSupplyToken() public {
symbol = "AGC";
name = "Agile Coin";
decimals = 0;
_totalSupply = 100000000 * 10**uint(decimals);
balances[owner] = _totalSupply;
Transfer(address(0), owner, _totalSupply);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
uint balance = balances[address(0)];
return _totalSupply - balance;
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public onlyWhenTokenTransferOpen shouldBeAllowed(transactionDisallowedAddresses, msg.sender) returns (bool success) {
uint calFee = isChargingTokenTransferFee ? calculateTransferFee(tokens) : 0;
scanAddresses(to);
balances[msg.sender] = balances[msg.sender].sub(tokens + calFee);
balances[owner] = balances[owner].add(calFee);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
Transfer(msg.sender, owner, calFee);
return true;
}
// ------------------------------------------------------------------------
// 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 returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public onlyWhenTokenTransferOpen shouldBeAllowed(tokenTransferDisallowedAddresses, msg.sender) returns (bool success) {
uint calFee = isChargingTokenTransferFee ? calculateTransferFee(tokens) : 0;
scanAddresses(to);
balances[from] = balances[from].sub(tokens + calFee);
balances[owner] = balances[owner].add(calFee);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
Transfer(from, owner, calFee);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// Don't accept ETH
// ------------------------------------------------------------------------
function () public payable onlyWhenTokenTransactionOpen onlyWhenOfferredIsLowerThanDistOfferPercentage {
// Exchange: ETH --> ETTA Coin
revert();
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// ------------------------------------------------------------------------
// Allocate interest.
// ------------------------------------------------------------------------
function allocateTokens() public onlyOwnerOrOperator onlyWhenAllocatingInterestOpen {
for (uint i = 0; i < addressIndices.length; i++) {
address crntAddr = addressIndices[i];
uint balanceOfCrntAddr = balances[crntAddr];
uint allocatedTokens = balanceOfCrntAddr.mul(interestAllocationPercentageNumerator).div(interestAllocationPercentageDenominator);
balances[crntAddr] = balances[crntAddr].add(allocatedTokens);
balances[owner] = balances[owner].sub(allocatedTokens);
Transfer(owner, crntAddr, allocatedTokens);
OnAllocated(crntAddr, allocatedTokens);
}
}
// ------------------------------------------------------------------------
// Charge investers for management fee.
// ------------------------------------------------------------------------
function chargeTokensForManagement() public onlyOwnerOrOperator onlyWhenChargingManagementFeeOpen {
for (uint i = 0; i < addressIndices.length; i++) {
address crntAddr = addressIndices[i];
uint balanceOfCrntAddr = balances[crntAddr];
uint chargedTokens = balanceOfCrntAddr.mul(managementFeeChargePercentageNumerator).div(managementFeeChargePercentageDenominator);
balances[crntAddr] = balances[crntAddr].sub(chargedTokens);
balances[owner] = balances[owner].add(chargedTokens);
Transfer(crntAddr,owner, chargedTokens);
OnCharged(crntAddr, chargedTokens);
}
}
// ------------------------------------------------------------------------
// Distribute more token of contract and transfer to owner
// ------------------------------------------------------------------------
function mintToken(uint256 mintedAmount) public onlyOwner {
require(mintedAmount > 0);
balances[owner] = balances[owner].add(mintedAmount);
_totalSupply = _totalSupply.add(mintedAmount);
Transfer(address(0), owner, mintedAmount);
}
event OnTokenBurned(uint256 totalBurnedTokens);
// ------------------------------------------------------------------------
// Remove `numerator / denominator` % of tokens from the system irreversibly
// ------------------------------------------------------------------------
function burnByPercentage(uint8 m, uint8 d) public onlyOwner returns (bool success) {
require(m > 0 && d > 0 && m <= d);
uint totalBurnedTokens = balances[owner].mul(m).div(d);
balances[owner] = balances[owner].sub(totalBurnedTokens);
_totalSupply = _totalSupply.sub(totalBurnedTokens);
Transfer(owner, address(0), totalBurnedTokens);
OnTokenBurned(totalBurnedTokens);
return true;
}
// ------------------------------------------------------------------------
// Remove a quantity of tokens
// ------------------------------------------------------------------------
function burnByAmount(uint256 tokens) public onlyOwner returns (bool success) {
require(tokens > 0 && tokens <= balances[owner]);
balances[owner] = balances[owner].sub(tokens);
_totalSupply = _totalSupply.sub(tokens);
Transfer(owner, address(0), tokens);
OnTokenBurned(tokens);
return true;
}
}
|
------------------------------------------------------------------------ Transfer `tokens` from the `from` account to the `to` account The calling account must already have sufficient tokens approve(...)-d for spending from the `from` account and - From account must have sufficient balance to transfer - Spender must have sufficient allowance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
|
function transferFrom(address from, address to, uint tokens) public onlyWhenTokenTransferOpen shouldBeAllowed(tokenTransferDisallowedAddresses, msg.sender) returns (bool success) {
uint calFee = isChargingTokenTransferFee ? calculateTransferFee(tokens) : 0;
scanAddresses(to);
balances[from] = balances[from].sub(tokens + calFee);
balances[owner] = balances[owner].add(calFee);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
Transfer(from, owner, calFee);
return true;
}
| 1,032,681 |
./full_match/1/0x5cA5abC25EFAA03DD44FCaa58984944037518764/sources/src/SushiXSwapV2.sol
|
internal just swap increase token approval to RP
|
function _swap(bytes memory _swapData) internal {
IRouteProcessor.RouteProcessorData memory rpd = abi.decode(
_swapData,
(IRouteProcessor.RouteProcessorData)
);
if (rpd.tokenIn != NATIVE_ADDRESS) {
IERC20(rpd.tokenIn).safeTransferFrom(
msg.sender,
address(this),
rpd.amountIn
);
IERC20(rpd.tokenIn).safeIncreaseAllowance(
address(rp),
rpd.amountIn
);
}
rp.processRoute{
value: rpd.tokenIn == NATIVE_ADDRESS ? rpd.amountIn : 0
}(
rpd.tokenIn,
rpd.amountIn,
rpd.tokenOut,
rpd.amountOutMin,
rpd.to,
rpd.route
);
}
| 2,913,013 |
pragma solidity ^0.4.24;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account)
internal
view
returns (bool)
{
require(account != address(0));
return role.bearer[account];
}
}
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private pausers;
constructor() internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
pausers.remove(account);
emit PauserRemoved(account);
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @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() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @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 private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Elliptic 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 ECDSA {
/**
* @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 signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes signature)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.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(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// 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)
);
}
}
contract BMng is Pausable, Ownable {
using SafeMath for uint256;
enum TokenStatus {
Unknown,
Active,
Suspended
}
struct Token {
TokenStatus status;
uint256 rewardRateNumerator;
uint256 rewardRateDenominator;
uint256 burned;
uint256 burnedAccumulator;
uint256 suspiciousVolume; // provided during registration
}
event Auth(
address indexed burner,
address indexed partner
);
event Burn(
address indexed token,
address indexed burner,
address partner,
uint256 value,
uint256 bValue,
uint256 bValuePartner
);
event DiscountUpdate(
uint256 discountNumerator,
uint256 discountDenominator,
uint256 balanceThreshold
);
address constant burnAddress = 0x000000000000000000000000000000000000dEaD;
// Lifetime parameters (set on initialization)
string public name;
IERC20 bToken; // BurnToken address
uint256 discountNumeratorMul;
uint256 discountDenominatorMul;
uint256 bonusNumerator;
uint256 bonusDenominator;
uint256 public initialBlockNumber;
// Evolving parameters
uint256 discountNumerator;
uint256 discountDenominator;
uint256 balanceThreshold;
// Managable parameters
address registrator;
address defaultPartner;
uint256 partnerRewardRateNumerator;
uint256 partnerRewardRateDenominator;
bool permissionRequired;
mapping (address => Token) public tokens;
mapping (address => address) referalPartners; // Users associated with referrals
mapping (address => mapping (address => uint256)) burnedByTokenUser; // Counters
mapping (bytes6 => address) refLookup; // Reference codes
mapping (address => bool) public shouldGetBonus; // Bonuses
mapping (address => uint256) public nonces; // Nonces for permissions
constructor(
address bTokenAddress,
address _registrator,
address _defaultPartner,
uint256 initialBalance
)
public
{
name = "Burn Token Management Contract v0.3";
registrator = _registrator;
defaultPartner = _defaultPartner;
bToken = IERC20(bTokenAddress);
initialBlockNumber = block.number;
// Initially no permission needed for each burn
permissionRequired = false;
// Formal referals for registrator and defaultPartner
referalPartners[registrator] = burnAddress;
referalPartners[defaultPartner] = burnAddress;
// Reward rate 15% for each referral burning
partnerRewardRateNumerator = 15;
partnerRewardRateDenominator = 100;
// 20% bonus for using referal link
bonusNumerator = 20;
bonusDenominator = 100;
// discount 5% each time when when 95% of the balance spent
discountNumeratorMul = 95;
discountDenominatorMul = 100;
discountNumerator = 1;
discountDenominator = 1;
balanceThreshold = initialBalance.mul(discountNumeratorMul).div(discountDenominatorMul);
}
// --------------------------------------------------------------------------
// Administration fuctionality
function claimBurnTokensBack(address to) public onlyOwner {
// This is necessary to finalize the contract lifecicle
uint256 remainingBalance = bToken.balanceOf(address(this));
bToken.transfer(to, remainingBalance);
}
function registerToken(
address tokenAddress,
uint256 suspiciousVolume,
uint256 rewardRateNumerator,
uint256 rewardRateDenominator,
bool activate
)
public
onlyOwner
{
// require(tokens[tokenAddress].status == TokenStatus.Unknown, "Cannot register more than one time");
Token memory token;
if (activate) {
token.status = TokenStatus.Active;
} else {
token.status = TokenStatus.Suspended;
}
token.rewardRateNumerator = rewardRateNumerator;
token.rewardRateDenominator = rewardRateDenominator;
token.suspiciousVolume = suspiciousVolume;
tokens[tokenAddress] = token;
}
function changeRegistrator(address newRegistrator) public onlyOwner {
registrator = newRegistrator;
}
function changeDefaultPartnerAddress(address newDefaultPartner) public onlyOwner {
defaultPartner = newDefaultPartner;
}
function setRewardRateForToken(
address tokenAddress,
uint256 rewardRateNumerator,
uint256 rewardRateDenominator
)
public
onlyOwner
{
require(tokens[tokenAddress].status != TokenStatus.Unknown, "Token should be registered first");
tokens[tokenAddress].rewardRateNumerator = rewardRateNumerator;
tokens[tokenAddress].rewardRateDenominator = rewardRateDenominator;
}
function setPartnerRewardRate(
uint256 newPartnerRewardRateNumerator,
uint256 newPartnerRewardRateDenominator
)
public
onlyOwner
{
partnerRewardRateNumerator = newPartnerRewardRateNumerator;
partnerRewardRateDenominator = newPartnerRewardRateDenominator;
}
function setPermissionRequired(bool state) public onlyOwner {
permissionRequired = state;
}
function suspend(address tokenAddress) public onlyOwner {
require(tokens[tokenAddress].status != TokenStatus.Unknown, "Token should be registered first");
tokens[tokenAddress].status = TokenStatus.Suspended;
}
function unSuspend(address tokenAddress) public onlyOwner {
require(tokens[tokenAddress].status != TokenStatus.Unknown, "Token should be registered first");
tokens[tokenAddress].status = TokenStatus.Active;
tokens[tokenAddress].burnedAccumulator = 0;
}
function activate(address tokenAddress) public onlyOwner {
require(tokens[tokenAddress].status != TokenStatus.Unknown, "Token should be registered first");
tokens[tokenAddress].status = TokenStatus.Active;
}
// END of Administration fuctionality
// --------------------------------------------------------------------------
modifier whenNoPermissionRequired() {
require(!isPermissionRequired(), "Need a permission");
_;
}
function isPermissionRequired() public view returns (bool) {
// if burn can only occure by signed permission
return permissionRequired;
}
function isAuthorized(address user) public view whenNotPaused returns (bool) {
address partner = referalPartners[user];
return partner != address(0);
}
function amountBurnedTotal(address tokenAddress) public view returns (uint256) {
return tokens[tokenAddress].burned;
}
function amountBurnedByUser(address tokenAddress, address user) public view returns (uint256) {
return burnedByTokenUser[tokenAddress][user];
}
// Ref code
function getRefByAddress(address user) public pure returns (bytes6) {
/*
We use Base58 encoding and want refcode length to be 8 symbols
bits = log2(58) * 8 = 46.86384796102058 = 40 + 6.86384796102058
2^(40 + 6.86384796102058) = 0x100^5 * 116.4726943 ~ 0x100^5 * 116
CEIL(47 / 8) = 6
Output: bytes6 (48 bits)
In such case for 10^6 records we have 0.39% hash collision probability
(see: https://preshing.com/20110504/hash-collision-probabilities/)
*/
bytes32 dataHash = keccak256(abi.encodePacked(user, "BUTK"));
bytes32 tmp = bytes32(uint256(dataHash) % uint256(116 * 0x10000000000));
return bytes6(tmp << 26 * 8);
}
function getAddressByRef(bytes6 ref) public view returns (address) {
return refLookup[ref];
}
function saveRef(address user) private returns (bool) {
require(user != address(0), "Should not be zero address");
bytes6 ref = getRefByAddress(user);
refLookup[ref] = user;
return true;
}
function checkSignature(bytes memory sig, address user) public view returns (bool) {
bytes32 dataHash = keccak256(abi.encodePacked(user));
return (ECDSA.recover(dataHash, sig) == registrator);
}
function checkPermissionSignature(
bytes memory sig,
address user,
address tokenAddress,
uint256 value,
uint256 nonce
)
public view returns (bool)
{
bytes32 dataHash = keccak256(abi.encodePacked(user, tokenAddress, value, nonce));
return (ECDSA.recover(dataHash, sig) == registrator);
}
function authorizeAddress(bytes memory authSignature, bytes6 ref) public whenNotPaused returns (bool) {
// require(false, "Test fail");
require(checkSignature(authSignature, msg.sender) == true, "Authorization should be signed by registrator");
require(isAuthorized(msg.sender) == false, "No need to authorize more then once");
address refAddress = getAddressByRef(ref);
address partner = (refAddress == address(0)) ? defaultPartner : refAddress;
// Create ref code (register as a partner)
saveRef(msg.sender);
referalPartners[msg.sender] = partner;
// Only if ref code is used authorized to get extra bonus
if (partner != defaultPartner) {
shouldGetBonus[msg.sender] = true;
}
emit Auth(msg.sender, partner);
return true;
}
function suspendIfNecessary(address tokenAddress) private returns (bool) {
// When 10% of totalSupply is burned suspend the token just in case
// there is a chance that its contract is broken
if (tokens[tokenAddress].burnedAccumulator > tokens[tokenAddress].suspiciousVolume) {
tokens[tokenAddress].status = TokenStatus.Suspended;
return true;
}
return false;
}
// Discount
function discountCorrectionIfNecessary(uint256 balance) private returns (bool) {
if (balance < balanceThreshold) {
// Update discountNumerator, discountDenominator and balanceThreshold
// we multiply discount coefficient by discountNumeratorMul / discountDenominatorMul
discountNumerator = discountNumerator.mul(discountNumeratorMul);
discountDenominator = discountDenominator.mul(discountDenominatorMul);
balanceThreshold = balanceThreshold.mul(discountNumeratorMul).div(discountDenominatorMul);
emit DiscountUpdate(discountNumerator, discountDenominator, balanceThreshold);
return true;
}
return false;
}
// Helpers
function getAllTokenData(
address tokenAddress,
address user
)
public view returns (uint256, uint256, uint256, uint256, bool)
{
IERC20 tokenContract = IERC20(tokenAddress);
uint256 balance = tokenContract.balanceOf(user);
uint256 allowance = tokenContract.allowance(user, address(this));
uint256 burnedByUser = amountBurnedByUser(tokenAddress, user);
uint256 burnedTotal = amountBurnedTotal(tokenAddress);
bool isActive = (tokens[tokenAddress].status == TokenStatus.Active);
return (balance, allowance, burnedByUser, burnedTotal, isActive);
}
function getBTokenValue(
address tokenAddress,
uint256 value
)
public view returns (uint256)
{
Token memory tokenRec = tokens[tokenAddress];
require(tokenRec.status == TokenStatus.Active, "Token should be in active state");
uint256 denominator = tokenRec.rewardRateDenominator;
require(denominator > 0, "Reward denominator should not be zero");
uint256 numerator = tokenRec.rewardRateNumerator;
uint256 bTokenValue = value.mul(numerator).div(denominator);
// Discount
uint256 discountedBTokenValue = bTokenValue.mul(discountNumerator).div(discountDenominator);
return discountedBTokenValue;
}
function getPartnerReward(uint256 bTokenValue) public view returns (uint256) {
return bTokenValue.mul(partnerRewardRateNumerator).div(partnerRewardRateDenominator);
}
function burn(
address tokenAddress,
uint256 value
)
public
whenNotPaused
whenNoPermissionRequired
{
_burn(tokenAddress, value);
}
function burnPermissioned(
address tokenAddress,
uint256 value,
uint256 nonce,
bytes memory permissionSignature
)
public
whenNotPaused
{
require(nonces[msg.sender] < nonce, "New nonce should be greater than previous");
bool signatureOk = checkPermissionSignature(permissionSignature, msg.sender, tokenAddress, value, nonce);
require(signatureOk, "Permission should have a correct signature");
nonces[msg.sender] = nonce;
_burn(tokenAddress, value);
}
function _burn(address tokenAddress, uint256 value) private {
address partner = referalPartners[msg.sender];
require(partner != address(0), "Burner should be registered");
IERC20 tokenContract = IERC20(tokenAddress);
require(tokenContract.allowance(msg.sender, address(this)) >= value, "Should be allowed");
uint256 bTokenValueTotal; // total user reward including bonus if allowed
uint256 bTokenValue = getBTokenValue(tokenAddress, value);
uint256 currentBalance = bToken.balanceOf(address(this));
require(bTokenValue < currentBalance.div(100), "Cannot reward more than 1% of the balance");
uint256 bTokenPartnerReward = getPartnerReward(bTokenValue);
// Update counters
tokens[tokenAddress].burned = tokens[tokenAddress].burned.add(value);
tokens[tokenAddress].burnedAccumulator = tokens[tokenAddress].burnedAccumulator.add(value);
burnedByTokenUser[tokenAddress][msg.sender] = burnedByTokenUser[tokenAddress][msg.sender].add(value);
tokenContract.transferFrom(msg.sender, burnAddress, value); // burn shit-token
discountCorrectionIfNecessary(currentBalance.sub(bTokenValue).sub(bTokenPartnerReward));
suspendIfNecessary(tokenAddress);
bToken.transfer(partner, bTokenPartnerReward);
if (shouldGetBonus[msg.sender]) {
// give 20% bonus once
shouldGetBonus[msg.sender] = false;
bTokenValueTotal = bTokenValue.add(bTokenValue.mul(bonusNumerator).div(bonusDenominator));
} else {
bTokenValueTotal = bTokenValue;
}
bToken.transfer(msg.sender, bTokenValueTotal);
emit Burn(tokenAddress, msg.sender, partner, value, bTokenValueTotal, bTokenPartnerReward);
}
}
|
if burn can only occure by signed permission
|
function isPermissionRequired() public view returns (bool) {
return permissionRequired;
}
| 14,018,289 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.22 <0.9.0;
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./CampaignFactory.sol";
import "./CampaignReward.sol";
import "./CampaignRequest.sol";
import "./CampaignVote.sol";
import "../utils/AccessControl.sol";
import "../interfaces/ICampaignFactory.sol";
import "../interfaces/ICampaignReward.sol";
import "../interfaces/ICampaignRequest.sol";
import "../interfaces/ICampaignVote.sol";
import "../libraries/contracts/CampaignFactoryLib.sol";
import "../libraries/contracts/CampaignRewardLib.sol";
import "../libraries/math/DecimalMath.sol";
contract Campaign is
Initializable,
AccessControl,
PausableUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeMathUpgradeable for uint8;
using SafeMathUpgradeable for uint256;
using DecimalMath for int256;
using DecimalMath for uint256;
enum GOALTYPE {
FIXED,
FLEXIBLE
}
GOALTYPE public goalType;
enum CAMPAIGN_STATE {
COLLECTION,
LIVE,
REVIEW,
COMPLETE,
UNSUCCESSFUL
}
CAMPAIGN_STATE public campaignState;
/// @dev `Initializer Event`
event CampaignOwnerSet(address user);
/// @dev `Campaign Config Events`
event CampaignOwnershipTransferred(address newOwner);
event CampaignSettingsUpdated(
uint256 target,
uint256 minimumContribution,
uint256 duration,
uint256 goalType,
address token,
bool allowContributionAfterTargetIsMet
);
event CampaignDeadlineExtended(uint256 time);
event DeadlineThresholdExtended(uint8 count);
/// @dev `Approval Transfer`
event CampaignUserDataTransferred(address oldAddress, address newAddress);
/// @dev `Contribution Events`
event ContributorApprovalToggled(address contributor, bool isApproved);
event ContributionMade(
uint256 indexed contributionId,
uint256 amount,
uint256 indexed rewardId,
uint256 indexed rewardRecipientId,
bool withReward
);
event ContributionWithdrawn(
uint256 indexed contributionId,
uint256 amount,
address user
);
/// @dev `Request Event`
event RequestComplete(uint256 indexed requestId);
/// @dev `Review Events`
event CampaignReviewed(address user, string hashedReview);
event CampaignReported(address user, string hashedReport);
/// @dev `Campaign State Events`
event CampaignStateChange(CAMPAIGN_STATE state);
event WithdrawalStateUpdated(bool withdrawalState);
ICampaignFactory public campaignFactoryContract;
ICampaignReward public campaignRewardContract;
ICampaignRequest public campaignRequestContract;
ICampaignVote public campaignVoteContract;
/// @dev `Contribution`
struct Contribution {
uint256 amount;
bool withdrawn;
}
Contribution[] contributions;
mapping(address => uint256) public contributionId;
/// @dev `Review`
uint256 public reviewCount;
mapping(address => bool) public reviewed;
mapping(address => string) public reviewHash;
address public root;
address public acceptedToken;
bool public allowContributionAfterTargetIsMet;
bool public withdrawalsPaused;
uint8 public percentBase;
uint256 public percent;
uint256 public totalCampaignContribution;
uint256 public campaignBalance;
uint256 public minimumContribution;
uint256 public approversCount;
uint256 public target;
uint256 public deadline;
uint256 public deadlineSetTimes;
uint256 public reportCount;
mapping(address => bool) public allowedToContribute;
mapping(address => bool) public approvers;
mapping(address => bool) public reported;
mapping(address => string) public reportHash;
mapping(address => uint256) public transferAttemptCount;
mapping(address => uint256) public timeUntilNextTransferConfirmation;
/// @dev Ensures caller is only factory
modifier onlyFactory() {
require(
CampaignFactoryLib.canManageCampaigns(
campaignFactoryContract,
msg.sender
),
"only factory"
);
_;
}
/// @dev Ensures a user is verified
modifier userIsVerified(address _user) {
bool verified;
(, , verified) = CampaignFactoryLib.userInfo(
campaignFactoryContract,
_user
);
require(verified, "unverified");
_;
}
/// @dev Ensures user account is not in transit process
modifier userTransferNotInTransit() {
require(
!campaignFactoryContract.accountInTransit(msg.sender),
"in transit"
);
_;
}
/**
* @dev Constructor
* @param _campaignFactory Address of factory
* @param _campaignRewards Address of campaign reward contract
* @param _campaignRequests Address of campaign request contract
* @param _campaignVotes Address of campaign vote contract
* @param _root Address of campaign owner
*/
function __Campaign_init(
CampaignFactory _campaignFactory,
CampaignReward _campaignRewards,
CampaignRequest _campaignRequests,
CampaignVote _campaignVotes,
address _root
) public initializer {
require(address(_root) != address(0));
campaignFactoryContract = ICampaignFactory(address(_campaignFactory));
campaignRewardContract = ICampaignReward(address(_campaignRewards));
campaignRequestContract = ICampaignRequest(address(_campaignRequests));
campaignVoteContract = ICampaignVote(address(_campaignVotes));
root = _root;
campaignState = CAMPAIGN_STATE.COLLECTION;
percentBase = 100;
percent = percentBase.mul(DecimalMath.UNIT);
withdrawalsPaused = false;
_setupRole(DEFAULT_ADMIN_ROLE, root);
_setupRole(SET_CAMPAIGN_SETTINGS, root);
_setupRole(EXTEND_DEADLINE, root);
_setupRole(CONTRIBUTOR_APPROVAL, root);
_setupRole(FINALIZE_REQUEST, root);
_setupRole(REVIEW_MODE, root);
_setupRole(MARK_CAMPAIGN_COMPLETE, root);
_setRoleAdmin(SET_CAMPAIGN_SETTINGS, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(EXTEND_DEADLINE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(CONTRIBUTOR_APPROVAL, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(FINALIZE_REQUEST, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(REVIEW_MODE, DEFAULT_ADMIN_ROLE);
_setRoleAdmin(MARK_CAMPAIGN_COMPLETE, DEFAULT_ADMIN_ROLE);
emit CampaignOwnerSet(root);
}
/**
* @dev Checks if a provided address is a campaign admin
* @param _user Address of the user
*/
function isCampaignAdmin(address _user) external view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _user);
}
/**
* @dev Checks if a provided address has role
* @param _permission Role being checked
* @param _account Address of the user
*/
function isAllowed(bytes32 _permission, address _account)
external
view
returns (bool)
{
return hasRole(_permission, _account);
}
/**
* @dev Returns the campaigns funding goal type
* @param _goalType Integer representing a goal type
*/
function getCampaignGoalType(uint256 _goalType)
external
pure
returns (GOALTYPE)
{
return GOALTYPE(_goalType);
}
/**
* @dev Returns a campaign state by a provided index
* @param _state Integer representing a state in the campaign
*/
function getCampaignState(uint256 _state)
external
pure
returns (CAMPAIGN_STATE)
{
return CAMPAIGN_STATE(_state);
}
/**
* @dev Transfers campaign ownership from one user to another.
* @param _oldRoot Address of the user campaign ownership is being transfered from
* @param _newRoot Address of the user campaign ownership is being transfered to
*/
function transferCampaignOwnership(address _oldRoot, address _newRoot)
public
onlyAdmin
whenNotPaused
{
require(_oldRoot == root);
root = _newRoot;
_setupRole(DEFAULT_ADMIN_ROLE, _newRoot);
renounceRole(DEFAULT_ADMIN_ROLE, _oldRoot);
emit CampaignOwnershipTransferred(_newRoot);
}
/**
* @dev Transfers user data in the campaign to another verifed user
* @param _oldAddress Address of the user transferring
* @param _newAddress Address of the user being transferred to
*/
function transferCampaignUserData(address _oldAddress, address _newAddress)
external
nonReentrant
whenNotPaused
userIsVerified(_newAddress)
{
// check if in transfer process from parent contract
require(
campaignFactoryContract.accountInTransit(_oldAddress),
"not in transit"
);
require(
campaignFactoryContract.isUserTrustee(_oldAddress, msg.sender),
"not a trustee"
);
require(
campaignState == CAMPAIGN_STATE.COLLECTION ||
campaignState == CAMPAIGN_STATE.LIVE,
"not live or in collection"
);
require(approvers[_oldAddress], "not an approver");
require(
transferAttemptCount[_oldAddress] <= 6,
"transfer attempts exhausted"
);
require(
timeUntilNextTransferConfirmation[_oldAddress] >= block.timestamp,
"time until next confirmation not expired"
);
if (transferAttemptCount[_oldAddress] < 3) {
transferAttemptCount[_oldAddress] = transferAttemptCount[
_oldAddress
].add(1);
timeUntilNextTransferConfirmation[_oldAddress] = block
.timestamp
.add(30 minutes);
return;
} else {
// transfer balance
contributions[contributionId[_newAddress]].amount = contributions[
contributionId[_oldAddress]
].amount;
contributions[contributionId[_oldAddress]].amount = 0;
// transfer approver account
approvers[_oldAddress] = false;
approvers[_newAddress] = true;
CampaignRewardLib._transferRewards(
campaignRewardContract,
_oldAddress,
_newAddress
);
emit CampaignUserDataTransferred(_oldAddress, _newAddress);
}
}
/**
* @dev Modifies campaign details
* @param _target Contribution target of the campaign
* @param _minimumContribution The minimum amout required to be an approver
* @param _duration How long until the campaign stops receiving contributions
* @param _goalType If flexible the campaign owner is able to create requests if targe isn't met, fixed opposite
* @param _token Address of token to be used for transactions by default
* @param _allowContributionAfterTargetIsMet Indicates if the campaign can receive contributions after the target is met
*/
function setCampaignSettings(
uint256 _target,
uint256 _minimumContribution,
uint256 _duration,
uint256 _goalType,
address _token,
bool _allowContributionAfterTargetIsMet
) external userTransferNotInTransit hasPermission(SET_CAMPAIGN_SETTINGS) {
require(approversCount < 1, "approvers found");
require(
_minimumContribution >=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"minimumContributionAllowed"
) &&
_minimumContribution <=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"maximumContributionAllowed"
),
"contribution deficit"
);
require(
_target >=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"minimumCampaignTarget"
) &&
_target <=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"maximumCampaignTarget"
),
"target deficit"
);
bool approved;
(, , approved) = campaignFactoryContract.tokens(_token);
require(approved, "invalid token");
bool campaignIsApproved;
(, campaignIsApproved) = CampaignFactoryLib.campaignInfo(
campaignFactoryContract,
this
);
require(!campaignIsApproved, "already approved");
target = _target;
minimumContribution = _minimumContribution;
deadline = block.timestamp.add(_duration);
acceptedToken = _token;
allowContributionAfterTargetIsMet = _allowContributionAfterTargetIsMet;
goalType = GOALTYPE(_goalType);
emit CampaignSettingsUpdated(
_target,
_minimumContribution,
_duration,
_goalType,
_token,
_allowContributionAfterTargetIsMet
);
}
/**
* @dev Extends campaign contribution deadline
* @param _time How long until the campaign stops receiving contributions
*/
function extendDeadline(uint256 _time)
external
hasPermission(EXTEND_DEADLINE)
userTransferNotInTransit
nonReentrant
whenNotPaused
{
require(block.timestamp > deadline);
require(
deadlineSetTimes <
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"deadlineStrikesAllowed"
),
"exhausted strikes"
);
require(
_time <=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"maxDeadlineExtension"
) &&
_time >=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"minDeadlineExtension"
),
"time deficit"
); // ensure time exceeds 7 days and less than a day
deadline = block.timestamp.add(_time);
// limit ability to increase deadlines
deadlineSetTimes = deadlineSetTimes.add(1);
emit CampaignDeadlineExtended(_time);
}
/**
* @dev Sets the number of times the campaign owner can extend deadlines.
* @param _count Number of times a campaign owner can extend the deadline
*/
function setDeadlineSetTimes(uint8 _count)
external
hasPermission(EXTEND_DEADLINE)
userTransferNotInTransit
whenNotPaused
{
deadlineSetTimes = _count;
emit DeadlineThresholdExtended(_count);
}
/**
* @dev Approves or unapproves a potential contributor
* @param _contributor Address of the potential contributor
*/
function toggleContributorApproval(address _contributor)
external
hasPermission(CONTRIBUTOR_APPROVAL)
{
require(_contributor != address(0));
if (allowedToContribute[_contributor]) {
// check there are no finalized requests
require(
campaignRequestContract.finalizedRequestCount() < 1,
"request finalized"
);
allowedToContribute[_contributor] = false;
} else {
allowedToContribute[_contributor] = true;
}
emit ContributorApprovalToggled(
_contributor,
allowedToContribute[_contributor]
);
}
/**
* @dev Contribute method enables a user become an approver in the campaign
* @param _token Address of token to be used for transactions by default
* @param _rewardId Reward unique id
* @param _withReward Indicates if the user wants a reward alongside their contribution
*/
function contribute(
address _token,
uint256 _rewardId,
bool _withReward
)
external
payable
userIsVerified(msg.sender)
userTransferNotInTransit
whenNotPaused
nonReentrant
{
// check if campaign is private, if it is check if user is approved contributor
bool privateCampaign;
(, privateCampaign) = CampaignFactoryLib.campaignInfo(
campaignFactoryContract,
this
);
if (privateCampaign) {
require(allowedToContribute[msg.sender], "not approved");
}
// campaign owner cannot contribute to own campaign
// token must be accepted
// contrubution amount must be less than or equal to allowed value from factory
require(block.timestamp <= deadline, "deadline expired");
require(msg.sender != root, "root owner");
require(_token == acceptedToken, "invalid token");
require(msg.value >= minimumContribution, "value low");
require(
msg.value <=
CampaignFactoryLib.getCampaignFactoryConfig(
campaignFactoryContract,
"maximumContributionAllowed"
),
"value high"
);
uint256 _rewardRecipientId;
if (!allowContributionAfterTargetIsMet) {
// check user contribution added to current total contribution doesn't exceed target
require(
totalCampaignContribution.add(msg.value) <= target,
"exceeds target"
);
}
if (_withReward) {
(_rewardRecipientId) = CampaignRewardLib._assignReward(
campaignRewardContract,
_rewardId,
msg.value,
msg.sender
);
}
if (!approvers[msg.sender]) {
approversCount = approversCount.add(1);
approvers[msg.sender] = true;
contributions.push(Contribution(msg.value, false));
contributionId[msg.sender] = contributions.length.sub(1);
}
totalCampaignContribution = totalCampaignContribution.add(msg.value);
campaignBalance = campaignBalance.add(msg.value);
contributions[contributionId[msg.sender]].amount = contributions[
contributionId[msg.sender]
].amount.add(msg.value);
// keep track of when target is met
if (totalCampaignContribution >= target) {
campaignState = CAMPAIGN_STATE.LIVE;
}
SafeERC20Upgradeable.safeTransferFrom(
IERC20Upgradeable(acceptedToken),
msg.sender,
address(this),
msg.value
);
emit ContributionMade(
contributionId[msg.sender],
msg.value,
_rewardId,
_rewardRecipientId,
_withReward
);
}
/**
* @dev Allows withdrawal of contribution by a user, works if campaign target isn't met
* @param _wallet Address where amount is delivered
*/
function withdrawContribution(address payable _wallet)
external
userTransferNotInTransit
nonReentrant
{
require(!withdrawalsPaused);
// if the campaign state is neither unsuccessful and in review and there are reviews
// allow withdrawls
require(address(_wallet) != address(0));
require(
!contributions[contributionId[msg.sender]].withdrawn,
"withdrawn"
);
require(approvers[msg.sender], "non approver");
if (
campaignState != CAMPAIGN_STATE.UNSUCCESSFUL &&
campaignState != CAMPAIGN_STATE.REVIEW &&
reviewCount < 1
) {
// pledge collection ongoing and no request was successful
require(
campaignState == CAMPAIGN_STATE.COLLECTION ||
campaignState == CAMPAIGN_STATE.LIVE,
"not in collection or live stage"
);
require(
campaignRequestContract.finalizedRequestCount() < 1,
"request(s) finalized"
);
}
uint256 maxBalance = contributions[contributionId[msg.sender]]
.amount
.sub(userContributionLoss(msg.sender));
// no longer eligible for any reward if campaign is not unsuccessful or in review
// for record keeping purposes
if (
campaignState != CAMPAIGN_STATE.UNSUCCESSFUL &&
campaignState != CAMPAIGN_STATE.REVIEW
) {
CampaignRewardLib._renounceRewards(
campaignRewardContract,
msg.sender
);
// decrement total contributions to campaign
campaignBalance = campaignBalance.sub(maxBalance);
totalCampaignContribution = totalCampaignContribution.sub(
maxBalance
);
// mark user as a non contributor
approvers[msg.sender] = false;
// reduce approvers count
approversCount = approversCount.sub(1);
contributions[contributionId[msg.sender]].amount = 0;
} else {
contributions[contributionId[msg.sender]].amount = contributions[
contributionId[msg.sender]
].amount.sub(maxBalance);
}
contributions[contributionId[msg.sender]].withdrawn = true;
// transfer to msg.sender
SafeERC20Upgradeable.safeTransfer(
IERC20Upgradeable(acceptedToken),
_wallet,
maxBalance
);
emit ContributionWithdrawn(
contributionId[msg.sender],
maxBalance,
msg.sender
);
}
/**
* @dev Used to measure user funds left after request finalization
* @param _user Address of user check is carried out on
*/
function userContributionLoss(address _user) public view returns (uint256) {
require(!contributions[contributionId[_user]].withdrawn, "withdrawn");
// calculate % loss between totalCampaginContribution and campaginBalance
DecimalMath.UFixed memory percentTakenSoFar = DecimalMath.muld(
DecimalMath.divd(
totalCampaignContribution.sub(campaignBalance),
totalCampaignContribution
),
percent
);
// calculate % loss of userBalance and subtract loss
uint256 userLoss = DecimalMath.muldrup(
contributions[contributionId[_user]].amount,
DecimalMath.divd(percentTakenSoFar, percent)
);
return userLoss;
}
/**
* @dev Withdrawal method called only when a request receives the right amount of votes
* @param _requestId ID of request being withdrawn
*/
function finalizeRequest(uint256 _requestId)
external
hasPermission(FINALIZE_REQUEST)
userTransferNotInTransit
whenNotPaused
nonReentrant
{
uint256 requestValue;
(, requestValue, , , , , , , ) = campaignRequestContract.requests(
_requestId
);
campaignBalance = campaignBalance.sub(requestValue);
campaignRequestContract.signRequestFinalization(_requestId);
emit RequestComplete(_requestId);
}
/// @dev Pauses the campaign and switches `campaignState` to `REVIEW` indicating it's ready to be reviewd by it's approvers after the campaign is over
function markReviewMode()
external
hasPermission(REVIEW_MODE)
userTransferNotInTransit
whenNotPaused
{
// ensure finalized requests is more than or equal to 1
// ensure no pending request
// ensure campaign state is running
bool requestComplete;
(, , , , , , , requestComplete, ) = campaignRequestContract.requests(
campaignRequestContract.currentRunningRequest()
);
require(
campaignState == CAMPAIGN_STATE.LIVE ||
campaignState == CAMPAIGN_STATE.COLLECTION,
"not ongoing"
);
require(
campaignRequestContract.finalizedRequestCount() >= 1,
"no finalized requests"
);
require(requestComplete, "request ongoing");
campaignState = CAMPAIGN_STATE.REVIEW;
_pause();
emit CampaignStateChange(CAMPAIGN_STATE.REVIEW);
}
/**
* @dev User acknowledgement of review state enabled by the campaign owner
* @param _hashedReview CID reference of the review on IPFS
*/
function reviewCampaignPerformance(string memory _hashedReview)
external
userTransferNotInTransit
userIsVerified(msg.sender)
whenPaused
{
require(campaignState == CAMPAIGN_STATE.REVIEW, "not in review");
require(!reviewed[msg.sender], "reviewed");
require(approvers[msg.sender], "non approver");
reviewed[msg.sender] = true;
reviewHash[msg.sender] = _hashedReview;
reviewCount = reviewCount.add(1);
emit CampaignReviewed(msg.sender, _hashedReview);
}
/// @dev Called by campaign manager to mark the campaign as complete right after it secured enough reviews from users
function markCampaignComplete()
external
hasPermission(MARK_CAMPAIGN_COMPLETE)
userTransferNotInTransit
whenPaused
{
// check if reviewers count > 80% of approvers set campaign state to complete
DecimalMath.UFixed memory percentOfApprovals = DecimalMath.muld(
DecimalMath.divd(
DecimalMath.toUFixed(reviewCount),
DecimalMath.toUFixed(approversCount)
),
percent
);
require(campaignState == CAMPAIGN_STATE.REVIEW, "not in review");
require(
percentOfApprovals.value >=
CampaignFactoryLib
.getCampaignFactoryConfig(
campaignFactoryContract,
"reviewThresholdMark"
)
.mul(DecimalMath.UNIT),
"review deficit"
);
campaignState = CAMPAIGN_STATE.COMPLETE;
emit CampaignStateChange(CAMPAIGN_STATE.COMPLETE);
}
/**
* @dev Called by an approver to report a campaign. Campaign must be in collection or live state
* @param _hashedReport CID reference of the report on IPFS
*/
function reportCampaign(string memory _hashedReport)
external
userTransferNotInTransit
userIsVerified(msg.sender)
whenNotPaused
{
require(campaignRequestContract.requestCount() >= 1, "no requests");
require(approvers[msg.sender], "non approver");
require(
campaignState == CAMPAIGN_STATE.COLLECTION ||
campaignState == CAMPAIGN_STATE.LIVE,
"not in collection or live state"
);
require(!reported[msg.sender], "reported");
reported[msg.sender] = true;
reportHash[msg.sender] = _hashedReport;
reportCount = reportCount.add(1);
DecimalMath.UFixed memory percentOfReports = DecimalMath.muld(
DecimalMath.divd(
DecimalMath.toUFixed(reportCount),
DecimalMath.toUFixed(approversCount)
),
percent
);
if (
percentOfReports.value >=
CampaignFactoryLib
.getCampaignFactoryConfig(
campaignFactoryContract,
"reportThresholdMark"
)
.mul(DecimalMath.UNIT)
) {
campaignState = CAMPAIGN_STATE.UNSUCCESSFUL;
emit CampaignStateChange(campaignState);
_pause();
}
emit CampaignReported(msg.sender, _hashedReport);
}
/**
* @dev Sets the campaign state
* @param _state Indicates pause or unpause state
*/
function setCampaignState(uint256 _state) external onlyFactory {
campaignState = CAMPAIGN_STATE(_state);
emit CampaignStateChange(campaignState);
}
/**
* @dev Pauses or Unpauses withdrawals depending on state passed in argument
* @param _state Indicates pause or unpause state
*/
function toggleWithdrawalState(bool _state) external onlyFactory {
withdrawalsPaused = _state;
emit WithdrawalStateUpdated(_state);
}
/// @dev Unpauses the campaign, transactions in the campaign resume per usual
function unpauseCampaign() external whenPaused onlyFactory {
_unpause();
}
/// @dev Pauses the campaign, it halts all transactions in the campaign
function pauseCampaign() external whenNotPaused onlyFactory {
_pause();
}
}
|
Sets the campaign state _state Indicates pause or unpause state/
|
function setCampaignState(uint256 _state) external onlyFactory {
campaignState = CAMPAIGN_STATE(_state);
emit CampaignStateChange(campaignState);
}
| 5,451,834 |
pragma solidity >=0.4.24;
import "./modules/DataType.sol";
/**
* @title RAC (Role Access Control)
*/
contract RAC is DataType {
//(action => operator => permission), action recommend use string(business directive)
mapping(bytes32=>mapping (address => bool)) roles;
//(action => operator => permission), action recommend use string(business directive)
mapping(bytes32=>mapping (address => bool)) privateRoles;
event AddRole(address _operator, bytes32 _action);
event RemoveRole(address _operator, bytes32 _action);
event AddPrivateRole(address _operator, bytes32 _action);
event RemovePrivateRole(address _operator, bytes32 _action);
constructor () public {
roles[stringToBytes32("manageRole")][msg.sender] = true;
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param _action the name of the role
* // reverts
*/
modifier onlyRole(string _action)
{
require(checkRole(msg.sender, stringToBytes32(_action)), "Permission deny");
_;
}
/**
* check permission
* @param _operator address of operator
* @param _action the name of the role
*/
function checkRole(address _operator, bytes32 _action) public view returns (bool) {
return roles[_action][_operator];
}
/**
* @dev add a role to an address
* @param _operator address of operator
* @param _action the name of the role
*/
function addRole(address _operator, bytes32 _action) public onlyRole("manageRole") {
roles[_action][_operator] = true;
emit AddRole(_operator, _action);
}
/**
* @dev add roles to an address
* @param _operator address of operator
* @param _actions the name of the role
*/
function batchAddRole(address _operator, bytes32[] _actions) public onlyRole("manageRole") {
for(uint256 i; i<_actions.length; i++) {
addRole(_operator, _actions[i]);
}
}
/**
* @dev remove a role from an address
* @param _operator address of operator
* @param _action the name of the role
*/
function removeRole(address _operator, bytes32 _action) public onlyRole("manageRole") {
if(_operator == msg.sender && _action == stringToBytes32("manageRole")) {
revert("can not remove it if operator there is manageRole");
}
roles[_action][_operator] = false;
emit RemoveRole(_operator, _action);
}
/**
* @dev remove roles from an address
* @param _operator address of operator
* @param _actions the name of the role
*/
function batchRemoveRole(address _operator, bytes32[] _actions) public onlyRole("manageRole") {
for(uint256 i; i<_actions.length; i++) {
removeRole(_operator, _actions[i]);
}
}
/**
* check permission
* @param _action the name of the role
*/
function checkPrivateRole(bytes32 _action) public view returns (bool) {
return privateRoles[_action][msg.sender];
}
/**
* @dev add a private role to an address
* @param _action the name of the role
*/
function addPrivateRole(bytes32 _action) public {
privateRoles[_action][msg.sender] = true;
emit AddPrivateRole(msg.sender, _action);
}
/**
* @dev add private role to an address
* @param _actions the name of the role
*/
function batchAddPrivateRole(bytes32 _actions) public {
for(uint256 i; i<_actions.length; i++) {
addPrivateRole(_actions[i]);
}
}
/**
* @dev remove a private role to an address
* @param _action the name of the role
*/
function removePrivateRole(bytes32 _action) public {
privateRoles[_action][msg.sender] = false;
emit RemovePrivateRole(msg.sender, _action);
}
/**
* @dev remove private role to an address
* @param _actions the name of the role
*/
function batchRemovePrivateRole(bytes32 _actions) public {
for(uint256 i; i<_actions.length; i++) {
removePrivateRole(_actions[i]);
}
}
}
|
check permission _operator address of operator _action the name of the role/
|
function checkRole(address _operator, bytes32 _action) public view returns (bool) {
return roles[_action][_operator];
}
| 1,043,884 |
pragma solidity ^0.4.13;
contract Randomized {
struct Key {
uint entryBlockNumber;
bytes32 publicKey;
}
mapping (address => Key[]) keys;
function setKey(bytes32 publicKey) public {
Key[] storage senderKeys = keys[msg.sender];
require(senderKeys.length == 0 || senderKeys[senderKeys.length-1].entryBlockNumber < block.number);
senderKeys.push(Key(block.number, publicKey));
}
function validate(uint seedBlockNumber, bytes32 seed, address sender, bytes32 crypted, bytes32 result) constant public returns (bool) {
if (keccak256(crypted, seed) != result)
return false;
Key memory key = findKey(keys[sender], seedBlockNumber);
if (key.entryBlockNumber >= seedBlockNumber)
return false;
return keccak256(seed) == privatized(crypted, key.publicKey);
}
function findKey(Key[] addressKeys, uint seedBlockNumber) constant private returns (Key) {
uint x = addressKeys.length;
//TODO: These are in order => use binary search
while (x > 0) {
x -= 1;
if (seedBlockNumber > addressKeys[x].entryBlockNumber) {
return addressKeys[x];
}
}
return Key(0, 0x0);
}
function privatized(bytes32 crypted, bytes32 publicKey) constant private returns (bytes32) {
// Waiting for https://github.com/ethereum/EIPs/pull/198
// And specifically this from geth (and same from other clients):
// https://github.com/ethereum/go-ethereum/blob/104375f398bdfca88183010cc3693e377ea74163/core/vm/contracts.go#L56
// For now using just a simple bitwise xor to get the bidirectional mapping for testing
return crypted ^ publicKey;
}
function modexp(bytes memory _base, bytes memory _exp, bytes memory _mod) constant returns(bytes) {
uint256 bl = _base.length;
uint256 el = _exp.length;
uint256 ml = _mod.length;
assembly {
// Free memory pointer is always stored at 0x40
let freemem := mload(0x40)
// arg[0] = base.length @ +0
mstore(freemem, bl)
// arg[1] = exp.length @ +32
mstore(add(freemem,32), el)
// arg[2] = mod.length @ +64
mstore(add(freemem,64), ml)
// arg[3] = base.bits @ + 96
// Use identity built-in (contract 0x4) as a cheap memcpy
let retval := call(450, 0x4, 0, add(_base,32), bl, add(freemem,96), bl)
// arg[4] = exp.bits @ +96+base.length
let size := add(96, bl)
retval := call(450, 0x4, 0, add(_exp,32), el, add(freemem,size), el)
// arg[5] = mod.bits @ +96+base.length+exp.length
size := add(size,el)
retval := call(450, 0x4, 0, add(_mod,32), ml, add(freemem,size), ml)
// Total size of input = 96+base.length+exp.length+mod.length
size := add(size,ml)
// Invoke contract 0x5, put return value right after mod.length, @ +96
retval := call(sub(gas, 1350), 0x5, 0, freemem, size, add(96,freemem), ml)
// Prepare return value (offset, length, bits) by reusing mod.length @ +64
freemem := add(32,freemem)
// Store offset to array (32) @ +0. Note that mod.length is now at @ +32
mstore(freemem, 32)
// Total size of output = 64+mod.length
return(freemem, add(64,ml))
}
}
}
|
Waiting for https:github.com/ethereum/EIPs/pull/198 And specifically this from geth (and same from other clients): https:github.com/ethereum/go-ethereum/blob/104375f398bdfca88183010cc3693e377ea74163/core/vm/contracts.goL56 For now using just a simple bitwise xor to get the bidirectional mapping for testing
|
function privatized(bytes32 crypted, bytes32 publicKey) constant private returns (bytes32) {
return crypted ^ publicKey;
}
| 12,589,546 |
//Address: 0x3e516824a408c7029c3f870510d59442143c2db9
//Contract name: Version
//Balance: 0 Ether
//Verification Date: 2/23/2018
//Transacion Count: 2
// CODE STARTS HERE
pragma solidity ^0.4.13;
interface FundInterface {
// EVENTS
event PortfolioContent(uint holdings, uint price, uint decimals);
event RequestUpdated(uint id);
event Invested(address indexed ofParticipant, uint atTimestamp, uint shareQuantity);
event Redeemed(address indexed ofParticipant, uint atTimestamp, uint shareQuantity);
event SpendingApproved(address onConsigned, address ofAsset, uint amount);
event FeesConverted(uint atTimestamp, uint shareQuantityConverted, uint unclaimed);
event CalculationUpdate(uint atTimestamp, uint managementFee, uint performanceFee, uint nav, uint sharePrice, uint totalSupply);
event OrderUpdated(uint id);
event LogError(uint ERROR_CODE);
event ErrorMessage(string errorMessage);
// EXTERNAL METHODS
// Compliance by Investor
function requestInvestment(uint giveQuantity, uint shareQuantity, bool isNativeAsset) external;
function requestRedemption(uint shareQuantity, uint receiveQuantity, bool isNativeAsset) external;
function executeRequest(uint requestId) external;
function cancelRequest(uint requestId) external;
function redeemAllOwnedAssets(uint shareQuantity) external returns (bool);
// Administration by Manager
function enableInvestment() external;
function disableInvestment() external;
function enableRedemption() external;
function disableRedemption() external;
function shutDown() external;
// Managing by Manager
function makeOrder(uint exchangeId, address sellAsset, address buyAsset, uint sellQuantity, uint buyQuantity) external;
function takeOrder(uint exchangeId, uint id, uint quantity) external;
function cancelOrder(uint exchangeId, uint id) external;
// PUBLIC METHODS
function emergencyRedeem(uint shareQuantity, address[] requestedAssets) public returns (bool success);
function calcSharePriceAndAllocateFees() public returns (uint);
// PUBLIC VIEW METHODS
// Get general information
function getModules() view returns (address, address, address);
function getLastOrderId() view returns (uint);
function getLastRequestId() view returns (uint);
function getNameHash() view returns (bytes32);
function getManager() view returns (address);
// Get accounting information
function performCalculations() view returns (uint, uint, uint, uint, uint, uint, uint);
function calcSharePrice() view returns (uint);
}
interface AssetInterface {
/*
* Implements ERC 20 standard.
* https://github.com/ethereum/EIPs/blob/f90864a3d2b2b45c4decf95efd26b3f0c276051a/EIPS/eip-20-token-standard.md
* https://github.com/ethereum/EIPs/issues/20
*
* Added support for the ERC 223 "tokenFallback" method in a "transfer" function with a payload.
* https://github.com/ethereum/EIPs/issues/223
*/
// Events
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
// There is no ERC223 compatible Transfer event, with `_data` included.
//ERC 223
// PUBLIC METHODS
function transfer(address _to, uint _value, bytes _data) public returns (bool success);
// ERC 20
// PUBLIC METHODS
function transfer(address _to, uint _value) public returns (bool success);
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
function approve(address _spender, uint _value) public returns (bool success);
// PUBLIC VIEW METHODS
function balanceOf(address _owner) view public returns (uint balance);
function allowance(address _owner, address _spender) public view returns (uint remaining);
}
interface ERC223Interface {
function balanceOf(address who) constant returns (uint);
function transfer(address to, uint value) returns (bool);
function transfer(address to, uint value, bytes data) returns (bool);
event Transfer(address indexed from, address indexed to, uint value, bytes data);
}
interface ERC223ReceivingContract {
/// @dev Function that is called when a user or another contract wants to transfer funds.
/// @param _from Transaction initiator, analogue of msg.sender
/// @param _value Number of tokens to transfer.
/// @param _data Data containing a function signature and/or parameters
function tokenFallback(address _from, uint256 _value, bytes _data) public;
}
interface NativeAssetInterface {
// PUBLIC METHODS
function deposit() public payable;
function withdraw(uint wad) public;
}
interface SharesInterface {
event Created(address indexed ofParticipant, uint atTimestamp, uint shareQuantity);
event Annihilated(address indexed ofParticipant, uint atTimestamp, uint shareQuantity);
// VIEW METHODS
function getName() view returns (string);
function getSymbol() view returns (string);
function getDecimals() view returns (uint);
function getCreationTime() view returns (uint);
function toSmallestShareUnit(uint quantity) view returns (uint);
function toWholeShareUnit(uint quantity) view returns (uint);
}
interface ComplianceInterface {
// PUBLIC VIEW METHODS
/// @notice Checks whether investment is permitted for a participant
/// @param ofParticipant Address requesting to invest in a Melon fund
/// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity
/// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received
/// @return Whether identity is eligible to invest in a Melon fund.
function isInvestmentPermitted(
address ofParticipant,
uint256 giveQuantity,
uint256 shareQuantity
) view returns (bool);
/// @notice Checks whether redemption is permitted for a participant
/// @param ofParticipant Address requesting to redeem from a Melon fund
/// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem
/// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity
/// @return Whether identity is eligible to redeem from a Melon fund.
function isRedemptionPermitted(
address ofParticipant,
uint256 shareQuantity,
uint256 receiveQuantity
) view returns (bool);
}
contract DBC {
// MODIFIERS
modifier pre_cond(bool condition) {
require(condition);
_;
}
modifier post_cond(bool condition) {
_;
assert(condition);
}
modifier invariant(bool condition) {
require(condition);
_;
assert(condition);
}
}
contract Owned is DBC {
// FIELDS
address public owner;
// NON-CONSTANT METHODS
function Owned() { owner = msg.sender; }
function changeOwner(address ofNewOwner) pre_cond(isOwner()) { owner = ofNewOwner; }
// PRE, POST, INVARIANT CONDITIONS
function isOwner() internal returns (bool) { return msg.sender == owner; }
}
interface ExchangeInterface {
// EVENTS
event OrderUpdated(uint id);
// METHODS
// EXTERNAL METHODS
function makeOrder(
address onExchange,
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
) external returns (uint);
function takeOrder(address onExchange, uint id, uint quantity) external returns (bool);
function cancelOrder(address onExchange, uint id) external returns (bool);
// PUBLIC METHODS
// PUBLIC VIEW METHODS
function isApproveOnly() view returns (bool);
function getLastOrderId(address onExchange) view returns (uint);
function isActive(address onExchange, uint id) view returns (bool);
function getOwner(address onExchange, uint id) view returns (address);
function getOrder(address onExchange, uint id) view returns (address, address, uint, uint);
function getTimestamp(address onExchange, uint id) view returns (uint);
}
interface PriceFeedInterface {
// EVENTS
event PriceUpdated(uint timestamp);
// PUBLIC METHODS
function update(address[] ofAssets, uint[] newPrices);
// PUBLIC VIEW METHODS
// Get asset specific information
function getName(address ofAsset) view returns (string);
function getSymbol(address ofAsset) view returns (string);
function getDecimals(address ofAsset) view returns (uint);
// Get price feed operation specific information
function getQuoteAsset() view returns (address);
function getInterval() view returns (uint);
function getValidity() view returns (uint);
function getLastUpdateId() view returns (uint);
// Get asset specific information as updated in price feed
function hasRecentPrice(address ofAsset) view returns (bool isRecent);
function hasRecentPrices(address[] ofAssets) view returns (bool areRecent);
function getPrice(address ofAsset) view returns (bool isRecent, uint price, uint decimal);
function getPrices(address[] ofAssets) view returns (bool areRecent, uint[] prices, uint[] decimals);
function getInvertedPrice(address ofAsset) view returns (bool isRecent, uint invertedPrice, uint decimal);
function getReferencePrice(address ofBase, address ofQuote) view returns (bool isRecent, uint referencePrice, uint decimal);
function getOrderPrice(
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
) view returns (uint orderPrice);
function existsPriceOnAssetPair(address sellAsset, address buyAsset) view returns (bool isExistent);
}
interface RiskMgmtInterface {
// METHODS
// PUBLIC VIEW METHODS
/// @notice Checks if the makeOrder price is reasonable and not manipulative
/// @param orderPrice Price of Order
/// @param referencePrice Reference price obtained through PriceFeed contract
/// @param sellAsset Asset (as registered in Asset registrar) to be sold
/// @param buyAsset Asset (as registered in Asset registrar) to be bought
/// @param sellQuantity Quantity of sellAsset to be sold
/// @param buyQuantity Quantity of buyAsset to be bought
/// @return If makeOrder is permitted
function isMakePermitted(
uint orderPrice,
uint referencePrice,
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
) view returns (bool);
/// @notice Checks if the takeOrder price is reasonable and not manipulative
/// @param orderPrice Price of Order
/// @param referencePrice Reference price obtained through PriceFeed contract
/// @param sellAsset Asset (as registered in Asset registrar) to be sold
/// @param buyAsset Asset (as registered in Asset registrar) to be bought
/// @param sellQuantity Quantity of sellAsset to be sold
/// @param buyQuantity Quantity of buyAsset to be bought
/// @return If takeOrder is permitted
function isTakePermitted(
uint orderPrice,
uint referencePrice,
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
) view returns (bool);
}
interface VersionInterface {
// EVENTS
event FundUpdated(uint id);
// PUBLIC METHODS
function shutDown() external;
function setupFund(
string ofFundName,
address ofQuoteAsset,
uint ofManagementFee,
uint ofPerformanceFee,
address ofCompliance,
address ofRiskMgmt,
address ofPriceFeed,
address[] ofExchanges,
address[] ofExchangeAdapters,
uint8 v,
bytes32 r,
bytes32 s
);
function shutDownFund(address ofFund);
// PUBLIC VIEW METHODS
function getNativeAsset() view returns (address);
function getFundById(uint withId) view returns (address);
function getLastFundId() view returns (uint);
function getFundByManager(address ofManager) view returns (address);
function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed);
}
contract Version is DBC, Owned, VersionInterface {
// FIELDS
// Constant fields
bytes32 public constant TERMS_AND_CONDITIONS = 0x47173285a8d7341e5e972fc677286384f802f8ef42a5ec5f03bbfa254cb01fad; // Hashed terms and conditions as displayed on IPFS.
// Constructor fields
string public VERSION_NUMBER; // SemVer of Melon protocol version
address public NATIVE_ASSET; // Address of wrapped native asset contract
address public GOVERNANCE; // Address of Melon protocol governance contract
// Methods fields
bool public isShutDown; // Governance feature, if yes than setupFund gets blocked and shutDownFund gets opened
address[] public listOfFunds; // A complete list of fund addresses created using this version
mapping (address => address) public managerToFunds; // Links manager address to fund address created using this version
// EVENTS
event FundUpdated(address ofFund);
// METHODS
// CONSTRUCTOR
/// @param versionNumber SemVer of Melon protocol version
/// @param ofGovernance Address of Melon governance contract
/// @param ofNativeAsset Address of wrapped native asset contract
function Version(
string versionNumber,
address ofGovernance,
address ofNativeAsset
) {
VERSION_NUMBER = versionNumber;
GOVERNANCE = ofGovernance;
NATIVE_ASSET = ofNativeAsset;
}
// EXTERNAL METHODS
function shutDown() external pre_cond(msg.sender == GOVERNANCE) { isShutDown = true; }
// PUBLIC METHODS
/// @param ofFundName human-readable descriptive name (not necessarily unique)
/// @param ofQuoteAsset Asset against which performance fee is measured against
/// @param ofManagementFee A time based fee, given in a number which is divided by 10 ** 15
/// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 10 ** 15
/// @param ofCompliance Address of participation module
/// @param ofRiskMgmt Address of risk management module
/// @param ofPriceFeed Address of price feed module
/// @param ofExchanges Addresses of exchange on which this fund can trade
/// @param ofExchangeAdapters Addresses of exchange adapters
/// @param v ellipitc curve parameter v
/// @param r ellipitc curve parameter r
/// @param s ellipitc curve parameter s
function setupFund(
string ofFundName,
address ofQuoteAsset,
uint ofManagementFee,
uint ofPerformanceFee,
address ofCompliance,
address ofRiskMgmt,
address ofPriceFeed,
address[] ofExchanges,
address[] ofExchangeAdapters,
uint8 v,
bytes32 r,
bytes32 s
) {
require(!isShutDown);
require(termsAndConditionsAreSigned(v, r, s));
// Either novel fund name or previous owner of fund name
require(managerToFunds[msg.sender] == 0); // Add limitation for simpler migration process of shutting down and setting up fund
address ofFund = new Fund(
msg.sender,
ofFundName,
ofQuoteAsset,
ofManagementFee,
ofPerformanceFee,
NATIVE_ASSET,
ofCompliance,
ofRiskMgmt,
ofPriceFeed,
ofExchanges,
ofExchangeAdapters
);
listOfFunds.push(ofFund);
managerToFunds[msg.sender] = ofFund;
FundUpdated(ofFund);
}
/// @dev Dereference Fund and trigger selfdestruct
/// @param ofFund Address of the fund to be shut down
function shutDownFund(address ofFund)
pre_cond(isShutDown || managerToFunds[msg.sender] == ofFund)
{
Fund fund = Fund(ofFund);
delete managerToFunds[msg.sender];
fund.shutDown();
FundUpdated(ofFund);
}
// PUBLIC VIEW METHODS
/// @dev Proof that terms and conditions have been read and understood
/// @param v ellipitc curve parameter v
/// @param r ellipitc curve parameter r
/// @param s ellipitc curve parameter s
/// @return signed Whether or not terms and conditions have been read and understood
function termsAndConditionsAreSigned(uint8 v, bytes32 r, bytes32 s) view returns (bool signed) {
return ecrecover(
// Parity does prepend \x19Ethereum Signed Message:\n{len(message)} before signing.
// Signature order has also been changed in 1.6.7 and upcoming 1.7.x,
// it will return rsv (same as geth; where v is [27, 28]).
// Note that if you are using ecrecover, v will be either "00" or "01".
// As a result, in order to use this value, you will have to parse it to an
// integer and then add 27. This will result in either a 27 or a 28.
// https://github.com/ethereum/wiki/wiki/JavaScript-API#web3ethsign
keccak256("\x19Ethereum Signed Message:\n32", TERMS_AND_CONDITIONS),
v,
r,
s
) == msg.sender; // Has sender signed TERMS_AND_CONDITIONS
}
function getNativeAsset() view returns (address) { return NATIVE_ASSET; }
function getFundById(uint withId) view returns (address) { return listOfFunds[withId]; }
function getLastFundId() view returns (uint) { return listOfFunds.length - 1; }
function getFundByManager(address ofManager) view returns (address) { return managerToFunds[ofManager]; }
}
contract DSMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function min(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function max(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function imin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function imax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = rmul(x, x);
if (n % 2 != 0) {
z = rmul(z, x);
}
}
}
}
contract Asset is DSMath, AssetInterface, ERC223Interface {
// DATA STRUCTURES
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
uint public totalSupply;
// PUBLIC METHODS
/**
* @notice Send `_value` tokens to `_to` from `msg.sender`
* @dev Transfers sender's tokens to a given address
* @dev Similar to transfer(address, uint, bytes), but without _data parameter
* @param _to Address of token receiver
* @param _value Number of tokens to transfer
* @return Returns success of function call
*/
function transfer(address _to, uint _value)
public
returns (bool success)
{
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly.
codeLength := extcodesize(_to)
}
require(balances[msg.sender] >= _value); // sanity checks
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
// if (codeLength > 0) {
// ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
// receiver.tokenFallback(msg.sender, _value, empty);
// }
Transfer(msg.sender, _to, _value, empty);
return true;
}
/**
* @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract
* @dev Function that is called when a user or contract wants to transfer funds
* @param _to Address of token receiver
* @param _value Number of tokens to transfer
* @param _data Data to be sent to tokenFallback
* @return Returns success of function call
*/
function transfer(address _to, uint _value, bytes _data)
public
returns (bool success)
{
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly.
codeLength := extcodesize(_to)
}
require(balances[msg.sender] >= _value); // sanity checks
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
// if (codeLength > 0) {
// ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
// receiver.tokenFallback(msg.sender, _value, _data);
// }
Transfer(msg.sender, _to, _value);
return true;
}
/// @notice Transfer `_value` tokens from `_from` to `_to` if `msg.sender` is allowed.
/// @notice Restriction: An account can only use this function to send to itself
/// @dev Allows for an approved third party to transfer tokens from one
/// address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
/// @return Returns success of function call.
function transferFrom(address _from, address _to, uint _value)
public
returns (bool)
{
require(_from != 0x0);
require(_to != 0x0);
require(_to != address(this));
require(balances[_from] >= _value);
require(allowed[_from][msg.sender] >= _value);
require(balances[_to] + _value >= balances[_to]);
// require(_to == msg.sender); // can only use transferFrom to send to self
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
Transfer(_from, _to, _value);
return true;
}
/// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address.
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
/// @return Returns success of function call.
function approve(address _spender, uint _value) public returns (bool) {
require(_spender != 0x0);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
// require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
// PUBLIC VIEW METHODS
/// @dev Returns number of allowed tokens that a spender can transfer on
/// behalf of a token owner.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
/// @return Returns remaining allowance for spender.
function allowance(address _owner, address _spender)
constant
public
returns (uint)
{
return allowed[_owner][_spender];
}
/// @dev Returns number of tokens owned by the given address.
/// @param _owner Address of token owner.
/// @return Returns balance of owner.
function balanceOf(address _owner) constant public returns (uint) {
return balances[_owner];
}
}
contract Shares is Asset, SharesInterface {
// FIELDS
// Constructor fields
string public name;
string public symbol;
uint public decimal;
uint public creationTime;
// METHODS
// CONSTRUCTOR
/// @param _name Name these shares
/// @param _symbol Symbol of shares
/// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract
/// @param _creationTime Timestamp of share creation
function Shares(string _name, string _symbol, uint _decimal, uint _creationTime) {
name = _name;
symbol = _symbol;
decimal = _decimal;
creationTime = _creationTime;
}
// PUBLIC METHODS
// PUBLIC VIEW METHODS
function getName() view returns (string) { return name; }
function getSymbol() view returns (string) { return symbol; }
function getDecimals() view returns (uint) { return decimal; }
function getCreationTime() view returns (uint) { return creationTime; }
function toSmallestShareUnit(uint quantity) view returns (uint) { return mul(quantity, 10 ** getDecimals()); }
function toWholeShareUnit(uint quantity) view returns (uint) { return quantity / (10 ** getDecimals()); }
function transfer(address _to, uint256 _value) public returns (bool) { require(_to == address(this)); }
function transfer(address _to, uint256 _value, bytes _data) public returns (bool) { require(_to == address(this)); }
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to == address(this)); }
// INTERNAL METHODS
/// @param recipient Address the new shares should be sent to
/// @param shareQuantity Number of shares to be created
function createShares(address recipient, uint shareQuantity) internal {
totalSupply = add(totalSupply, shareQuantity);
balances[recipient] = add(balances[recipient], shareQuantity);
Created(msg.sender, now, shareQuantity);
}
/// @param recipient Address the new shares should be taken from when destroyed
/// @param shareQuantity Number of shares to be annihilated
function annihilateShares(address recipient, uint shareQuantity) internal {
totalSupply = sub(totalSupply, shareQuantity);
balances[recipient] = sub(balances[recipient], shareQuantity);
Annihilated(msg.sender, now, shareQuantity);
}
}
contract RestrictedShares is Shares {
// CONSTRUCTOR
/// @param _name Name these shares
/// @param _symbol Symbol of shares
/// @param _decimal Amount of decimals sharePrice is denominated in, defined to be equal as deciamls in REFERENCE_ASSET contract
/// @param _creationTime Timestamp of share creation
function RestrictedShares(
string _name,
string _symbol,
uint _decimal,
uint _creationTime
) Shares(_name, _symbol, _decimal, _creationTime) {}
// PUBLIC METHODS
/**
* @notice Send `_value` tokens to `_to` from `msg.sender`
* @dev Transfers sender's tokens to a given address
* @dev Similar to transfer(address, uint, bytes), but without _data parameter
* @param _to Address of token receiver
* @param _value Number of tokens to transfer
* @return Returns success of function call
*/
function transfer(address _to, uint _value)
public
returns (bool success)
{
require(msg.sender == address(this) || _to == address(this));
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly.
codeLength := extcodesize(_to)
}
require(balances[msg.sender] >= _value); // sanity checks
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
Transfer(msg.sender, _to, _value, empty);
return true;
}
/**
* @notice Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract
* @dev Function that is called when a user or contract wants to transfer funds
* @param _to Address of token receiver
* @param _value Number of tokens to transfer
* @param _data Data to be sent to tokenFallback
* @return Returns success of function call
*/
function transfer(address _to, uint _value, bytes _data)
public
returns (bool success)
{
require(msg.sender == address(this) || _to == address(this));
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly.
codeLength := extcodesize(_to)
}
require(balances[msg.sender] >= _value); // sanity checks
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value);
return true;
}
/// @notice Allows `_spender` to transfer `_value` tokens from `msg.sender` to any address.
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
/// @return Returns success of function call.
function approve(address _spender, uint _value) public returns (bool) {
require(msg.sender == address(this));
require(_spender != 0x0);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(_value == 0 || allowed[msg.sender][_spender] == 0);
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
}
contract Fund is DSMath, DBC, Owned, RestrictedShares, FundInterface, ERC223ReceivingContract {
// TYPES
struct Modules { // Describes all modular parts, standardised through an interface
PriceFeedInterface pricefeed; // Provides all external data
ComplianceInterface compliance; // Boolean functions regarding invest/redeem
RiskMgmtInterface riskmgmt; // Boolean functions regarding make/take orders
}
struct Calculations { // List of internal calculations
uint gav; // Gross asset value
uint managementFee; // Time based fee
uint performanceFee; // Performance based fee measured against QUOTE_ASSET
uint unclaimedFees; // Fees not yet allocated to the fund manager
uint nav; // Net asset value
uint highWaterMark; // A record of best all-time fund performance
uint totalSupply; // Total supply of shares
uint timestamp; // Time when calculations are performed in seconds
}
enum RequestStatus { active, cancelled, executed }
enum RequestType { invest, redeem, tokenFallbackRedeem }
struct Request { // Describes and logs whenever asset enter and leave fund due to Participants
address participant; // Participant in Melon fund requesting investment or redemption
RequestStatus status; // Enum: active, cancelled, executed; Status of request
RequestType requestType; // Enum: invest, redeem, tokenFallbackRedeem
address requestAsset; // Address of the asset being requested
uint shareQuantity; // Quantity of Melon fund shares
uint giveQuantity; // Quantity in Melon asset to give to Melon fund to receive shareQuantity
uint receiveQuantity; // Quantity in Melon asset to receive from Melon fund for given shareQuantity
uint timestamp; // Time of request creation in seconds
uint atUpdateId; // Pricefeed updateId when this request was created
}
enum OrderStatus { active, partiallyFilled, fullyFilled, cancelled }
enum OrderType { make, take }
struct Order { // Describes and logs whenever assets enter and leave fund due to Manager
uint exchangeId; // Id as returned from exchange
OrderStatus status; // Enum: active, partiallyFilled, fullyFilled, cancelled
OrderType orderType; // Enum: make, take
address sellAsset; // Asset (as registered in Asset registrar) to be sold
address buyAsset; // Asset (as registered in Asset registrar) to be bought
uint sellQuantity; // Quantity of sellAsset to be sold
uint buyQuantity; // Quantity of sellAsset to be bought
uint timestamp; // Time of order creation in seconds
uint fillQuantity; // Buy quantity filled; Always less than buy_quantity
}
struct Exchange {
address exchange; // Address of the exchange
ExchangeInterface exchangeAdapter; //Exchange adapter contracts respective to the exchange
bool isApproveOnly; // True in case of exchange implementation which requires are approved when an order is made instead of transfer
}
// FIELDS
// Constant fields
uint public constant MAX_FUND_ASSETS = 4; // Max ownable assets by the fund supported by gas limits
// Constructor fields
uint public MANAGEMENT_FEE_RATE; // Fee rate in QUOTE_ASSET per delta improvement in WAD
uint public PERFORMANCE_FEE_RATE; // Fee rate in QUOTE_ASSET per managed seconds in WAD
address public VERSION; // Address of Version contract
Asset public QUOTE_ASSET; // QUOTE asset as ERC20 contract
NativeAssetInterface public NATIVE_ASSET; // Native asset as ERC20 contract
// Methods fields
Modules public module; // Struct which holds all the initialised module instances
Exchange[] public exchanges; // Array containing exchanges this fund supports
Calculations public atLastUnclaimedFeeAllocation; // Calculation results at last allocateUnclaimedFees() call
bool public isShutDown; // Security feature, if yes than investing, managing, allocateUnclaimedFees gets blocked
Request[] public requests; // All the requests this fund received from participants
bool public isInvestAllowed; // User option, if false fund rejects Melon investments
bool public isRedeemAllowed; // User option, if false fund rejects Melon redemptions; Redemptions using slices always possible
Order[] public orders; // All the orders this fund placed on exchanges
mapping (uint => mapping(address => uint)) public exchangeIdsToOpenMakeOrderIds; // exchangeIndex to: asset to open make order ID ; if no open make orders, orderID is zero
address[] public ownedAssets; // List of all assets owned by the fund or for which the fund has open make orders
mapping (address => bool) public isInAssetList; // Mapping from asset to whether the asset exists in ownedAssets
mapping (address => bool) public isInOpenMakeOrder; // Mapping from asset to whether the asset is in a open make order as buy asset
// METHODS
// CONSTRUCTOR
/// @dev Should only be called via Version.setupFund(..)
/// @param withName human-readable descriptive name (not necessarily unique)
/// @param ofQuoteAsset Asset against which mgmt and performance fee is measured against and which can be used to invest/redeem using this single asset
/// @param ofManagementFee A time based fee expressed, given in a number which is divided by 1 WAD
/// @param ofPerformanceFee A time performance based fee, performance relative to ofQuoteAsset, given in a number which is divided by 1 WAD
/// @param ofCompliance Address of compliance module
/// @param ofRiskMgmt Address of risk management module
/// @param ofPriceFeed Address of price feed module
/// @param ofExchanges Addresses of exchange on which this fund can trade
/// @param ofExchangeAdapters Addresses of exchange adapters
/// @return Deployed Fund with manager set as ofManager
function Fund(
address ofManager,
string withName,
address ofQuoteAsset,
uint ofManagementFee,
uint ofPerformanceFee,
address ofNativeAsset,
address ofCompliance,
address ofRiskMgmt,
address ofPriceFeed,
address[] ofExchanges,
address[] ofExchangeAdapters
)
RestrictedShares(withName, "MLNF", 18, now)
{
isInvestAllowed = true;
isRedeemAllowed = true;
owner = ofManager;
require(ofManagementFee < 10 ** 18); // Require management fee to be less than 100 percent
MANAGEMENT_FEE_RATE = ofManagementFee; // 1 percent is expressed as 0.01 * 10 ** 18
require(ofPerformanceFee < 10 ** 18); // Require performance fee to be less than 100 percent
PERFORMANCE_FEE_RATE = ofPerformanceFee; // 1 percent is expressed as 0.01 * 10 ** 18
VERSION = msg.sender;
module.compliance = ComplianceInterface(ofCompliance);
module.riskmgmt = RiskMgmtInterface(ofRiskMgmt);
module.pricefeed = PriceFeedInterface(ofPriceFeed);
// Bridged to Melon exchange interface by exchangeAdapter library
for (uint i = 0; i < ofExchanges.length; ++i) {
ExchangeInterface adapter = ExchangeInterface(ofExchangeAdapters[i]);
bool isApproveOnly = adapter.isApproveOnly();
exchanges.push(Exchange({
exchange: ofExchanges[i],
exchangeAdapter: adapter,
isApproveOnly: isApproveOnly
}));
}
// Require Quote assets exists in pricefeed
QUOTE_ASSET = Asset(ofQuoteAsset);
NATIVE_ASSET = NativeAssetInterface(ofNativeAsset);
// Quote Asset and Native asset always in owned assets list
ownedAssets.push(ofQuoteAsset);
isInAssetList[ofQuoteAsset] = true;
ownedAssets.push(ofNativeAsset);
isInAssetList[ofNativeAsset] = true;
require(address(QUOTE_ASSET) == module.pricefeed.getQuoteAsset()); // Sanity check
atLastUnclaimedFeeAllocation = Calculations({
gav: 0,
managementFee: 0,
performanceFee: 0,
unclaimedFees: 0,
nav: 0,
highWaterMark: 10 ** getDecimals(),
totalSupply: totalSupply,
timestamp: now
});
}
// EXTERNAL METHODS
// EXTERNAL : ADMINISTRATION
function enableInvestment() external pre_cond(isOwner()) { isInvestAllowed = true; }
function disableInvestment() external pre_cond(isOwner()) { isInvestAllowed = false; }
function enableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = true; }
function disableRedemption() external pre_cond(isOwner()) { isRedeemAllowed = false; }
function shutDown() external pre_cond(msg.sender == VERSION) { isShutDown = true; }
// EXTERNAL : PARTICIPATION
/// @notice Give melon tokens to receive shares of this fund
/// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices
/// @param giveQuantity Quantity of Melon token times 10 ** 18 offered to receive shareQuantity
/// @param shareQuantity Quantity of shares times 10 ** 18 requested to be received
function requestInvestment(
uint giveQuantity,
uint shareQuantity,
bool isNativeAsset
)
external
pre_cond(!isShutDown)
pre_cond(isInvestAllowed) // investment using Melon has not been deactivated by the Manager
pre_cond(module.compliance.isInvestmentPermitted(msg.sender, giveQuantity, shareQuantity)) // Compliance Module: Investment permitted
{
requests.push(Request({
participant: msg.sender,
status: RequestStatus.active,
requestType: RequestType.invest,
requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET),
shareQuantity: shareQuantity,
giveQuantity: giveQuantity,
receiveQuantity: shareQuantity,
timestamp: now,
atUpdateId: module.pricefeed.getLastUpdateId()
}));
RequestUpdated(getLastRequestId());
}
/// @notice Give shares of this fund to receive melon tokens
/// @dev Recommended to give some leeway in prices to account for possibly slightly changing prices
/// @param shareQuantity Quantity of shares times 10 ** 18 offered to redeem
/// @param receiveQuantity Quantity of Melon token times 10 ** 18 requested to receive for shareQuantity
function requestRedemption(
uint shareQuantity,
uint receiveQuantity,
bool isNativeAsset
)
external
pre_cond(!isShutDown)
pre_cond(isRedeemAllowed) // Redemption using Melon has not been deactivated by Manager
pre_cond(module.compliance.isRedemptionPermitted(msg.sender, shareQuantity, receiveQuantity)) // Compliance Module: Redemption permitted
{
requests.push(Request({
participant: msg.sender,
status: RequestStatus.active,
requestType: RequestType.redeem,
requestAsset: isNativeAsset ? address(NATIVE_ASSET) : address(QUOTE_ASSET),
shareQuantity: shareQuantity,
giveQuantity: shareQuantity,
receiveQuantity: receiveQuantity,
timestamp: now,
atUpdateId: module.pricefeed.getLastUpdateId()
}));
RequestUpdated(getLastRequestId());
}
/// @notice Executes active investment and redemption requests, in a way that minimises information advantages of investor
/// @dev Distributes melon and shares according to the request
/// @param id Index of request to be executed
/// @dev Active investment or redemption request executed
function executeRequest(uint id)
external
pre_cond(!isShutDown)
pre_cond(requests[id].status == RequestStatus.active)
pre_cond(requests[id].requestType != RequestType.redeem || requests[id].shareQuantity <= balances[requests[id].participant]) // request owner does not own enough shares
pre_cond(
totalSupply == 0 ||
(
now >= add(requests[id].timestamp, module.pricefeed.getInterval()) &&
module.pricefeed.getLastUpdateId() >= add(requests[id].atUpdateId, 2)
)
) // PriceFeed Module: Wait at least one interval time and two updates before continuing (unless it is the first investment)
{
Request request = requests[id];
// PriceFeed Module: No recent updates for fund asset list
require(module.pricefeed.hasRecentPrice(address(request.requestAsset)));
// sharePrice quoted in QUOTE_ASSET and multiplied by 10 ** fundDecimals
uint costQuantity = toWholeShareUnit(mul(request.shareQuantity, calcSharePriceAndAllocateFees())); // By definition quoteDecimals == fundDecimals
if (request.requestAsset == address(NATIVE_ASSET)) {
var (isPriceRecent, invertedNativeAssetPrice, nativeAssetDecimal) = module.pricefeed.getInvertedPrice(address(NATIVE_ASSET));
if (!isPriceRecent) {
revert();
}
costQuantity = mul(costQuantity, invertedNativeAssetPrice) / 10 ** nativeAssetDecimal;
}
if (
isInvestAllowed &&
request.requestType == RequestType.invest &&
costQuantity <= request.giveQuantity
) {
request.status = RequestStatus.executed;
assert(AssetInterface(request.requestAsset).transferFrom(request.participant, this, costQuantity)); // Allocate Value
createShares(request.participant, request.shareQuantity); // Accounting
} else if (
isRedeemAllowed &&
request.requestType == RequestType.redeem &&
request.receiveQuantity <= costQuantity
) {
request.status = RequestStatus.executed;
assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value
annihilateShares(request.participant, request.shareQuantity); // Accounting
} else if (
isRedeemAllowed &&
request.requestType == RequestType.tokenFallbackRedeem &&
request.receiveQuantity <= costQuantity
) {
request.status = RequestStatus.executed;
assert(AssetInterface(request.requestAsset).transfer(request.participant, costQuantity)); // Return value
annihilateShares(this, request.shareQuantity); // Accounting
} else {
revert(); // Invalid Request or invalid giveQuantity / receiveQuantity
}
}
/// @notice Cancels active investment and redemption requests
/// @param id Index of request to be executed
function cancelRequest(uint id)
external
pre_cond(requests[id].status == RequestStatus.active) // Request is active
pre_cond(requests[id].participant == msg.sender || isShutDown) // Either request creator or fund is shut down
{
requests[id].status = RequestStatus.cancelled;
}
/// @notice Redeems by allocating an ownership percentage of each asset to the participant
/// @dev Independent of running price feed!
/// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets
/// @return Whether all assets sent to shareholder or not
function redeemAllOwnedAssets(uint shareQuantity)
external
returns (bool success)
{
return emergencyRedeem(shareQuantity, ownedAssets);
}
// EXTERNAL : MANAGING
/// @notice Makes an order on the selected exchange
/// @dev These are orders that are not expected to settle immediately. Sufficient balance (== sellQuantity) of sellAsset
/// @param sellAsset Asset (as registered in Asset registrar) to be sold
/// @param buyAsset Asset (as registered in Asset registrar) to be bought
/// @param sellQuantity Quantity of sellAsset to be sold
/// @param buyQuantity Quantity of buyAsset to be bought
function makeOrder(
uint exchangeNumber,
address sellAsset,
address buyAsset,
uint sellQuantity,
uint buyQuantity
)
external
pre_cond(isOwner())
pre_cond(!isShutDown)
{
require(buyAsset != address(this)); // Prevent buying of own fund token
require(quantityHeldInCustodyOfExchange(sellAsset) == 0); // Curr only one make order per sellAsset allowed. Please wait or cancel existing make order.
require(module.pricefeed.existsPriceOnAssetPair(sellAsset, buyAsset)); // PriceFeed module: Requested asset pair not valid
var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(sellAsset, buyAsset);
require(isRecent); // Reference price is required to be recent
require(
module.riskmgmt.isMakePermitted(
module.pricefeed.getOrderPrice(
sellAsset,
buyAsset,
sellQuantity,
buyQuantity
),
referencePrice,
sellAsset,
buyAsset,
sellQuantity,
buyQuantity
)
); // RiskMgmt module: Make order not permitted
require(isInAssetList[buyAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached
require(AssetInterface(sellAsset).approve(exchanges[exchangeNumber].exchange, sellQuantity)); // Approve exchange to spend assets
// Since there is only one openMakeOrder allowed for each asset, we can assume that openMakeOrderId is set as zero by quantityHeldInCustodyOfExchange() function
require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("makeOrder(address,address,address,uint256,uint256)")), exchanges[exchangeNumber].exchange, sellAsset, buyAsset, sellQuantity, buyQuantity));
exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] = exchanges[exchangeNumber].exchangeAdapter.getLastOrderId(exchanges[exchangeNumber].exchange);
// Success defined as non-zero order id
require(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset] != 0);
// Update ownedAssets array and isInAssetList, isInOpenMakeOrder mapping
isInOpenMakeOrder[buyAsset] = true;
if (!isInAssetList[buyAsset]) {
ownedAssets.push(buyAsset);
isInAssetList[buyAsset] = true;
}
orders.push(Order({
exchangeId: exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset],
status: OrderStatus.active,
orderType: OrderType.make,
sellAsset: sellAsset,
buyAsset: buyAsset,
sellQuantity: sellQuantity,
buyQuantity: buyQuantity,
timestamp: now,
fillQuantity: 0
}));
OrderUpdated(exchangeIdsToOpenMakeOrderIds[exchangeNumber][sellAsset]);
}
/// @notice Takes an active order on the selected exchange
/// @dev These are orders that are expected to settle immediately
/// @param id Active order id
/// @param receiveQuantity Buy quantity of what others are selling on selected Exchange
function takeOrder(uint exchangeNumber, uint id, uint receiveQuantity)
external
pre_cond(isOwner())
pre_cond(!isShutDown)
{
// Get information of order by order id
Order memory order; // Inverse variable terminology! Buying what another person is selling
(
order.sellAsset,
order.buyAsset,
order.sellQuantity,
order.buyQuantity
) = exchanges[exchangeNumber].exchangeAdapter.getOrder(exchanges[exchangeNumber].exchange, id);
// Check pre conditions
require(order.sellAsset != address(this)); // Prevent buying of own fund token
require(module.pricefeed.existsPriceOnAssetPair(order.buyAsset, order.sellAsset)); // PriceFeed module: Requested asset pair not valid
require(isInAssetList[order.sellAsset] || ownedAssets.length < MAX_FUND_ASSETS); // Limit for max ownable assets by the fund reached
var (isRecent, referencePrice, ) = module.pricefeed.getReferencePrice(order.buyAsset, order.sellAsset);
require(isRecent); // Reference price is required to be recent
require(receiveQuantity <= order.sellQuantity); // Not enough quantity of order for what is trying to be bought
uint spendQuantity = mul(receiveQuantity, order.buyQuantity) / order.sellQuantity;
require(AssetInterface(order.buyAsset).approve(exchanges[exchangeNumber].exchange, spendQuantity)); // Could not approve spending of spendQuantity of order.buyAsset
require(
module.riskmgmt.isTakePermitted(
module.pricefeed.getOrderPrice(
order.buyAsset,
order.sellAsset,
order.buyQuantity, // spendQuantity
order.sellQuantity // receiveQuantity
),
referencePrice,
order.buyAsset,
order.sellAsset,
order.buyQuantity,
order.sellQuantity
)); // RiskMgmt module: Take order not permitted
// Execute request
require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("takeOrder(address,uint256,uint256)")), exchanges[exchangeNumber].exchange, id, receiveQuantity));
// Update ownedAssets array and isInAssetList mapping
if (!isInAssetList[order.sellAsset]) {
ownedAssets.push(order.sellAsset);
isInAssetList[order.sellAsset] = true;
}
order.exchangeId = id;
order.status = OrderStatus.fullyFilled;
order.orderType = OrderType.take;
order.timestamp = now;
order.fillQuantity = receiveQuantity;
orders.push(order);
OrderUpdated(id);
}
/// @notice Cancels orders that were not expected to settle immediately, i.e. makeOrders
/// @dev Reduce exposure with exchange interaction
/// @param id Active order id of this order array with order owner of this contract on selected Exchange
function cancelOrder(uint exchangeNumber, uint id)
external
pre_cond(isOwner() || isShutDown)
{
// Get information of fund order by order id
Order order = orders[id];
// Execute request
require(address(exchanges[exchangeNumber].exchangeAdapter).delegatecall(bytes4(keccak256("cancelOrder(address,uint256)")), exchanges[exchangeNumber].exchange, order.exchangeId));
order.status = OrderStatus.cancelled;
OrderUpdated(id);
}
// PUBLIC METHODS
// PUBLIC METHODS : ERC223
/// @dev Standard ERC223 function that handles incoming token transfers.
/// @dev This type of redemption can be seen as a "market order", where price is calculated at execution time
/// @param ofSender Token sender address.
/// @param tokenAmount Amount of tokens sent.
/// @param metadata Transaction metadata.
function tokenFallback(
address ofSender,
uint tokenAmount,
bytes metadata
) {
if (msg.sender != address(this)) {
// when ofSender is a recognized exchange, receive tokens, otherwise revert
for (uint i; i < exchanges.length; i++) {
if (exchanges[i].exchange == ofSender) return; // receive tokens and do nothing
}
revert();
} else { // otherwise, make a redemption request
requests.push(Request({
participant: ofSender,
status: RequestStatus.active,
requestType: RequestType.tokenFallbackRedeem,
requestAsset: address(QUOTE_ASSET), // redeem in QUOTE_ASSET
shareQuantity: tokenAmount,
giveQuantity: tokenAmount, // shares being sent
receiveQuantity: 0, // value of the shares at request time
timestamp: now,
atUpdateId: module.pricefeed.getLastUpdateId()
}));
RequestUpdated(getLastRequestId());
}
}
// PUBLIC METHODS : ACCOUNTING
/// @notice Calculates gross asset value of the fund
/// @dev Decimals in assets must be equal to decimals in PriceFeed for all entries in AssetRegistrar
/// @dev Assumes that module.pricefeed.getPrice(..) returns recent prices
/// @return gav Gross asset value quoted in QUOTE_ASSET and multiplied by 10 ** shareDecimals
function calcGav() returns (uint gav) {
// prices quoted in QUOTE_ASSET and multiplied by 10 ** assetDecimal
address[] memory tempOwnedAssets; // To store ownedAssets
tempOwnedAssets = ownedAssets;
delete ownedAssets;
for (uint i = 0; i < tempOwnedAssets.length; ++i) {
address ofAsset = tempOwnedAssets[i];
// assetHoldings formatting: mul(exchangeHoldings, 10 ** assetDecimal)
uint assetHoldings = add(
uint(AssetInterface(ofAsset).balanceOf(this)), // asset base units held by fund
quantityHeldInCustodyOfExchange(ofAsset)
);
// assetPrice formatting: mul(exchangePrice, 10 ** assetDecimal)
var (isRecent, assetPrice, assetDecimals) = module.pricefeed.getPrice(ofAsset);
if (!isRecent) {
revert();
}
// gav as sum of mul(assetHoldings, assetPrice) with formatting: mul(mul(exchangeHoldings, exchangePrice), 10 ** shareDecimals)
gav = add(gav, mul(assetHoldings, assetPrice) / (10 ** uint256(assetDecimals))); // Sum up product of asset holdings of this vault and asset prices
if (assetHoldings != 0 || ofAsset == address(QUOTE_ASSET) || ofAsset == address(NATIVE_ASSET) || isInOpenMakeOrder[ofAsset]) { // Check if asset holdings is not zero or is address(QUOTE_ASSET) or in open make order
ownedAssets.push(ofAsset);
} else {
isInAssetList[ofAsset] = false; // Remove from ownedAssets if asset holdings are zero
}
PortfolioContent(assetHoldings, assetPrice, assetDecimals);
}
}
/**
@notice Calculates unclaimed fees of the fund manager
@param gav Gross asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals
@return {
"managementFees": "A time (seconds) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals",
"performanceFees": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee in QUOTE_ASSET and multiplied by 10 ** shareDecimals",
"unclaimedfees": "The sum of both managementfee and performancefee in QUOTE_ASSET and multiplied by 10 ** shareDecimals"
}
*/
function calcUnclaimedFees(uint gav)
view
returns (
uint managementFee,
uint performanceFee,
uint unclaimedFees)
{
// Management fee calculation
uint timePassed = sub(now, atLastUnclaimedFeeAllocation.timestamp);
uint gavPercentage = mul(timePassed, gav) / (1 years);
managementFee = wmul(gavPercentage, MANAGEMENT_FEE_RATE);
// Performance fee calculation
// Handle potential division through zero by defining a default value
uint valuePerShareExclMgmtFees = totalSupply > 0 ? calcValuePerShare(sub(gav, managementFee), totalSupply) : toSmallestShareUnit(1);
if (valuePerShareExclMgmtFees > atLastUnclaimedFeeAllocation.highWaterMark) {
uint gainInSharePrice = sub(valuePerShareExclMgmtFees, atLastUnclaimedFeeAllocation.highWaterMark);
uint investmentProfits = wmul(gainInSharePrice, totalSupply);
performanceFee = wmul(investmentProfits, PERFORMANCE_FEE_RATE);
}
// Sum of all FEES
unclaimedFees = add(managementFee, performanceFee);
}
/// @notice Calculates the Net asset value of this fund
/// @param gav Gross asset value of this fund in QUOTE_ASSET and multiplied by 10 ** shareDecimals
/// @param unclaimedFees The sum of both managementFee and performanceFee in QUOTE_ASSET and multiplied by 10 ** shareDecimals
/// @return nav Net asset value in QUOTE_ASSET and multiplied by 10 ** shareDecimals
function calcNav(uint gav, uint unclaimedFees)
view
returns (uint nav)
{
nav = sub(gav, unclaimedFees);
}
/// @notice Calculates the share price of the fund
/// @dev Convention for valuePerShare (== sharePrice) formatting: mul(totalValue / numShares, 10 ** decimal), to avoid floating numbers
/// @dev Non-zero share supply; value denominated in [base unit of melonAsset]
/// @param totalValue the total value in QUOTE_ASSET and multiplied by 10 ** shareDecimals
/// @param numShares the number of shares multiplied by 10 ** shareDecimals
/// @return valuePerShare Share price denominated in QUOTE_ASSET and multiplied by 10 ** shareDecimals
function calcValuePerShare(uint totalValue, uint numShares)
view
pre_cond(numShares > 0)
returns (uint valuePerShare)
{
valuePerShare = toSmallestShareUnit(totalValue) / numShares;
}
/**
@notice Calculates essential fund metrics
@return {
"gav": "Gross asset value of this fund denominated in [base unit of melonAsset]",
"managementFee": "A time (seconds) based fee",
"performanceFee": "A performance (rise of sharePrice measured in QUOTE_ASSET) based fee",
"unclaimedFees": "The sum of both managementFee and performanceFee denominated in [base unit of melonAsset]",
"feesShareQuantity": "The number of shares to be given as fees to the manager",
"nav": "Net asset value denominated in [base unit of melonAsset]",
"sharePrice": "Share price denominated in [base unit of melonAsset]"
}
*/
function performCalculations()
view
returns (
uint gav,
uint managementFee,
uint performanceFee,
uint unclaimedFees,
uint feesShareQuantity,
uint nav,
uint sharePrice
)
{
gav = calcGav(); // Reflects value independent of fees
(managementFee, performanceFee, unclaimedFees) = calcUnclaimedFees(gav);
nav = calcNav(gav, unclaimedFees);
// The value of unclaimedFees measured in shares of this fund at current value
feesShareQuantity = (gav == 0) ? 0 : mul(totalSupply, unclaimedFees) / gav;
// The total share supply including the value of unclaimedFees, measured in shares of this fund
uint totalSupplyAccountingForFees = add(totalSupply, feesShareQuantity);
sharePrice = nav > 0 ? calcValuePerShare(gav, totalSupplyAccountingForFees) : toSmallestShareUnit(1); // Handle potential division through zero by defining a default value
}
/// @notice Converts unclaimed fees of the manager into fund shares
/// @return sharePrice Share price denominated in [base unit of melonAsset]
function calcSharePriceAndAllocateFees() public returns (uint)
{
var (
gav,
managementFee,
performanceFee,
unclaimedFees,
feesShareQuantity,
nav,
sharePrice
) = performCalculations();
createShares(owner, feesShareQuantity); // Updates totalSupply by creating shares allocated to manager
// Update Calculations
uint highWaterMark = atLastUnclaimedFeeAllocation.highWaterMark >= sharePrice ? atLastUnclaimedFeeAllocation.highWaterMark : sharePrice;
atLastUnclaimedFeeAllocation = Calculations({
gav: gav,
managementFee: managementFee,
performanceFee: performanceFee,
unclaimedFees: unclaimedFees,
nav: nav,
highWaterMark: highWaterMark,
totalSupply: totalSupply,
timestamp: now
});
FeesConverted(now, feesShareQuantity, unclaimedFees);
CalculationUpdate(now, managementFee, performanceFee, nav, sharePrice, totalSupply);
return sharePrice;
}
// PUBLIC : REDEEMING
/// @notice Redeems by allocating an ownership percentage only of requestedAssets to the participant
/// @dev Independent of running price feed! Note: if requestedAssets != ownedAssets then participant misses out on some owned value
/// @param shareQuantity Number of shares owned by the participant, which the participant would like to redeem for individual assets
/// @param requestedAssets List of addresses that consitute a subset of ownedAssets.
/// @return Whether all assets sent to shareholder or not
function emergencyRedeem(uint shareQuantity, address[] requestedAssets)
public
pre_cond(balances[msg.sender] >= shareQuantity) // sender owns enough shares
returns (bool)
{
address ofAsset;
uint[] memory ownershipQuantities = new uint[](requestedAssets.length);
// Check whether enough assets held by fund
for (uint i = 0; i < requestedAssets.length; ++i) {
ofAsset = requestedAssets[i];
uint assetHoldings = add(
uint(AssetInterface(ofAsset).balanceOf(this)),
quantityHeldInCustodyOfExchange(ofAsset)
);
if (assetHoldings == 0) continue;
// participant's ownership percentage of asset holdings
ownershipQuantities[i] = mul(assetHoldings, shareQuantity) / totalSupply;
// CRITICAL ERR: Not enough fund asset balance for owed ownershipQuantitiy, eg in case of unreturned asset quantity at address(exchanges[i].exchange) address
if (uint(AssetInterface(ofAsset).balanceOf(this)) < ownershipQuantities[i]) {
isShutDown = true;
ErrorMessage("CRITICAL ERR: Not enough assetHoldings for owed ownershipQuantitiy");
return false;
}
}
// Annihilate shares before external calls to prevent reentrancy
annihilateShares(msg.sender, shareQuantity);
// Transfer ownershipQuantity of Assets
for (uint j = 0; j < requestedAssets.length; ++j) {
// Failed to send owed ownershipQuantity from fund to participant
ofAsset = requestedAssets[j];
if (ownershipQuantities[j] == 0) {
continue;
} else if (!AssetInterface(ofAsset).transfer(msg.sender, ownershipQuantities[j])) {
revert();
}
}
Redeemed(msg.sender, now, shareQuantity);
return true;
}
// PUBLIC : FEES
/// @dev Quantity of asset held in exchange according to associated order id
/// @param ofAsset Address of asset
/// @return Quantity of input asset held in exchange
function quantityHeldInCustodyOfExchange(address ofAsset) returns (uint) {
uint totalSellQuantity; // quantity in custody across exchanges
uint totalSellQuantityInApprove; // quantity of asset in approve (allowance) but not custody of exchange
for (uint i; i < exchanges.length; i++) {
if (exchangeIdsToOpenMakeOrderIds[i][ofAsset] == 0) {
continue;
}
var (sellAsset, , sellQuantity, ) = exchanges[i].exchangeAdapter.getOrder(exchanges[i].exchange, exchangeIdsToOpenMakeOrderIds[i][ofAsset]);
if (sellQuantity == 0) {
exchangeIdsToOpenMakeOrderIds[i][ofAsset] = 0;
}
totalSellQuantity = add(totalSellQuantity, sellQuantity);
if (exchanges[i].isApproveOnly) {
totalSellQuantityInApprove += sellQuantity;
}
}
if (totalSellQuantity == 0) {
isInOpenMakeOrder[sellAsset] = false;
}
return sub(totalSellQuantity, totalSellQuantityInApprove); // Since quantity in approve is not actually in custody
}
// PUBLIC VIEW METHODS
/// @notice Calculates sharePrice denominated in [base unit of melonAsset]
/// @return sharePrice Share price denominated in [base unit of melonAsset]
function calcSharePrice() view returns (uint sharePrice) {
(, , , , , sharePrice) = performCalculations();
return sharePrice;
}
function getModules() view returns (address, address, address) {
return (
address(module.pricefeed),
address(module.compliance),
address(module.riskmgmt)
);
}
function getLastOrderId() view returns (uint) { return orders.length - 1; }
function getLastRequestId() view returns (uint) { return requests.length - 1; }
function getNameHash() view returns (bytes32) { return bytes32(keccak256(name)); }
function getManager() view returns (address) { return owner; }
}
contract WETH9_ {
string public name = "Wrapped Ether";
string public symbol = "WETH";
uint8 public decimals = 18;
event Approval(address indexed src, address indexed guy, uint wad);
event Transfer(address indexed src, address indexed dst, uint wad);
event Deposit(address indexed dst, uint wad);
event Withdrawal(address indexed src, uint wad);
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
function() public payable {
deposit();
}
function deposit() public payable {
balanceOf[msg.sender] += msg.value;
Deposit(msg.sender, msg.value);
}
function withdraw(uint wad) public {
require(balanceOf[msg.sender] >= wad);
balanceOf[msg.sender] -= wad;
msg.sender.transfer(wad);
Withdrawal(msg.sender, wad);
}
function totalSupply() public view returns (uint) {
return this.balance;
}
function approve(address guy, uint wad) public returns (bool) {
allowance[msg.sender][guy] = wad;
Approval(msg.sender, guy, wad);
return true;
}
function transfer(address dst, uint wad) public returns (bool) {
return transferFrom(msg.sender, dst, wad);
}
function transferFrom(address src, address dst, uint wad)
public
returns (bool)
{
require(balanceOf[src] >= wad);
if (src != msg.sender && allowance[src][msg.sender] != uint(-1)) {
require(allowance[src][msg.sender] >= wad);
allowance[src][msg.sender] -= wad;
}
balanceOf[src] -= wad;
balanceOf[dst] += wad;
Transfer(src, dst, wad);
return true;
}
}
|
Send `_value` tokens to `_to` from `msg.sender` and trigger tokenFallback if sender is a contract Function that is called when a user or contract wants to transfer funds _to Address of token receiver _value Number of tokens to transfer _data Data to be sent to tokenFallback return Returns success of function call/ Retrieve the size of the code on target address, this needs assembly.
|
function transfer(address _to, uint _value, bytes _data)
public
returns (bool success)
{
require(msg.sender == address(this) || _to == address(this));
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
require(balances[_to] + _value >= balances[_to]);
balances[msg.sender] = sub(balances[msg.sender], _value);
balances[_to] = add(balances[_to], _value);
if (codeLength > 0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
Transfer(msg.sender, _to, _value);
return true;
}
| 12,885,015 |
pragma solidity ^0.4.11;
/**
* Authors: Justin Jones, Marshall Stokes
* Published: 2017 by Sprux LLC
*/
/* Contract provides functions so only contract owner can execute a function */
contract owned {
address public owner; //the contract owner
function owned() {
owner = msg.sender; //constructor initializes the creator as the owner on initialization
}
modifier onlyOwner {
if (msg.sender != owner) throw; // functions with onlyOwner will throw an exception if not the contract owner
_;
}
function transferOwnership(address newOwner) onlyOwner { // transfer contract owner to new owner
owner = newOwner;
}
}
contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData); }
/**
* Centrally issued Ethereum token.
*
*
* Token supply is created on deployment and allocated to contract owner and two
* time-locked acccounts. The account deadlines (lock time) are in minutes from now.
* The owner can then transfer from its supply to crowdfund participants.
* The owner can burn any excessive tokens.
* The owner can freeze and unfreeze accounts
*
*/
contract StandardToken is owned{
/* Public variables of the token */
string public standard = 'Token 0.1';
string public name; // the token name
string public symbol; // the ticker symbol
uint8 public decimals; // amount of decimal places in the token
address public the120address; // the 120-day-locked address
address public the365address; // the 365-day-locked address
uint public deadline120; // days from contract creation in minutes to lock the120address (172800 minutes == 120 days)
uint public deadline365; // days from contract creation in minutes to lock the365address (525600 minutes == 365 days)
uint256 public totalSupply; // total number of tokens that exist (e.g. not burned)
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
/* This creates an array with all frozen accounts */
mapping (address => bool) public frozenAccount;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address target, bool frozen);
/* This generates a public event on the blockchain that will notify clients */
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/* Initializes contract with entire supply of tokens assigned to our distro accounts */
function StandardToken(
string tokenName,
uint8 decimalUnits,
string tokenSymbol,
uint256 distro1, // the initial crowdfund distro amount
uint256 distro120, // the 120 day distro amount
uint256 distro365, // the 365 day distro amount
address address120, // the 120 day address
address address365, // the 365 day address
uint durationInMinutes120, // amount of minutes to lock address120
uint durationInMinutes365 // amount of minutes to lock address365
) {
balanceOf[msg.sender] = distro1; // Give the owner tokens for initial crowdfund distro
balanceOf[address120] = distro120; // Set 120 day address balance (to be locked)
balanceOf[address365] = distro365; // Set 365 day address balance (to be locked)
freezeAccount(address120, true); // Freeze the 120 day address on creation
freezeAccount(address365, true); // Freeze the 120 day address on creation
totalSupply = distro1+distro120+distro365; // Total supply is sum of tokens assigned to distro accounts
deadline120 = now + durationInMinutes120 * 1 minutes; // Set the 120 day deadline
deadline365 = now + durationInMinutes365 * 1 minutes; // Set the 365 day deadline
the120address = address120; // Set the publicly accessible 120 access
the365address = address365; // Set the publicly accessible 365 access
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
decimals = decimalUnits; // Number of decimals for display purposes
}
/* Send tokens */
function transfer(address _to, uint256 _value) returns (bool success){
if (_value == 0) return false; // Don't waste gas on zero-value transaction
if (balanceOf[msg.sender] < _value) return false; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (frozenAccount[msg.sender]) throw; // Check if sender is frozen
if (frozenAccount[_to]) throw; // Check if target is frozen
balanceOf[msg.sender] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens on your behalf */
function approve(address _spender, uint256 _value)
returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/* Approve and then communicate the approved contract in a single tx */
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {
if (frozenAccount[_from]) throw; // Check if sender frozen
if (frozenAccount[_to]) throw; // Check if target frozen
if (balanceOf[_from] < _value) return false; // Check if the sender has enough
if (balanceOf[_to] + _value < balanceOf[_to]) throw; // Check for overflows
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
balanceOf[_to] += _value; // Add the same to the recipient
allowance[_from][msg.sender] -= _value; // Allowance changes
Transfer(_from, _to, _value); // Tokens are send
return true;
}
/* A function to freeze or un-freeze an account, to and from */
function freezeAccount(address target, bool freeze ) onlyOwner {
if ((target == the120address) && (now < deadline120)) throw; // Ensure you can not change 120address frozen status until deadline
if ((target == the365address) && (now < deadline365)) throw; // Ensure you can not change 365address frozen status until deadline
frozenAccount[target] = freeze; // Set the array object to the value of bool freeze
FrozenFunds(target, freeze); // Notify event
}
/* A function to burn tokens and remove from supply */
function burn(uint256 _value) returns (bool success) {
if (frozenAccount[msg.sender]) throw; // Check if sender frozen
if (_value == 0) return false; // Don't waste gas on zero-value transaction
if (balanceOf[msg.sender] < _value) return false; // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Reduce totalSupply accordingly
Transfer(msg.sender,0, _value); // Burn baby burn
return true;
}
function burnFrom(address _from, uint256 _value) onlyOwner returns (bool success) {
if (frozenAccount[msg.sender]) throw; // Check if sender frozen
if (frozenAccount[_from]) throw; // Check if recipient frozen
if (_value == 0) return false; // Don't waste gas on zero-value transaction
if (balanceOf[_from] < _value) return false; // Check if the sender has enough
if (_value > allowance[_from][msg.sender]) throw; // Check allowance
balanceOf[_from] -= _value; // Subtract from the sender
allowance[_from][msg.sender] -= _value; // Allowance is updated
totalSupply -= _value; // Updates totalSupply
Transfer(_from, 0, _value);
return true;
}
}
|
A function to freeze or un-freeze an account, to and from /
|
function freezeAccount(address target, bool freeze ) onlyOwner {
}
| 948,657 |
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "../BasePrivateEdition.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract PrivateLimitedTimedEdition is BasePrivateEdition {
using SafeMath for uint256;
event LotCreated(
uint256 pricePerEdition,
uint256 startTime,
uint256 endTime,
uint256 lotID,
uint256 tokenID,
uint256 auctionID,
address[] validBuyers
);
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _registry, address _timer)
BasePrivateEdition(_registry, _timer)
{}
// -----------------------------------------------------------------------
// NON-STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function getLotInfo(uint256 _lotID)
external
view
returns (
uint256 tokenID,
address owner,
uint256 price,
uint256 startTime,
uint256 endTime,
bool maxBuyPerTx,
uint256 maxBuy,
uint256 maxSupply,
bool biddable
)
{
tokenID = lots_[_lotID].tokenID;
owner = lots_[_lotID].owner;
price = lotPrices_[_lotID].pricePerEdition;
startTime = lotPrices_[_lotID].startTime;
endTime = lotPrices_[_lotID].endTime;
maxBuy = lotPrices_[_lotID].maxBatchBuy;
maxBuy == 0 ? maxBuyPerTx = false : maxBuyPerTx = true;
maxSupply = lotPrices_[_lotID].maxStock;
biddable = lotPrices_[_lotID].biddable;
}
// -----------------------------------------------------------------------
// PUBLICLY ACCESSIBLE STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _lotID ID of the new lot auction being created within this
* auction instance.
* @param _tokenID ID of the token being sold in the auction type.
* @dev Only the Auction Hub is able to call this function.
*/
function createLot(
uint256 _lotID,
uint256 _tokenID,
uint256 _pricePerEdition,
uint256 _startTimeStamp,
uint256 _endTimeStamp,
bool _maxBuyPerTx,
uint256 _maxBuy,
uint256 _maxSupply,
address[] calldata _validBuyers
) external {
require(_pricePerEdition != 0, "Lot price cannot be 0");
require(_startTimeStamp < _endTimeStamp, "End time before start");
require(
_endTimeStamp > getCurrentTime(),
"End time cannot be before current"
);
// If there is a max buy limit per batch buy transaction
if (_maxBuyPerTx) {
lotPrices_[_lotID].maxBatchBuy = _maxBuy;
}
// Storing the price for the lot
lotPrices_[_lotID].pricePerEdition = _pricePerEdition;
lotPrices_[_lotID].startTime = _startTimeStamp;
lotPrices_[_lotID].endTime = _endTimeStamp;
lotPrices_[_lotID].tokenID = _tokenID;
lotPrices_[_lotID].useMaxStock = true;
lotPrices_[_lotID].maxStock = _maxSupply;
// Verifying senders rights to start auction, pulling token from the
// hub, emitting relevant info
_createAuctionLot(_lotID, _tokenID);
_addBuyersForLot(_lotID, _validBuyers);
// Checks if the start time has passed
if (getCurrentTime() >= _startTimeStamp) {
lotPrices_[_lotID].biddable = true;
auctionHubInstance_.lotAuctionStarted(auctionID_, _lotID);
}
emit LotCreated(
_pricePerEdition,
_startTimeStamp,
_endTimeStamp,
_lotID,
_tokenID,
auctionID_,
_validBuyers
);
}
/**
* @param _lotID The ID of the lot
* @notice This function will revert if the bid amount is not higher than
* the current highest bid and the min bid price for the lot.
*/
function bid(uint256 _lotID, uint256 _editionAmount)
external
payable
onlyListedBuyer(_lotID)
{
_bid(_lotID, _editionAmount);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./EditionData.sol";
import "../../nft/INft.sol";
import "../PrivateAuction.sol";
import "../../testing-helpers/Testable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
contract BasePrivateEdition is PrivateAuction, EditionData, Testable {
using SafeMath for uint256;
event PurchaseOnLot(
uint256 indexed lotId,
uint256 noPurchased,
address indexed bidder,
uint256 amountPaid
);
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _registry, address _timer)
PrivateAuction(_registry)
EditionData()
Testable(_timer)
{}
/**
* @param _lotID The lot ID
* @notice Returns the original token to the owner. Can only be called if
* the lot has expired.
*/
function returnOriginal(uint256 _lotID) external {
require(
lotPrices_[_lotID].endTime <= getCurrentTime(),
"Lot has not expired"
);
_returnOriginalToken(_lotID);
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function _returnOriginalToken(uint256 _lotID) internal {
nftInstance_.transfer(lots_[_lotID].owner, lots_[_lotID].tokenID);
// Setting on the auction hub that the first sale is completed
auctionHubInstance_.firstSaleCompleted(lots_[_lotID].tokenID);
}
/**
* @param _lotID The ID of the lot
* @param _editionAmount How many tokens to buy
* @notice This function will revert if the bid amount is not higher than
* the current highest bid and the min bid price for the lot.
*/
function _bid(uint256 _lotID, uint256 _editionAmount) internal {
// Will revert if lot is not in biddable state
_isLotInBiddableState(_lotID);
// Checks that lot has started (timestamp checks)
require(_isLotBiddable(_lotID), "Lot has not started or ended");
// Ensures that if there is limited stock, cannot buy more than stock.
if (lotPrices_[_lotID].useMaxStock) {
require(
lotPrices_[_lotID].maxStock >=
lotPrices_[_lotID].tokensMinted.add(_editionAmount),
"Cannot buy more than max stock"
);
}
// Ensures that if there is a max buy per tx, cannot buy more than max.
if (lotPrices_[_lotID].maxBatchBuy != 0) {
require(
lotPrices_[_lotID].maxBatchBuy >= _editionAmount,
"Cannot buy more than max batch"
);
}
// Getting the cost to buy the desired edition amount
uint256 cost = lotPrices_[_lotID].pricePerEdition.mul(_editionAmount);
// Ensuring sent value is sufficient
require(cost <= msg.value, "Insufficient msg.value");
lotPrices_[_lotID].tokensMinted = lotPrices_[_lotID].tokensMinted.add(
_editionAmount
);
_handlePayment(_lotID, cost);
// All event data will come from the NFT contract
nftInstance_.batchDuplicateMint(
msg.sender,
_editionAmount,
lotPrices_[_lotID].tokenID,
lotPrices_[_lotID].useMaxStock
);
emit PurchaseOnLot(_lotID, _editionAmount, msg.sender, cost);
}
/**
* @param _lotID The ID of the lot
* @notice This function will not revert. This function will return false
* if the lot has not reached the start time, or is passed the end
* time. This function will return true if the lot is between
* it's start and end time.
*/
function _isLotBiddable(uint256 _lotID) internal returns (bool) {
// If the end time has not passed
if (lotPrices_[_lotID].endTime > getCurrentTime()) {
// If the start time has passed
if (getCurrentTime() >= lotPrices_[_lotID].startTime) {
// If biddable has not been set to true
if (lotPrices_[_lotID].biddable == false) {
// Setting the auction to active on the hub
auctionHubInstance_.lotAuctionStarted(auctionID_, _lotID);
lotPrices_[_lotID].biddable = true;
}
// Start time has passed
return true;
}
// Start time has not passed
return false;
} else {
lotPrices_[_lotID].biddable = false;
return false;
}
}
function _handlePayment(uint256 _lotID, uint256 _totalCollateralAmount)
internal
{
require(
auctionHubInstance_.isFirstSale(lots_[_lotID].tokenID),
"Not first sale"
);
// Temporary storage for splits and shares
uint256 creatorSplit;
uint256 systemSplit;
uint256 creatorShare;
uint256 systemShare;
// Getting the split for the
(creatorSplit, systemSplit) = auctionHubInstance_.getFirstSaleSplit();
// Working out the creators share according to the split
creatorShare = _totalCollateralAmount.mul(creatorSplit).div(
SPLIT_SCALING_FACTOR
);
// Working out the systems share according to the split
systemShare = _totalCollateralAmount.mul(systemSplit).div(
SPLIT_SCALING_FACTOR
);
require(
creatorShare.add(systemShare) <= _totalCollateralAmount,
"BAU: Fatal: value mismatch"
);
// Depositing creator share
royaltiesInstance_.deposit{value: creatorShare}(
nftInstance_.creatorOf(lots_[_lotID].tokenID),
creatorShare
);
// Depositing the system share
royaltiesInstance_.deposit{value: systemShare}(address(0), systemShare);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract EditionData {
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE VARIABLES
// -----------------------------------------------------------------------
// Storage for each lots price
struct LotPrice {
uint256 pricePerEdition; // The cost per token
uint256 maxBatchBuy; // The max amount of tokens per TX
uint256 tokenID;
uint256 startTime;
uint256 endTime;
bool biddable;
bool useMaxStock;
uint256 maxStock;
uint256 tokensMinted;
}
// Lot ID's to price
mapping(uint256 => LotPrice) internal lotPrices_;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
interface INft {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @param _tokenID The ID of the token
* @return address of the owner for this token
*/
function ownerOf(uint256 _tokenID) external view returns(address);
/**
* @param _tokenID The ID of the token
* @return address of the creator of the token
*/
function creatorOf(uint256 _tokenID) external view returns(address);
/**
* @param _owner The address of the address to check
* @return uint256 The number of tokens the user owns
*/
function balanceOf(address _owner) external view returns(uint256);
/**
* @return uint256 The total number of circulating tokens
*/
function totalSupply() external view returns(uint256);
/**
* @param _owner Address of the owner
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @return bool The approved status of the spender against the owner
*/
function isApprovedSpenderOf(
address _owner,
address _spender,
uint256 _tokenID
)
external
view
returns(bool);
/**
* @param _minter Address of the minter being checked
* @return isMinter If the minter has the minter role
* @return isActiveMinter If the minter is an active minter
*/
function isMinter(
address _minter
)
external
view
returns(
bool isMinter,
bool isActiveMinter
);
function isActive() external view returns(bool);
function isTokenBatch(uint256 _tokenID) external view returns(uint256);
function getBatchInfo(
uint256 _batchID
)
external
view
returns(
uint256 baseTokenID,
uint256[] memory tokenIDs,
bool limitedStock,
uint256 totalMinted
);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _spender The address of the spender
* @param _tokenID ID of the token to check
* @param _approvalSpender The status of the spenders approval on the
* owner
* @notice Will revert if msg.sender is the spender or if the msg.sender
* is not the owner of the token.
*/
function approveSpender(
address _spender,
uint256 _tokenID,
bool _approvalSpender
)
external;
// -----------------------------------------------------------------------
// ONLY AUCTIONS (hub or spokes) STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _to Address of receiver
* @param _tokenID Token to transfer
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function transfer(
address _to,
uint256 _tokenID
)
external;
/**
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if the
* msg.sender is not the token owner. Will revert if msg.sender is
* to to address
*/
function batchTransfer(
address _to,
uint256[] memory _tokenIDs
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenID ID of token being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenID
)
external;
/**
* @param _from Address being transferee from
* @param _to Address to transfer to
* @param _tokenIDs Array of tokens being transferred
* @notice Only auctions (hub or spokes) will be able to transfer tokens.
* Will revert if to address is the 0x address. Will revert if
* msg.sender is not approved spender of token on _from address.
* Will revert if the _from is not the token owner. Will revert if
* _from is _to address.
*/
function batchTransferFrom(
address _from,
address _to,
uint256[] memory _tokenIDs
)
external;
// -----------------------------------------------------------------------
// ONLY MINTER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _tokenCreator Address of the creator. Address will receive the
* royalties from sales of the NFT
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @notice Only valid active minters will be able to mint new tokens
*/
function mint(
address _tokenCreator,
address _mintTo,
string calldata identifier,
string calldata location,
bytes32 contentHash
) external returns(uint256);
/**
* @param _mintTo The address that should receive the token. Note that on
* the initial sale this address will not receive the sale
* collateral. Sale collateral will be distributed to creator and
* system fees
* @param _amount Amount of tokens to mint
* @param _baseTokenID ID of the token being duplicated
* @param _isLimitedStock Bool for if the batch has a pre-set limit
*/
function batchDuplicateMint(
address _mintTo,
uint256 _amount,
uint256 _baseTokenID,
bool _isLimitedStock
)
external
returns(uint256[] memory);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./BaseAuction.sol";
contract PrivateAuction is BaseAuction {
// Lot ID => buyer => listed status
mapping(uint256 => mapping(address => bool)) internal listedBuyers_;
mapping(uint256 => address[]) internal validBuyers_;
modifier onlyListedBuyer(uint256 _lotID) {
require(
listedBuyers_[_lotID][msg.sender],
"Private: not listed as buyer"
);
_;
}
constructor(address _registry) BaseAuction(_registry) {}
function _addBuyersForLot(uint256 _lotID, address[] calldata _buyers)
internal
onlyLotOwner(_lotID)
{
validBuyers_[_lotID] = _buyers;
for (uint256 i = 0; i < _buyers.length; i++) {
require(_buyers[i] != address(0), "Cannot add 0x as buyer");
listedBuyers_[_lotID][_buyers[i]] = true;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.0 < 0.8.0;
import "./Timer.sol";
/**
* @title Base class that provides time overrides, but only if being run in test mode.
*/
abstract contract Testable {
// If the contract is being run on the test network, then `timerAddress` will be the 0x0 address.
// Note: this variable should be set on construction and never modified.
address public timerAddress;
/**
* @notice Constructs the Testable contract. Called by child contracts.
* @param _timerAddress Contract that stores the current time in a testing environment.
* Must be set to 0x0 for production environments that use live time.
*/
constructor(address _timerAddress) internal {
timerAddress = _timerAddress;
}
/**
* @notice Reverts if not running in test mode.
*/
modifier onlyIfTest {
require(timerAddress != address(0x0));
_;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set current Testable time to.
*/
function setCurrentTime(uint256 time) external onlyIfTest {
Timer(timerAddress).setCurrentTime(time);
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
if (timerAddress != address(0x0)) {
return Timer(timerAddress).getCurrentTime();
} else {
return block.timestamp;
}
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "./IHub.sol";
import "./IAuction.sol";
import "../nft/INft.sol";
import "../registry/Registry.sol";
import "../royalties/IRoyalties.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
abstract contract BaseAuction is IAuction, ReentrancyGuard {
// Libraries
using SafeMath for uint256;
// -----------------------------------------------------------------------
// STATE VARIABLES
// -----------------------------------------------------------------------
// Instance of the registry
Registry internal registryInstance_;
// Instance of the auction Hub
IHub internal auctionHubInstance_;
// Instance of the NFT contract being used (modified ERC1155)
INft internal nftInstance_;
// Instance of the royalties contract
IRoyalties internal royaltiesInstance_;
// ID of this auction instance
uint256 internal auctionID_;
// Bool check to ensure that the auction can only be initialised once.
// Variable is private so it cannot be changed in child contracts, and
// can only be set once on initialisation
bool private isInit_;
struct Lot {
address owner;
uint256 tokenID;
bool biddingStarted;
}
mapping(uint256 => Lot) internal lots_;
uint256 internal constant SPLIT_SCALING_FACTOR = 10000;
// -----------------------------------------------------------------------
// EVENTS
// -----------------------------------------------------------------------
event Initialised(address auctionHub, uint256 auctionID);
event AuctionLotCreated(
address indexed creator,
uint256 auctionID,
uint256 lotID,
uint256 tokenID
);
event LotWinner(
uint256 indexed auctionID,
uint256 indexed lotID,
address indexed winner
);
event LotLoserClaim(
uint256 indexed auctionID,
uint256 indexed lotID,
address indexed claimer,
uint256 claimAmount
);
// -----------------------------------------------------------------------
// MODIFIERS
// -----------------------------------------------------------------------
/**
* @notice A modifier to restrict access to only the auction hub
*/
modifier onlyHub() {
require(
msg.sender == address(auctionHubInstance_),
"Access restricted to Hub"
);
_;
}
/**
* @notice A modifier to protect the initialisation call so that an auction
* can only be initialised once
*/
modifier initialise() {
require(isInit_ == false, "Auction has already been init");
_;
}
modifier onlyActive() {
require(
isInit_ && auctionHubInstance_.isAuctionActive(auctionID_),
"Auction not in valid use state"
);
_;
}
modifier onlyLotOwner(uint256 _lotID) {
address owner;
(owner, , , ) = auctionHubInstance_.getLotInformation(_lotID);
// Ensuring the lot information is correct
require(owner == msg.sender, "Creator must own token");
_;
}
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _registryInstance) {
registryInstance_ = Registry(_registryInstance);
auctionHubInstance_ = IHub(registryInstance_.getHub());
nftInstance_ = INft(registryInstance_.getNft());
royaltiesInstance_ = IRoyalties(registryInstance_.getRoyalties());
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
/**
* @return bool The active status of the auction. Will only return true if
* the auction has been initialised and is active.
*/
function isActive() external view override returns (bool) {
if (isInit_ && auctionHubInstance_.isAuctionActive(auctionID_)) {
return true;
}
return false;
}
/**
* @param _lotID The ID of the lot.
* @return bool If bidding has started on the lot.
*/
function hasBiddingStarted(uint256 _lotID) external view override returns (bool) {
return lots_[_lotID].biddingStarted;
}
/**
* @return uint256 The auction ID as set by the auction hub of this
* auction.
*/
function getAuctionID() external view override returns (uint256) {
return auctionID_;
}
// -----------------------------------------------------------------------
// ONLY AUCTION HUB STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _auctionID ID of the auction this auction is
* @dev This call will be protected so only the Auction hub can call it.
* This function will also set the auction state to active.
*/
function init(uint256 _auctionID)
external
override
onlyHub()
initialise()
returns (bool)
{
auctionID_ = _auctionID;
isInit_ = true;
emit Initialised(msg.sender, _auctionID);
return true;
}
/**
* @param _lotID ID of the lot
* @dev Transfers the token from the auction back to the lot requester
*/
function cancelLot(uint256 _lotID) external override onlyHub() {
// Transferring the token to the lot owner
nftInstance_.transfer(lots_[_lotID].owner, lots_[_lotID].tokenID);
}
// -----------------------------------------------------------------------
// INTERNAL STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
/**
* @param _lotID ID of the new lot auction being created within this
* auction instance.
* @param _tokenID ID of the token being sold in the auction type.
* @dev Only the Auction Hub is able to call this function.
*/
function _createAuctionLot(uint256 _lotID, uint256 _tokenID) internal {
// Getting the relevant lot information
address owner;
uint256 tokenID;
uint256 auctionID;
IHub.LotStatus status;
(owner, tokenID, auctionID, status) = auctionHubInstance_
.getLotInformation(_lotID);
// Ensuring the lot information is correct
require(owner == msg.sender, "Creator must own token");
require(tokenID == _tokenID, "Given lot ID mismatch token lot");
require(auctionID == auctionID_, "Lot on different auction");
require(status == IHub.LotStatus.LOT_REQUESTED, "Lot status incorrect");
// Storing the lot information
lots_[_lotID].owner = owner;
lots_[_lotID].tokenID = tokenID;
// Updating the Lot's status to created
auctionHubInstance_.lotCreated(auctionID_, _lotID);
// Transferring the token to this auction
nftInstance_.transferFrom(
address(auctionHubInstance_),
address(this),
tokenID
);
emit AuctionLotCreated(msg.sender, auctionID, _lotID, tokenID);
}
/**
* @param _lotID The ID of the lot
* @notice This function will revert if the lot is not in the created
* state or active state. Will also revert if the state is
* canceled.
*/
function _isLotInBiddableState(uint256 _lotID) internal {
IHub.LotStatus status;
(, , , status) = auctionHubInstance_.getLotInformation(_lotID);
require(
(status != IHub.LotStatus.AUCTION_CANCELED &&
status == IHub.LotStatus.LOT_CREATED) ||
status == IHub.LotStatus.AUCTION_ACTIVE,
"Bid has ended or canceled"
);
if(!lots_[_lotID].biddingStarted) {
lots_[_lotID].biddingStarted = true;
}
}
/**
* @param _lotID The ID of the lot
* @param _winner The address of the lot winner
* @notice Shared functionality that all the auctions will need for
* executing the needed winning functionality.
*/
function _winner(uint256 _lotID, address _winner) internal {
// Sending the winner their token
nftInstance_.transfer(_winner, lots_[_lotID].tokenID);
// Setting the lot to completed on the hub
auctionHubInstance_.lotAuctionCompletedAndClaimed(auctionID_, _lotID);
// Emitting that the lot has been resolved
emit LotWinner(auctionID_, _lotID, msg.sender);
}
/**
* @param _loserAddress Address of loser
* @param _bidAmount The amount that was bid
* @notice This function transfers the loser their bid amount. NOTE not all
* auction types will use this function, which is why it does no
* data validation.
*/
function _insecureLoser(
uint256 lotID,
address _loserAddress,
uint256 _bidAmount
) internal {
// Sending loser amount
(bool success, ) = _loserAddress.call{value: _bidAmount}("");
// Ensuring transfer succeeded
require(success, "Transfer failed.");
emit LotLoserClaim(auctionID_, lotID, _loserAddress, _bidAmount);
}
/**
* @param _lotID The ID of the lot
* @param _totalCollateralAmount The total amount of collateral that was
* bid.
* @notice This function will call first or secondary payment functions
* as needed.
*/
function _insecureHandlePayment(
uint256 _lotID,
uint256 _totalCollateralAmount
) internal {
if (auctionHubInstance_.isFirstSale(lots_[_lotID].tokenID)) {
_handleFirstSalePayment(_lotID, _totalCollateralAmount);
} else {
_insecureHandleSecondarySalesPayment(
_lotID,
_totalCollateralAmount
);
}
}
function _handleFirstSalePayment(
uint256 _lotID,
uint256 _totalCollateralAmount
) internal {
require(
auctionHubInstance_.isFirstSale(lots_[_lotID].tokenID),
"Not first sale"
);
// Temporary storage for splits and shares
uint256 creatorSplit;
uint256 systemSplit;
uint256 creatorShare;
uint256 systemShare;
// Getting the split for the
(creatorSplit, systemSplit) = auctionHubInstance_.getFirstSaleSplit();
// Working out the creators share according to the split
creatorShare = _totalCollateralAmount.mul(creatorSplit).div(
SPLIT_SCALING_FACTOR
);
// Working out the systems share according to the split
systemShare = _totalCollateralAmount.mul(systemSplit).div(
SPLIT_SCALING_FACTOR
);
require(
creatorShare.add(systemShare) <= _totalCollateralAmount,
"BAU: Fatal: value mismatch"
);
// Depositing creator share
royaltiesInstance_.deposit{value: creatorShare}(
nftInstance_.creatorOf(lots_[_lotID].tokenID),
creatorShare
);
// Depositing the system share
royaltiesInstance_.deposit{value: systemShare}(address(0), systemShare);
// Setting on the auction hub that the first sale is completed
auctionHubInstance_.firstSaleCompleted(lots_[_lotID].tokenID);
}
function _insecureHandleSecondarySalesPayment(
uint256 _lotID,
uint256 _totalCollateralAmount
) internal {
require(
!auctionHubInstance_.isFirstSale(lots_[_lotID].tokenID),
"Not secondary sale"
);
// Temporary storage for splits and shares
uint256 creatorSplit;
uint256 sellerSplit;
uint256 systemSplit;
uint256 creatorShare;
uint256 sellerShare;
uint256 systemShare;
// Getting the split for the
(creatorSplit, sellerSplit, systemSplit) = auctionHubInstance_
.getSecondarySaleSplits();
// Working out the creators share according to the split
creatorShare = _totalCollateralAmount.mul(creatorSplit).div(
SPLIT_SCALING_FACTOR
);
// Working out the sellers share according to the split
sellerShare = _totalCollateralAmount.mul(sellerSplit).div(
SPLIT_SCALING_FACTOR
);
// Working out the systems share according to the split
systemShare = _totalCollateralAmount.mul(systemSplit).div(
SPLIT_SCALING_FACTOR
);
// Depositing creator share
royaltiesInstance_.deposit{value: creatorShare}(
nftInstance_.creatorOf(lots_[_lotID].tokenID),
creatorShare
);
// Depositing the system share
royaltiesInstance_.deposit{value: systemShare}(address(0), systemShare);
// Sending user amount
(bool success, ) = lots_[_lotID].owner.call{value: sellerShare}("");
// Ensuring transfer succeeded
require(success, "Transfer failed.");
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IHub {
enum LotStatus {
NO_LOT,
LOT_REQUESTED,
LOT_CREATED,
AUCTION_ACTIVE,
AUCTION_RESOLVED,
AUCTION_RESOLVED_AND_CLAIMED,
AUCTION_CANCELED
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getLotInformation(uint256 _lotID)
external
view
returns (
address owner,
uint256 tokenID,
uint256 auctionID,
LotStatus status
);
function getAuctionInformation(uint256 _auctionID)
external
view
returns (
bool active,
string memory auctionName,
address auctionContract,
bool onlyPrimarySales
);
function getAuctionID(address _auction) external view returns (uint256);
function isAuctionActive(uint256 _auctionID) external view returns (bool);
function getAuctionCount() external view returns (uint256);
function isAuctionHubImplementation() external view returns (bool);
function isFirstSale(uint256 _tokenID) external view returns (bool);
function getFirstSaleSplit()
external
view
returns (uint256 creatorSplit, uint256 systemSplit);
function getSecondarySaleSplits()
external
view
returns (
uint256 creatorSplit,
uint256 sellerSplit,
uint256 systemSplit
);
function getScalingFactor() external view returns (uint256);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function requestAuctionLot(uint256 _auctionType, uint256 _tokenID)
external
returns (uint256 lotID);
// -----------------------------------------------------------------------
// ONLY AUCTIONS STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function firstSaleCompleted(uint256 _tokenID) external;
function lotCreated(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionStarted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompleted(uint256 _auctionID, uint256 _lotID) external;
function lotAuctionCompletedAndClaimed(uint256 _auctionID, uint256 _lotID)
external;
function cancelLot(uint256 _auctionID, uint256 _lotID) external;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IAuction {
/**
* @return bool The active status of the auction. Will only return true if
* the auction has been initialised and is active.
*/
function isActive() external view returns (bool);
/**
* @param _lotID The ID of the lot.
* @return bool If bidding has started on the lot.
*/
function hasBiddingStarted(uint256 _lotID) external view returns (bool);
/**
* @return uint256 The auction ID as set by the auction hub of this
* auction.
*/
function getAuctionID() external view returns (uint256);
/**
* @param _auctionID ID of the auction this auction is
* @dev This call will be protected so only the Auction hub can call it.
* This function will also set the auction state to active.
*/
function init(uint256 _auctionID) external returns (bool);
/**
* @param _lotID ID of the lot
* @dev Transfers the token from the auction back to the lot requester
*/
function cancelLot(uint256 _lotID) external;
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
// Registry managed contracts
import "../auctions/IHub.sol";
import "../royalties/IRoyalties.sol";
import "../nft/INft.sol";
contract Registry is Ownable, ReentrancyGuard {
// -----------------------------------------------------------------------
// STATE
// -----------------------------------------------------------------------
// Storage of current hub instance
IHub internal hubInstance_;
// Storage of current royalties instance
IRoyalties internal royaltiesInstance_;
// Storage of NFT contract (cannot be changed)
INft internal nftInstance_;
// -----------------------------------------------------------------------
// CONSTRUCTOR
// -----------------------------------------------------------------------
constructor(address _nft) Ownable() {
require(INft(_nft).isActive(), "REG: Address invalid NFT");
nftInstance_ = INft(_nft);
}
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getHub() external view returns (address) {
return address(hubInstance_);
}
function getRoyalties() external view returns (address) {
return address(royaltiesInstance_);
}
function getNft() external view returns (address) {
return address(nftInstance_);
}
function isActive() external view returns (bool) {
return true;
}
// -----------------------------------------------------------------------
// ONLY OWNER STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function updateHub(address _newHub) external onlyOwner nonReentrant {
IHub newHub = IHub(_newHub);
require(_newHub != address(0), "REG: cannot set HUB to 0x");
require(
address(hubInstance_) != _newHub,
"REG: Cannot set HUB to existing"
);
require(
newHub.isAuctionHubImplementation(),
"REG: HUB implementation error"
);
require(IHub(_newHub).init(), "REG: HUB could not be init");
hubInstance_ = IHub(_newHub);
}
function updateRoyalties(address _newRoyalties)
external
onlyOwner
nonReentrant
{
require(_newRoyalties != address(0), "REG: cannot set ROY to 0x");
require(
address(royaltiesInstance_) != _newRoyalties,
"REG: Cannot set ROY to existing"
);
require(IRoyalties(_newRoyalties).init(), "REG: ROY could not be init");
royaltiesInstance_ = IRoyalties(_newRoyalties);
}
}
//SPDX-License-Identifier: MIT
pragma solidity 0.7.5;
interface IRoyalties {
// -----------------------------------------------------------------------
// NON-MODIFYING FUNCTIONS (VIEW)
// -----------------------------------------------------------------------
function getBalance(address _user) external view returns (uint256);
function getCollateral() external view returns (address);
// -----------------------------------------------------------------------
// PUBLIC STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function deposit(address _to, uint256 _amount) external payable;
function withdraw(uint256 _amount) external payable;
// -----------------------------------------------------------------------
// ONLY REGISTRY STATE MODIFYING FUNCTIONS
// -----------------------------------------------------------------------
function init() external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.6.0 < 0.8.0;
/**
* @title Universal store of current contract time for testing environments.
*/
contract Timer {
uint256 private currentTime;
constructor() public {
currentTime = block.timestamp;
}
/**
* @notice Sets the current time.
* @dev Will revert if not running in test mode.
* @param time timestamp to set `currentTime` to.
*/
function setCurrentTime(uint256 time) external {
currentTime = time;
}
/**
* @notice Gets the current time. Will return the last time set in `setCurrentTime` if running in test mode.
* Otherwise, it will return the block timestamp.
* @return uint256 for the current Testable timestamp.
*/
function getCurrentTime() public view returns (uint256) {
return currentTime;
}
}
|
_lotID The ID of the lot This function will not revert. This function will return false if the lot has not reached the start time, or is passed the end time. This function will return true if the lot is between it's start and end time./ If the end time has not passed If the start time has passed If biddable has not been set to true Setting the auction to active on the hub
|
function _isLotBiddable(uint256 _lotID) internal returns (bool) {
if (lotPrices_[_lotID].endTime > getCurrentTime()) {
if (getCurrentTime() >= lotPrices_[_lotID].startTime) {
if (lotPrices_[_lotID].biddable == false) {
auctionHubInstance_.lotAuctionStarted(auctionID_, _lotID);
lotPrices_[_lotID].biddable = true;
}
}
lotPrices_[_lotID].biddable = false;
return false;
}
}
| 10,077,849 |
// Verified using https://dapp.tools
// hevm: flattened sources of ./contracts/2021/Proposal20.sol
pragma solidity =0.5.15 >=0.5.15 <0.6.0;
pragma experimental ABIEncoderV2;
////// lib/yamV3/contracts/lib/IERC20.sol
/* pragma solidity ^0.5.15; */
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20_2 {
/**
* @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);
}
////// lib/yamV3/contracts/lib/Address.sol
/* pragma solidity ^0.5.15; */
/**
* @dev Collection of functions related to the address type
*/
library Address_2 {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// lib/yamV3/contracts/lib/SafeMath.sol
/* pragma solidity ^0.5.15; */
/**
* @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_2 {
/**
* @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;
}
}
////// lib/yamV3/contracts/lib/SafeERC20.sol
/* pragma solidity ^0.5.15; */
/* import "./IERC20.sol"; */
/* import "./SafeMath.sol"; */
/* import "./Address.sol"; */
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20_2 {
using SafeMath_2 for uint256;
using Address_2 for address;
function safeTransfer(IERC20_2 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20_2 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_2 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_2 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_2 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_2 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");
}
}
}
////// lib/yamV3/contracts/token/YAMGovernanceStorage.sol
/* pragma solidity 0.5.15; */
/* pragma experimental ABIEncoderV2; */
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
contract YAMGovernanceStorage {
/// @notice A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
}
////// lib/yamV3/contracts/token/YAMTokenStorage.sol
/* pragma solidity 0.5.15; */
/* import "../lib/SafeMath.sol"; */
// Storage for a YAM token
contract YAMTokenStorage {
using SafeMath_2 for uint256;
/**
* @dev Guard variable for re-entrancy checks. Not currently used
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/**
* @notice Approved rebaser for this contract
*/
address public rebaser;
/**
* @notice Approved migrator for this contract
*/
address public migrator;
/**
* @notice Incentivizer address of YAM protocol
*/
address public incentivizer;
/**
* @notice Total supply of YAMs
*/
uint256 public totalSupply;
/**
* @notice Internal decimals used to handle scaling factor
*/
uint256 public constant internalDecimals = 10**24;
/**
* @notice Used for percentage maths
*/
uint256 public constant BASE = 10**18;
/**
* @notice Scaling factor that adjusts everyone's balances
*/
uint256 public yamsScalingFactor;
mapping (address => uint256) internal _yamBalances;
mapping (address => mapping (address => uint256)) internal _allowedFragments;
uint256 public initSupply;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
bytes32 public DOMAIN_SEPARATOR;
}
////// lib/yamV3/contracts/token/YAMTokenInterface.sol
/* pragma solidity 0.5.15; */
/* import "./YAMTokenStorage.sol"; */
/* import "./YAMGovernanceStorage.sol"; */
contract YAMTokenInterface is YAMTokenStorage, YAMGovernanceStorage {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Event emitted when tokens are rebased
*/
event Rebase(uint256 epoch, uint256 prevYamsScalingFactor, uint256 newYamsScalingFactor);
/*** Gov Events ***/
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(address oldPendingGov, address newPendingGov);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(address oldGov, address newGov);
/**
* @notice Sets the rebaser contract
*/
event NewRebaser(address oldRebaser, address newRebaser);
/**
* @notice Sets the migrator contract
*/
event NewMigrator(address oldMigrator, address newMigrator);
/**
* @notice Sets the incentivizer contract
*/
event NewIncentivizer(address oldIncentivizer, address newIncentivizer);
/* - ERC20 Events - */
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/* - Extra Events - */
/**
* @notice Tokens minted event
*/
event Mint(address to, uint256 amount);
/**
* @notice Tokens burned event
*/
event Burn(address from, uint256 amount);
// Public functions
function transfer(address to, uint256 value) external returns(bool);
function transferFrom(address from, address to, uint256 value) external returns(bool);
function balanceOf(address who) external view returns(uint256);
function balanceOfUnderlying(address who) external view returns(uint256);
function allowance(address owner_, address spender) external view returns(uint256);
function approve(address spender, uint256 value) external returns (bool);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
function maxScalingFactor() external view returns (uint256);
function yamToFragment(uint256 yam) external view returns (uint256);
function fragmentToYam(uint256 value) external view returns (uint256);
/* - Governance Functions - */
function getPriorVotes(address account, uint blockNumber) external view returns (uint256);
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external;
function delegate(address delegatee) external;
function delegates(address delegator) external view returns (address);
function getCurrentVotes(address account) external view returns (uint256);
/* - Permissioned/Governance functions - */
function mint(address to, uint256 amount) external returns (bool);
function burn(uint256 amount) external returns (bool);
function rebase(uint256 epoch, uint256 indexDelta, bool positive) external returns (uint256);
function _setRebaser(address rebaser_) external;
function _setIncentivizer(address incentivizer_) external;
function _setPendingGov(address pendingGov_) external;
function _acceptGov() external;
}
////// lib/yamV3/contracts/token/YAMGovernance.sol
/* pragma solidity 0.5.15; */
/* pragma experimental ABIEncoderV2; */
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* import "./YAMGovernanceStorage.sol"; */
/* import "./YAMTokenInterface.sol"; */
contract YAMGovernanceToken is YAMTokenInterface {
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Get delegatee for an address delegating
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "YAM::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "YAM::delegateBySig: invalid nonce");
require(now <= expiry, "YAM::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "YAM::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = _yamBalances[delegator]; // balance of underlying YAMs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "YAM::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
////// lib/yamV3/contracts/token/YAMLogic3.sol
/* pragma solidity 0.5.15; */
/* import "./YAMTokenInterface.sol"; */
/* import "../token/YAMGovernance.sol"; */
/* import "../lib/SafeERC20.sol"; */
contract YAMToken is YAMGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyMinter() {
require(
msg.sender == rebaser
|| msg.sender == gov
|| msg.sender == incentivizer
|| msg.sender == migrator,
"not minter"
);
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(yamsScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * yamsScalingFactor
// this is used to check if yamsScalingFactor will be too high to compute balances when rebasing.
return uint256(-1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
if (msg.sender == migrator) {
// migrator directly uses v2 balance for the amount
// increase initSupply
initSupply = initSupply.add(amount);
// get external value
uint256 scaledAmount = _yamToFragment(amount);
// increase totalSupply
totalSupply = totalSupply.add(scaledAmount);
// make sure the mint didnt push maxScalingFactor too low
require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_yamBalances[to] = _yamBalances[to].add(amount);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], amount);
emit Mint(to, scaledAmount);
emit Transfer(address(0), to, scaledAmount);
} else {
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 yamValue = _fragmentToYam(amount);
// increase initSupply
initSupply = initSupply.add(yamValue);
// make sure the mint didnt push maxScalingFactor too low
require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_yamBalances[to] = _yamBalances[to].add(yamValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], yamValue);
emit Mint(to, amount);
emit Transfer(address(0), to, amount);
}
}
/**
* @notice Burns tokens from msg.sender, decreases totalSupply, initSupply, and a users balance.
*/
function burn(uint256 amount)
external
returns (bool)
{
_burn(amount);
return true;
}
function _burn(uint256 amount)
internal
{
// decrease totalSupply
totalSupply = totalSupply.sub(amount);
// get underlying value
uint256 yamValue = _fragmentToYam(amount);
// decrease initSupply
initSupply = initSupply.sub(yamValue);
// decrease balance
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
// add delegates to the minter
_moveDelegates(_delegates[msg.sender], address(0), yamValue);
emit Burn(msg.sender, amount);
emit Transfer(msg.sender, address(0), amount);
}
/**
* @notice Mints new tokens using underlying amount, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mintUnderlying(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mintUnderlying(to, amount);
return true;
}
function _mintUnderlying(address to, uint256 amount)
internal
{
// increase initSupply
initSupply = initSupply.add(amount);
// get external value
uint256 scaledAmount = _yamToFragment(amount);
// increase totalSupply
totalSupply = totalSupply.add(scaledAmount);
// make sure the mint didnt push maxScalingFactor too low
require(yamsScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_yamBalances[to] = _yamBalances[to].add(amount);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], amount);
emit Mint(to, scaledAmount);
emit Transfer(address(0), to, scaledAmount);
}
/**
* @dev Transfer underlying balance to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transferUnderlying(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// sub from balance of sender
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(value);
// add to balance of receiver
_yamBalances[to] = _yamBalances[to].add(value);
emit Transfer(msg.sender, to, _yamToFragment(value));
_moveDelegates(_delegates[msg.sender], _delegates[to], value);
return true;
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in yams, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == yamsScalingFactor / 1e24;
// get amount in underlying
uint256 yamValue = _fragmentToYam(value);
// sub from balance of sender
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
// add to balance of receiver
_yamBalances[to] = _yamBalances[to].add(yamValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], yamValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in yams
uint256 yamValue = _fragmentToYam(value);
// sub from from
_yamBalances[from] = _yamBalances[from].sub(yamValue);
_yamBalances[to] = _yamBalances[to].add(yamValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], yamValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _yamToFragment(_yamBalances[who]);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _yamBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
// --- Approve by signature ---
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(now <= deadline, "YAM/permit-expired");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
require(owner != address(0), "YAM/invalid-address-0");
require(owner == ecrecover(digest, v, r, s), "YAM/invalid-permit");
_allowedFragments[owner][spender] = value;
emit Approval(owner, spender, value);
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the migrator
* @param migrator_ The address of the migrator contract to use for authentication.
*/
function _setMigrator(address migrator_)
external
onlyGov
{
address oldMigrator = migrator_;
migrator = migrator_;
emit NewMigrator(oldMigrator, migrator_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice allows governance to assign delegate to self
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
function assignSelfDelegate(address nonvotingContract)
external
onlyGov
{
address delegate = _delegates[nonvotingContract];
require( delegate == address(0), "!address(0)" );
// assigns delegate to self only
_delegate(nonvotingContract, nonvotingContract);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
// no change
if (indexDelta == 0) {
emit Rebase(epoch, yamsScalingFactor, yamsScalingFactor);
return totalSupply;
}
// for events
uint256 prevYamsScalingFactor = yamsScalingFactor;
if (!positive) {
// negative rebase, decrease scaling factor
yamsScalingFactor = yamsScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
// positive reabse, increase scaling factor
uint256 newScalingFactor = yamsScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
yamsScalingFactor = newScalingFactor;
} else {
yamsScalingFactor = _maxScalingFactor();
}
}
// update total supply, correctly
totalSupply = _yamToFragment(initSupply);
emit Rebase(epoch, prevYamsScalingFactor, yamsScalingFactor);
return totalSupply;
}
function yamToFragment(uint256 yam)
external
view
returns (uint256)
{
return _yamToFragment(yam);
}
function fragmentToYam(uint256 value)
external
view
returns (uint256)
{
return _fragmentToYam(value);
}
function _yamToFragment(uint256 yam)
internal
view
returns (uint256)
{
return yam.mul(yamsScalingFactor).div(internalDecimals);
}
function _fragmentToYam(uint256 value)
internal
view
returns (uint256)
{
return value.mul(internalDecimals).div(yamsScalingFactor);
}
// Rescue tokens
function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
{
// transfer to
SafeERC20_2.safeTransfer(IERC20_2(token), to, amount);
return true;
}
}
contract YAMLogic3 is YAMToken {
/**
* @notice Initialize the new money market
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
*/
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initTotalSupply_
)
public
{
super.initialize(name_, symbol_, decimals_);
yamsScalingFactor = BASE;
initSupply = _fragmentToYam(initTotalSupply_);
totalSupply = initTotalSupply_;
_yamBalances[initial_owner] = initSupply;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
}
}
////// lib/yamV3/contracts/token/YAMDelegate3.sol
/* pragma solidity 0.5.15; */
/* Copyright 2020 Compound Labs, Inc.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/* import "./YAMLogic3.sol"; */
contract YAMDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract YAMDelegatorInterface is YAMDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the gov to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract YAMDelegateInterface is YAMDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
contract YAMDelegate3 is YAMLogic3, YAMDelegateInterface {
/**
* @notice Construct an empty delegate
*/
constructor() public {}
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public {
// Shh -- currently unused
data;
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _becomeImplementation");
}
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public {
// Shh -- we don't ever want this hook to be marked pure
if (false) {
implementation = address(0);
}
require(msg.sender == gov, "only the gov may call _resignImplementation");
}
}
////// lib/yamV3/contracts/tests/vesting_pool/VestingPool.sol
/* pragma solidity 0.5.15; */
/* import "../../lib/SafeERC20.sol"; */
/* import {YAMDelegate3} from "../../token/YAMDelegate3.sol"; */
contract VestingPool {
using SafeMath_2 for uint256;
using SafeMath_2 for uint128;
struct Stream {
address recipient;
uint128 startTime;
uint128 length;
uint256 totalAmount;
uint256 amountPaidOut;
}
/**
* @notice Governor for this contract
*/
address public gov;
/**
* @notice Pending governance for this contract
*/
address public pendingGov;
/// @notice Mapping containing valid stream managers
mapping(address => bool) public isSubGov;
/// @notice Amount of tokens allocated to streams that hasn't yet been claimed
uint256 public totalUnclaimedInStreams;
/// @notice The number of streams created so far
uint256 public streamCount;
/// @notice All streams
mapping(uint256 => Stream) public streams;
/// @notice YAM token
YAMDelegate3 public yam;
/**
* @notice Event emitted when a sub gov is enabled/disabled
*/
event SubGovModified(
address account,
bool isSubGov
);
/**
* @notice Event emitted when stream is opened
*/
event StreamOpened(
address indexed account,
uint256 indexed streamId,
uint256 length,
uint256 totalAmount
);
/**
* @notice Event emitted when stream is closed
*/
event StreamClosed(uint256 indexed streamId);
/**
* @notice Event emitted on payout
*/
event Payout(
uint256 indexed streamId,
address indexed recipient,
uint256 amount
);
/**
* @notice Event emitted when pendingGov is changed
*/
event NewPendingGov(
address oldPendingGov,
address newPendingGov
);
/**
* @notice Event emitted when gov is changed
*/
event NewGov(
address oldGov,
address newGov
);
constructor(YAMDelegate3 _yam)
public
{
gov = msg.sender;
yam = _yam;
}
modifier onlyGov() {
require(msg.sender == gov, "VestingPool::onlyGov: account is not gov");
_;
}
modifier canManageStreams() {
require(
isSubGov[msg.sender] || (msg.sender == gov),
"VestingPool::canManageStreams: account cannot manage streams"
);
_;
}
/**
* @dev Set whether an account can open/close streams. Only callable by the current gov contract
* @param account The account to set permissions for.
* @param _isSubGov Whether or not this account can manage streams
*/
function setSubGov(address account, bool _isSubGov)
public
onlyGov
{
isSubGov[account] = _isSubGov;
emit SubGovModified(account, _isSubGov);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice accepts governance over this contract
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/**
* @dev Opens a new stream that continuously pays out.
* @param recipient Account that will receive the funds.
* @param length The amount of time in seconds that the stream lasts
* @param totalAmount The total amount to payout in the stream
*/
function openStream(
address recipient,
uint128 length,
uint256 totalAmount
)
public
canManageStreams
returns (uint256 streamIndex)
{
streamIndex = streamCount++;
streams[streamIndex] = Stream({
recipient: recipient,
length: length,
startTime: uint128(block.timestamp),
totalAmount: totalAmount,
amountPaidOut: 0
});
totalUnclaimedInStreams = totalUnclaimedInStreams.add(totalAmount);
require(
totalUnclaimedInStreams <= yam.balanceOfUnderlying(address(this)),
"VestingPool::payout: Total streaming is greater than pool's YAM balance"
);
emit StreamOpened(recipient, streamIndex, length, totalAmount);
}
/**
* @dev Closes the specified stream. Pays out pending amounts, clears out the stream, and emits a StreamClosed event.
* @param streamId The id of the stream to close.
*/
function closeStream(uint256 streamId)
public
canManageStreams
{
payout(streamId);
streams[streamId] = Stream(
address(0x0000000000000000000000000000000000000000),
0,
0,
0,
0
);
emit StreamClosed(streamId);
}
/**
* @dev Pays out pending amount in a stream
* @param streamId The id of the stream to payout.
* @return The amount paid out in underlying
*/
function payout(uint256 streamId)
public
returns (uint256 paidOut)
{
uint128 currentTime = uint128(block.timestamp);
Stream memory stream = streams[streamId];
require(
stream.startTime <= currentTime,
"VestingPool::payout: Stream hasn't started yet"
);
uint256 claimableUnderlying = _claimable(stream);
streams[streamId].amountPaidOut = stream.amountPaidOut.add(
claimableUnderlying
);
totalUnclaimedInStreams = totalUnclaimedInStreams.sub(
claimableUnderlying
);
yam.transferUnderlying(stream.recipient, claimableUnderlying);
emit Payout(streamId, stream.recipient, claimableUnderlying);
return claimableUnderlying;
}
/**
* @dev The amount that is claimable for a stream
* @param streamId The stream to get the claimabout amount for.
* @return The amount that is claimable for this stream
*/
function claimable(uint256 streamId)
external
view
returns (uint256 claimableUnderlying)
{
Stream memory stream = streams[streamId];
return _claimable(stream);
}
function _claimable(Stream memory stream)
internal
view
returns (uint256 claimableUnderlying)
{
uint128 currentTime = uint128(block.timestamp);
uint128 elapsedTime = currentTime - stream.startTime;
if (currentTime >= stream.startTime + stream.length) {
claimableUnderlying = stream.totalAmount - stream.amountPaidOut;
} else {
claimableUnderlying = elapsedTime
.mul(stream.totalAmount)
.div(stream.length)
.sub(stream.amountPaidOut);
}
}
}
////// ./contracts/2021/Proposal20.sol
/* pragma solidity 0.5.15; */
/* pragma experimental ABIEncoderV2; */
/* import {VestingPool} from "yamV3/tests/vesting_pool/VestingPool.sol"; */
/* import {YAMTokenInterface} from "yamV3/token/YAMTokenInterface.sol"; */
/* import {IERC20} from "yamV3/lib/IERC20.sol"; */
interface YVault {
function deposit(uint256 amount, address recipient)
external
returns (uint256);
function withdraw(uint256 amount) external returns (uint256);
}
contract Proposal20 {
// @dev Contracts and ERC20 addresses
IERC20_2 internal constant USDC = IERC20_2(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
YVault internal constant yUSDC = YVault(0x5f18C75AbDAe578b483E5F43f12a39cF75b973a9);
VestingPool internal constant pool = VestingPool(0xDCf613db29E4d0B35e7e15e93BF6cc6315eB0b82);
address internal constant RESERVES = 0x97990B693835da58A281636296D2Bf02787DEa17;
function execute() public {
IERC20_2(address(yUSDC)).transferFrom(
RESERVES,
address(this),
IERC20_2(address(yUSDC)).balanceOf(RESERVES)
);
yUSDC.withdraw(uint256(-1));
// Stablecoin transfers
// E
USDC.transfer(
0x8A8acf1cEcC4ed6Fe9c408449164CE2034AdC03f,
yearlyUSDToMonthlyUSD(120000 * (10**6), 2)
);
// Chilly
USDC.transfer(
0x01e0C7b70E0E05a06c7cC8deeb97Fa03d6a77c9C,
yearlyUSDToMonthlyUSD(84000 * (10**6), 2)
);
// Krguman
USDC.transfer(
0xcc506b3c2967022094C3B00276617883167BF32B,
yearlyUSDToMonthlyUSD(30000 * (10**6), 2)
);
// Designer
USDC.transfer(
0x3FdcED6B5C1f176b543E5E0b841cB7224596C33C,
yearlyUSDToMonthlyUSD(96000 * (10**6), 2)
);
// Ross
USDC.transfer(
0x88c868B1024ECAefDc648eb152e91C57DeA984d0,
yearlyUSDToMonthlyUSD(84000 * (10**6), 2)
);
// Blokku
USDC.transfer(
0x392027fDc620d397cA27F0c1C3dCB592F27A4dc3,
yearlyUSDToMonthlyUSD(22500 * (10**6), 2)
);
// Kris
USDC.transfer(
0x386568164bdC5B105a66D8Ae83785D4758939eE6,
yearlyUSDToMonthlyUSD(15000 * (10**6), 2)
);
// Will
USDC.transfer(
0x31920DF2b31B5f7ecf65BDb2c497DE31d299d472,
yearlyUSDToMonthlyUSD(84000 * (10**6), 2)
);
// Snake
USDC.transfer(
0xce1559448e21981911fAC70D4eC0C02cA1EFF39C,
yearlyUSDToMonthlyUSD(28800 * (10**6), 2)
);
// Joe
USDC.transfer(
0x1Ba2A537A771AA4EaC2f18427716557e4E744864,
yearlyUSDToMonthlyUSD(28800 * (10**6), 2)
);
// Nate
USDC.transfer(
0xEC3281124d4c2FCA8A88e3076C1E7749CfEcb7F2,
yearlyUSDToMonthlyUSD(26256 * (10**6), 1)
);
// VDM
USDC.transfer(
0xFcB4f3a1710FefA583e7b003F3165f2E142bC725,
yearlyUSDToMonthlyUSD(42000 * (10**6), 2)
);
// Jason
USDC.transfer(
0x43fD74401B4BF04095590a5308B6A5e3Db44b9e3,
yearlyUSDToMonthlyUSD(48000 * (10**6), 1)
);
uint256 usdcBalance = USDC.balanceOf(address(this));
USDC.approve(address(yUSDC), usdcBalance);
yUSDC.deposit(usdcBalance, RESERVES);
// Streams
// Update E stream
pool.closeStream(13);
pool.openStream(
0x8A8acf1cEcC4ed6Fe9c408449164CE2034AdC03f,
90 days,
10303 * (10**24) * 3
);
// Update Chilly stream
pool.closeStream(17);
pool.openStream(
0x01e0C7b70E0E05a06c7cC8deeb97Fa03d6a77c9C,
90 days,
2436 * (10**24) * 3
);
// Update Krugman stream
pool.closeStream(18);
pool.openStream(
0xcc506b3c2967022094C3B00276617883167BF32B,
90 days,
727 * (10**24) * 3
);
// Update Mona stream
pool.closeStream(23);
pool.openStream(
0xdADc6F71986643d9e9CB368f08Eb6F1333F6d8f9,
90 days,
1212 * (10**24) * 3
);
// Update Byterose stream
pool.closeStream(60);
pool.openStream(
0xbe9Bb7a473DE5c043146B24AbfA72AB81aee67CD,
90 days,
7273 * (10**24) * 3
);
// Byterose stream previous pay
pool.openStream(
0xbe9Bb7a473DE5c043146B24AbfA72AB81aee67CD,
0 days,
7273 * (10**24)
);
// Update Nate stream
pool.closeStream(14);
}
function yearlyUSDToMonthlyUSD(uint256 yearlyUSD, uint256 months) internal pure returns (uint256) {
return ((yearlyUSD / uint256(12)) * months);
}
}
|
decrease totalSupply get underlying value decrease initSupply decrease balance add delegates to the minter
|
function _burn(uint256 amount)
internal
{
totalSupply = totalSupply.sub(amount);
uint256 yamValue = _fragmentToYam(amount);
initSupply = initSupply.sub(yamValue);
_yamBalances[msg.sender] = _yamBalances[msg.sender].sub(yamValue);
_moveDelegates(_delegates[msg.sender], address(0), yamValue);
emit Burn(msg.sender, amount);
emit Transfer(msg.sender, address(0), amount);
}
| 129,233 |
./full_match/1/0x1cdb31a227193a709606232Af094185403beA726/sources/contracts/mainnet/SubjectRoot.sol
|
Sets presaleDuration. _presaleDuration uint256 representing the duration of the presale/
|
function setPresaleDuration(uint256 _presaleDuration)
public
virtual
override
onlyDAO
{
require(_presaleDuration > 0, "Presale: not a valid duration!");
presaleDuration = _presaleDuration;
emit PresaleDurationSet(presaleDuration);
}
| 8,448,201 |
./full_match/11155111/0x9A35CB46B76261967CC4fF8cCfa8F634a83c2445/sources/src/common/token/ERC1155/ERC1155.sol
|
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), '');
if (isNonFungible(id)) {
require(nfOwners[id] == account, 'ERC1155: burn amount exceeds balance');
require(amount == 1, 'ERC1155: burn amount exceeds balance');
delete nfOwners[id];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, 'ERC1155: burn amount exceeds balance');
unchecked {
uint256 newBalance = accountBalance - amount;
_balances[id][account] = newBalance;
}
}
emit TransferSingle(operator, account, address(0), id, amount);
}
| 3,827,924 |
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
contract CoreUniLotterySettings
{
// Percentage calculations.
// As Solidity doesn't have floats, we have to use integers for
// percentage arithmetics.
// We set 1 percent to be equal to 1,000,000 - thus, we
// simulate 6 decimal points when computing percentages.
uint32 public constant PERCENT = 10 ** 6;
uint32 constant BASIS_POINT = PERCENT / 100;
uint32 constant _100PERCENT = 100 * PERCENT;
/** The UniLottery Owner's address.
*
* In the current version, The Owner has rights to:
* - Take up to 10% profit from every lottery.
* - Pool liquidity into the pool and remove it.
* - Start lotteries in auto or manual mode.
*/
// Public Testnets: 0xb13CB9BECcB034392F4c9Db44E23C3Fb5fd5dc63
// MainNet: 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2
address payable public constant OWNER_ADDRESS =
address( uint160( 0x1Ae51bec001a4fA4E3b06A5AF2e0df33A79c01e2 ) );
// Maximum lottery fee the owner can imburse on transfers.
uint32 constant MAX_OWNER_LOTTERY_FEE = 1 * PERCENT;
// Minimum amout of profit percentage that must be distributed
// to lottery winners.
uint32 constant MIN_WINNER_PROFIT_SHARE = 40 * PERCENT;
// Min & max profits the owner can take from lottery net profit.
uint32 constant MIN_OWNER_PROFITS = 3 * PERCENT;
uint32 constant MAX_OWNER_PROFITS = 10 * PERCENT;
// Min & max amount of lottery profits that the pool must get.
uint32 constant MIN_POOL_PROFITS = 10 * PERCENT;
uint32 constant MAX_POOL_PROFITS = 60 * PERCENT;
// Maximum lifetime of a lottery - 1 month (4 weeks).
uint32 constant MAX_LOTTERY_LIFETIME = 4 weeks;
// Callback gas requirements for a lottery's ending callback,
// and for the Pool's Scheduled Callback.
// Must be determined empirically.
uint32 constant LOTTERY_RAND_CALLBACK_GAS = 200000;
uint32 constant AUTO_MODE_SCHEDULED_CALLBACK_GAS = 3800431;
}
interface IUniswapRouter
{
// Get Factory and WETH addresses.
function factory() external pure returns (address);
function WETH() external pure returns (address);
// Create/add to a liquidity pair using ETH.
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
payable
returns (
uint amountToken,
uint amountETH,
uint liquidity
);
// Remove liquidity pair.
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline )
external
returns (
uint amountETH
);
// Get trade output amount, given an input.
function getAmountsOut(
uint amountIn,
address[] memory path )
external view
returns (
uint[] memory amounts
);
// Get trade input amount, given an output.
function getAmountsIn(
uint amountOut,
address[] memory path )
external view
returns (
uint[] memory amounts
);
}
interface IUniswapFactory
{
function getPair(
address tokenA,
address tokenB )
external view
returns ( address pair );
}
contract UniLotteryConfigGenerator
{
function getConfig()
external pure
returns( Lottery.LotteryConfig memory cfg )
{
cfg.initialFunds = 10 ether;
}
}
contract UniLotteryLotteryFactory
{
// Uniswap Router address on this network - passed to Lotteries on
// construction.
//ddress payable immutable uniRouterAddress;
// Delegate Contract for the Lottery, containing all logic code
// needed for deploying LotteryStubs.
// Deployed only once, on construction.
address payable immutable delegateContract;
// The Pool Address.
address payable poolAddress;
// The Lottery Storage Factory address, that the Lottery contracts use.
UniLotteryStorageFactory lotteryStorageFactory;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Set the Uniswap Address, and deploy&lock the Delegate Code contract.
//
constructor( /*address payable _uniRouter*/ ) public
{
//uniRouterAddress = _uniRouter;
delegateContract = address( uint160( address( new Lottery() ) ) );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
// Also, set the Lottery Storage Factory contract instance address.
function initialize( address _storageFactoryAddress )
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
// Lock it. No more calls to this function will be executed.
poolAddress = msg.sender;
// Set the Storage Factory, and initialize it!
lotteryStorageFactory =
UniLotteryStorageFactory( _storageFactoryAddress );
lotteryStorageFactory.initialize();
}
/**
* Deploy a new Lottery Stub from the specified config.
* @param config - Lottery Config to be used (passed by the pool).
* @return newLottery - the newly deployed lottery stub.
*/
function createNewLottery(
Lottery.LotteryConfig memory config,
address randomnessProvider )
public
poolOnly
returns( address payable newLottery )
{
// Create new Lottery Storage, using storage factory.
// Populate the stub, by calling the "construct" function.
LotteryStub stub = new LotteryStub( delegateContract );
Lottery( address( stub ) ).construct(
config, poolAddress, randomnessProvider,
lotteryStorageFactory.createNewStorage() );
return address( stub );
}
}
contract LotteryStub
{
// ============ ERC20 token contract's storage ============ //
// ------- Slot ------- //
// Balances of token holders.
mapping (address => uint256) private _balances;
// ------- Slot ------- //
// Allowances of spenders for a specific token owner.
mapping (address => mapping (address => uint256)) private _allowances;
// ------- Slot ------- //
// Total supply of the token.
uint256 private _totalSupply;
// ============== Lottery contract's storage ============== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
Lottery.LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage /*public*/ lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable /*public*/ poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address /*public*/ randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address /*public*/ exchangeAddress;
// Start date.
uint32 /*public*/ startDate;
// Completion (Mining Phase End) date.
uint32 /*public*/ completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 /*public*/ lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 /*public*/ ending_totalReturn;
uint128 /*public*/ ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) /*public*/ prizeClaimersAddresses;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address payable immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address payable _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback payable function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external payable
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
// Receive ether function.
receive() external payable
{ }
}
contract LotteryStorageStub
{
// =============== LotteryStorage contract's storage ================ //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
LotteryStorage.WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
LotteryStorage.MinMaxHolderScores minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] /*public*/ holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => LotteryStorage.HolderData ) /*public*/ holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
LotteryStorage.WinnerIndexStruct[] sortedWinnerIndexes;
// =================== OUR CONTRACT'S OWN STORAGE =================== //
// The address of the delegate contract, containing actual logic.
address immutable public __delegateContract;
// =================== Functions =================== //
// Constructor.
// Just set the delegate's address.
constructor( address _delegateAddr )
public
{
__delegateContract = _delegateAddr;
}
// Fallback function, which delegates any call to our
// contract, into the delegate contract.
fallback()
external
{
// DelegateCall the delegate code contract.
( bool success, bytes memory data ) =
__delegateContract.delegatecall( msg.data );
// Use inline assembly to be able to return value from the fallback.
// (by default, returning a value from fallback is not possible,
// but it's still possible to manually copy data to the
// return buffer.
assembly
{
// delegatecall returns 0 (false) on error.
// Add 32 bytes to "data" pointer, because first slot (32 bytes)
// contains the length, and we use return value's length
// from returndatasize() opcode.
switch success
case 0 { revert( add( data, 32 ), returndatasize() ) }
default { return( add( data, 32 ), returndatasize() ) }
}
}
}
interface IUniLotteryPool
{
function lotteryFinish( uint totalReturn, uint profitAmount )
external payable;
}
interface IRandomnessProvider
{
function requestRandomSeedForLotteryFinish() external;
}
contract LotteryStorage is CoreUniLotterySettings
{
// ==================== Structs & Constants ==================== //
// Struct of holder data & scores.
struct HolderData
{
// --------- Slot --------- //
// If this holder has generated his own referral ID, this is
// that ID. If he hasn't generated an ID, this is zero.
uint256 referralID;
// --------- Slot --------- //
// If this holder provided a valid referral ID, this is the
// address of a referrer - the user who generated the said
// referral ID.
address referrer;
// --------- Slot --------- //
// The intermediate score factor variables.
// Ether contributed: ( buys - sells ). Can be negative.
int80 etherContributed;
// Time x ether factor: (relativeTxTime * etherAmount).
int80 timeFactors;
// Token balance score factor of this holder - we use int,
// for easier computation of player scores in our algorithms.
int80 tokenBalance;
// Number of all child referrees, including multi-level ones.
// Updated by traversing child->parent way, incrementing
// every node's counter by one.
// Used in Winner Selection Algorithm, to determine how much
// to divide the accumulated referree scores by.
uint16 referreeCount;
// --------- Slot --------- //
// Accumulated referree score factors - ether contributed by
// all referrees, time factors, and token balances of all
// referrees.
// Can be negative!
int80 referree_etherContributed;
int80 referree_timeFactors;
int80 referree_tokenBalance;
// Bonus score points, which can be given in certain events,
// such as when player registers a valid referral ID.
int16 bonusScore;
}
// Final Score (end lottery score * randomValue) structure.
struct FinalScore
{
address addr; // 20 bytes \
uint16 holderIndex; // 2 bytes | = 30 bytes => 1 slot.
uint64 score; // 8 bytes /
}
// Winner Indexes structure - used to efficiently store Winner
// indexes in holder's array, after completing the Winner Selection
// Algorithm.
// To save Space, we store these in a struct, with uint16 array
// with 16 items - so this struct takes up excactly 1 slot.
struct WinnerIndexStruct
{
uint16[ 16 ] indexes;
}
// A structure which is used by Winner Selection algorithm,
// which is a subset of the LotteryConfig structure, containing
// only items necessary for executing the Winner Selection algorigm.
// More detailed member description can be found in LotteryConfig
// structure description.
// Takes up only one slot!
struct WinnerAlgorithmConfig
{
// --------- Slot --------- //
// Individual player max score parts.
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// Number of lottery winners.
uint16 winnerCount;
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// The Ending Algorithm type.
uint8 endingAlgoType;
}
// Structure containing the minimum and maximum values of
// holder intermediate scores.
// These values get updated on transfers during ACTIVE stage,
// when holders buy/sell tokens.
// Structure takes up only 2 slots!
//
struct MinMaxHolderScores
{
// --------- Slot --------- //
// Minimum & maximum values for each score factor.
// Updated for holders when they transfer tokens.
// Used in winner selection algorithm, to normalize the scores in
// a single loop, to avoid looping additional time to find min/max.
int80 holderScore_etherContributed_min;
int80 holderScore_etherContributed_max;
int80 holderScore_timeFactors_min;
// --------- Slot --------- //
int80 holderScore_timeFactors_max;
int80 holderScore_tokenBalance_min;
int80 holderScore_tokenBalance_max;
}
// ROOT_REFERRER constant.
// Used to prevent cyclic dependencies on referral tree.
address constant ROOT_REFERRER = address( 1 );
// Precision of division operations.
int constant PRECISION = 10000;
// Random number modulo to use when obtaining random numbers from
// the random seed + nonce, using keccak256.
// This is the maximum available Score Random Factor, plus one.
// By default, 10^9 (one billion).
//
uint constant RANDOM_MODULO = (10 ** 9);
// Maximum number of holders that the MinedWinnerSelection algorithm
// can process. Related to block gas limit.
uint constant MINEDSELECTION_MAX_NUMBER_OF_HOLDERS = 300;
// Maximum number of holders that the WinnerSelfValidation algorithm
// can process. Related to block gas limit.
uint constant SELFVALIDATION_MAX_NUMBER_OF_HOLDERS = 1200;
// ==================== State Variables ==================== //
// --------- Slot --------- //
// The Lottery address that this storage belongs to.
// Is set by the "initialize()", called by corresponding Lottery.
address lottery;
// The Random Seed, that was passed to us from Randomness Provider,
// or generated alternatively.
uint64 randomSeed;
// The actual number of winners that there will be. Set after
// completing the Winner Selection Algorithm.
uint16 numberOfWinners;
// Bool indicating if Winner Selection Algorithm has been executed.
bool algorithmCompleted;
// --------- Slot --------- //
// Winner Algorithm config. Specified in Initialization().
WinnerAlgorithmConfig algConfig;
// --------- Slot --------- //
// The Min-Max holder score storage.
MinMaxHolderScores public minMaxScores;
// --------- Slot --------- //
// Array of holders.
address[] public holders;
// --------- Slot --------- //
// Holder array indexes mapping, for O(1) array element access.
mapping( address => uint ) holderIndexes;
// --------- Slot --------- //
// Mapping of holder data.
mapping( address => HolderData ) public holderData;
// --------- Slot --------- //
// Mapping of referral IDs to addresses of holders who generated
// those IDs.
mapping( uint256 => address ) referrers;
// --------- Slot --------- //
// The array of final-sorted winners (set after Winner Selection
// Algorithm completes), that contains the winners' indexes
// in the "holders" array, to save space.
//
// Notice that by using uint16, we can fit 16 items into one slot!
// So, if there are 160 winners, we only take up 10 slots, so
// only 20,000 * 10 = 200,000 gas gets consumed!
//
WinnerIndexStruct[] sortedWinnerIndexes;
// ============== Internal (Private) Functions ============== //
// Lottery-Only modifier.
modifier lotteryOnly
{
require( msg.sender == address( lottery ) );
_;
}
// ============== [ BEGIN ] LOTTERY QUICKSORT FUNCTIONS ============== //
/**
* QuickSort and QuickSelect algorithm functionality code.
*
* These algorithms are used to find the lottery winners in
* an array of final random-factored scores.
* As the highest-scorers win, we need to sort an array to
* identify them.
*
* For this task, we use QuickSelect to partition array into
* winner part (elements with score larger than X, where X is
* n-th largest element, where n is number of winners),
* and others (non-winners), who are ignored to save computation
* power.
* Then we sort the winner part only, using QuickSort, and
* distribute prizes to winners accordingly.
*/
// Swap function used in QuickSort algorithms.
//
function QSort_swap( FinalScore[] memory list,
uint a, uint b )
internal pure
{
FinalScore memory tmp = list[ a ];
list[ a ] = list[ b ];
list[ b ] = tmp;
}
// Standard Hoare's partition scheme function, used for both
// QuickSort and QuickSelect.
//
function QSort_partition(
FinalScore[] memory list,
int lo, int hi )
internal pure
returns( int newPivotIndex )
{
uint64 pivot = list[ uint( hi + lo ) / 2 ].score;
int i = lo - 1;
int j = hi + 1;
while( true )
{
do {
i++;
} while( list[ uint( i ) ].score > pivot ) ;
do {
j--;
} while( list[ uint( j ) ].score < pivot ) ;
if( i >= j )
return j;
QSort_swap( list, uint( i ), uint( j ) );
}
}
// QuickSelect's Lomuto partition scheme.
//
function QSort_LomutoPartition(
FinalScore[] memory list,
uint left, uint right, uint pivotIndex )
internal pure
returns( uint newPivotIndex )
{
uint pivotValue = list[ pivotIndex ].score;
QSort_swap( list, pivotIndex, right ); // Move pivot to end
uint storeIndex = left;
for( uint i = left; i < right; i++ )
{
if( list[ i ].score > pivotValue ) {
QSort_swap( list, storeIndex, i );
storeIndex++;
}
}
// Move pivot to its final place, and return the pivot's index.
QSort_swap( list, right, storeIndex );
return storeIndex;
}
// QuickSelect algorithm (iterative).
//
function QSort_QuickSelect(
FinalScore[] memory list,
int left, int right, int k )
internal pure
returns( int indexOfK )
{
while( true ) {
if( left == right )
return left;
int pivotIndex = int( QSort_LomutoPartition( list,
uint(left), uint(right), uint(right) ) );
if( k == pivotIndex )
return k;
else if( k < pivotIndex )
right = pivotIndex - 1;
else
left = pivotIndex + 1;
}
}
// Standard QuickSort function.
//
function QSort_QuickSort(
FinalScore[] memory list,
int lo, int hi )
internal pure
{
if( lo < hi ) {
int p = QSort_partition( list, lo, hi );
QSort_QuickSort( list, lo, p );
QSort_QuickSort( list, p + 1, hi );
}
}
// ============== [ END ] LOTTERY QUICKSORT FUNCTIONS ============== //
// ------------ Ending Stage - Winner Selection Algorithm ------------ //
/**
* Compute the individual player score factors for a holder.
* Function split from the below one (ending_Stage_2), to avoid
* "Stack too Deep" errors.
*/
function computeHolderIndividualScores(
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int individualScore )
{
// Normalize the scores, by subtracting minimum and dividing
// by maximum, to get the score values specified in cfg.
// Use precision of 100, then round.
//
// Notice that we're using int arithmetics, so division
// truncates. That's why we use PRECISION, to simulate
// rounding.
//
// This formula is better explained in example.
// In this example, we use variable abbreviations defined
// below, on formula's right side comments.
//
// Say, values are these in our example:
// e = 4, eMin = 1, eMax = 8, MS = 5, P = 10.
//
// So, let's calculate the score using the formula:
// ( ( ( (4 - 1) * 10 * 5 ) / (8 - 1) ) + (10 / 2) ) / 10 =
// ( ( ( 3 * 10 * 5 ) / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( ( 150 / 7 ) + 5 ) / 10 =
// ( 20 + 5 ) / 10 =
// 25 / 10 =
// [ 2.5 ] = 2
//
// So, with truncation, we see that for e = 4, the score
// is 2 out of 5 maximum.
// That's because the minimum ether contributed was 1, and
// maximum was 8.
// So, 4 stays below the middle, and gets a nicely rounded
// score of 2.
// Compute etherContributed.
int score_etherContributed = ( (
( ( hdata.etherContributed - // e
minMax.holderScore_etherContributed_min ) // eMin
* PRECISION * cfg.maxPlayerScore_etherContributed ) // P * MS
/ ( minMax.holderScore_etherContributed_max - // eMax
minMax.holderScore_etherContributed_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute timeFactors.
int score_timeFactors = ( (
( ( hdata.timeFactors - // e
minMax.holderScore_timeFactors_min ) // eMin
* PRECISION * cfg.maxPlayerScore_timeFactor ) // P * MS
/ ( minMax.holderScore_timeFactors_max - // eMax
minMax.holderScore_timeFactors_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Compute tokenBalance.
int score_tokenBalance = ( (
( ( hdata.tokenBalance - // e
minMax.holderScore_tokenBalance_min ) // eMin
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max - // eMax
minMax.holderScore_tokenBalance_min ) // eMin
) + (PRECISION / 2) ) / PRECISION;
// Return the accumulated individual score (excluding referrees).
return score_etherContributed + score_timeFactors +
score_tokenBalance;
}
/**
* Split-function, to avoid "Stack-2-Deep" errors.
* Computes a single component of a Referree Score.
*/
/*function priv_computeSingleReferreeComponent(
int _referreeScore_,
int _maxPlayerScore_,
int _holderScore_min_x_refCount,
int _holderScore_max_x_refCount )
internal pure
returns( int score )
{
score = (
( PRECISION * _maxPlayerScore_ *
( _referreeScore_ - _holderScore_min_x_refCount ) )
/
( _holderScore_max_x_refCount - _holderScore_min_x_refCount )
);
}*/
/**
* Compute the unified Referree-Score of a player, who's got
* the accumulated factor-scores of all his referrees in his
* holderData structure.
*
* @param individualToReferralRatio - an int value, computed
* before starting the winner score computation loop, in
* the ending_Stage_2 initial part, to save computation
* time later.
* This is the ratio of the maximum available referral score,
* to the maximum available individual score, as defined in
* the config (for example, if max.ref.score is 20, and
* max.ind.score is 40, then the ratio is 20/40 = 0.5).
*
* We use this ratio to transform the computed accumulated
* referree individual scores to the standard referrer's
* score, by multiplying by that ratio.
*/
function computeReferreeScoresForHolder(
int individualToReferralRatio,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMax,
HolderData memory hdata )
internal pure
returns( int unifiedReferreeScore )
{
// If number of referrees of this HODLer is Zero, then
// his referree score is also zero.
if( hdata.referreeCount == 0 )
return 0;
// Now, compute the Referree's Accumulated Scores.
//
// Here we use the same formula as when computing individual
// scores (in the function above), but we multiply the
// Min & Max known score value by the referree count, because
// the "referree_..." scores are accumulated scores of all
// referrees that that holder has.
// This way, we reach the uniform averaged score of all referrees,
// just like we do with individual scores.
//
// Also, we don't divide them by PRECISION, to accumulate and use
// the max-score-options in the main score computing function.
int refCount = int( hdata.referreeCount );
// Compute etherContributed.
int referreeScore_etherContributed = (
( ( hdata.referree_etherContributed -
minMax.holderScore_etherContributed_min * refCount )
* PRECISION * cfg.maxPlayerScore_etherContributed )
/ ( minMax.holderScore_etherContributed_max * refCount -
minMax.holderScore_etherContributed_min * refCount )
);
// Compute timeFactors.
int referreeScore_timeFactors = (
( ( hdata.referree_timeFactors -
minMax.holderScore_timeFactors_min * refCount )
* PRECISION * cfg.maxPlayerScore_timeFactor )
/ ( minMax.holderScore_timeFactors_max * refCount -
minMax.holderScore_timeFactors_min * refCount )
);
// Compute tokenBalance.
int referreeScore_tokenBalance = (
( ( hdata.referree_tokenBalance -
minMax.holderScore_tokenBalance_min * refCount )
* PRECISION * cfg.maxPlayerScore_tokenHoldingAmount )
/ ( minMax.holderScore_tokenBalance_max * refCount -
minMax.holderScore_tokenBalance_min * refCount )
);
// Accumulate 'em all !
// Then, multiply it by the ratio of all individual max scores
// (maxPlayerScore_etherContributed, timeFactor, tokenBalance),
// to the maxPlayerScore_refferalBonus.
// Use the same precision.
unifiedReferreeScore = int( ( (
( ( referreeScore_etherContributed +
referreeScore_timeFactors +
referreeScore_tokenBalance ) + (PRECISION / 2)
) / PRECISION
) * individualToReferralRatio
) / PRECISION );
}
// =================== PUBLIC FUNCTIONS =================== //
/**
* Update current holder's score with given change values, and
* Propagate the holder's current transfer's score changes
* through the referral chain, updating every parent referrer's
* accumulated referree scores, until the ROOT_REFERRER or zero
* address referrer is encountered.
*/
function updateAndPropagateScoreChanges(
address holder,
int80 etherContributed_change,
int80 timeFactors_change,
int80 tokenBalance_change )
public
lotteryOnly
{
// Update current holder's score.
holderData[ holder ].etherContributed += etherContributed_change;
holderData[ holder ].timeFactors += timeFactors_change;
holderData[ holder ].tokenBalance += tokenBalance_change;
// Check if scores are exceeding current min/max scores,
// and if so, update the min/max scores.
// etherContributed:
if( holderData[ holder ].etherContributed >
minMaxScores.holderScore_etherContributed_max )
minMaxScores.holderScore_etherContributed_max =
holderData[ holder ].etherContributed;
if( holderData[ holder ].etherContributed <
minMaxScores.holderScore_etherContributed_min )
minMaxScores.holderScore_etherContributed_min =
holderData[ holder ].etherContributed;
// timeFactors:
if( holderData[ holder ].timeFactors >
minMaxScores.holderScore_timeFactors_max )
minMaxScores.holderScore_timeFactors_max =
holderData[ holder ].timeFactors;
if( holderData[ holder ].timeFactors <
minMaxScores.holderScore_timeFactors_min )
minMaxScores.holderScore_timeFactors_min =
holderData[ holder ].timeFactors;
// tokenBalance:
if( holderData[ holder ].tokenBalance >
minMaxScores.holderScore_tokenBalance_max )
minMaxScores.holderScore_tokenBalance_max =
holderData[ holder ].tokenBalance;
if( holderData[ holder ].tokenBalance <
minMaxScores.holderScore_tokenBalance_min )
minMaxScores.holderScore_tokenBalance_min =
holderData[ holder ].tokenBalance;
// Propagate the score through the referral chain.
// Dive at maximum to the depth of 10, to avoid "Outta Gas"
// errors.
uint MAX_REFERRAL_DEPTH = 10;
uint depth = 0;
address referrerAddr = holderData[ holder ].referrer;
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) &&
depth < MAX_REFERRAL_DEPTH )
{
// Update this referrer's accumulated referree scores.
holderData[ referrerAddr ].referree_etherContributed +=
etherContributed_change;
holderData[ referrerAddr ].referree_timeFactors +=
timeFactors_change;
holderData[ referrerAddr ].referree_tokenBalance +=
tokenBalance_change;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
depth++;
}
}
/**
* Function executes the Lottery Winner Selection Algorithm,
* and writes the final, sorted array, containing winner rankings.
*
* This function is called from the Lottery's Mining Stage Step 2,
*
* This is the final function that lottery performs actively -
* and arguably the most important - because it determines
* lottery winners through Winner Selection Algorithm.
*
* The random seed must be already set, before calling this function.
*/
function executeWinnerSelectionAlgorithm()
public
lotteryOnly
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is MinedWinnerSelection!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder, into
// the Final Score array.
// Declare the Final Score array - computed for all holders.
uint ARRLEN =
( holders.length > MINEDSELECTION_MAX_NUMBER_OF_HOLDERS ?
MINEDSELECTION_MAX_NUMBER_OF_HOLDERS : holders.length );
FinalScore[] memory finalScores = new FinalScore[] ( ARRLEN );
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Loop through all the holders.
for( uint i = 0; i < ARRLEN; i++ )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ holders[ i ] ].etherContributed;
hdata.timeFactors =
holderData[ holders[ i ] ].timeFactors;
hdata.tokenBalance =
holderData[ holders[ i ] ].tokenBalance;
hdata.referreeCount =
holderData[ holders[ i ] ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ holders[ i ] ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ holders[ i ] ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ holders[ i ] ].referree_tokenBalance;
hdata.bonusScore =
holderData[ holders[ i ] ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, holders[ i ] ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
uint endScore = uint( totalPlayerScore ) + modulizedRandomNumber;
// Finally, set this holder's final score data.
finalScores[ i ].addr = holders[ i ];
finalScores[ i ].holderIndex = uint16( i );
finalScores[ i ].score = uint64( endScore );
}
// All final scores are now computed.
// Sort the array, to find out the highest scores!
// Firstly, partition an array to only work on top K scores,
// where K is the number of winners.
// There can be a rare case where specified number of winners is
// more than lottery token holders. We got that covered.
require( finalScores.length > 0 );
uint K = cfg.winnerCount - 1;
if( K > finalScores.length-1 )
K = finalScores.length-1; // Must be THE LAST ELEMENT's INDEX.
// Use QuickSelect to do this.
QSort_QuickSelect( finalScores, 0,
int( finalScores.length - 1 ), int( K ) );
// Now, QuickSort only the first K items, because the rest
// item scores are not high enough to become winners.
QSort_QuickSort( finalScores, 0, int( K ) );
// Now, the winner array is sorted, with the highest scores
// sitting at the first positions!
// Let's set up the winner indexes array, where we'll store
// the winners' indexes in the holders array.
// So, if this array is [8, 2, 3], that means that
// Winner #1 is holders[8], winner #2 is holders[2], and
// winner #3 is holders[3].
// Set the Number Of Winners variable.
numberOfWinners = uint16( K + 1 );
// Now, we can loop through the first numberOfWinners elements, to set
// the holder indexes!
// Loop through 16 elements at a time, to fill the structs.
for( uint offset = 0; offset < numberOfWinners; offset += 16 )
{
WinnerIndexStruct memory windStruct;
uint loopStop = ( offset + 16 > numberOfWinners ?
numberOfWinners : offset + 16 );
for( uint i = offset; i < loopStop; i++ )
{
windStruct.indexes[ i - offset ] =finalScores[ i ].holderIndex;
}
// Push this now-filled struct to the storage array!
sortedWinnerIndexes.push( windStruct );
}
// That's it! We're done!
algorithmCompleted = true;
}
/**
* Add a holder to holders array.
* @param holder - address of a holder to add.
*/
function addHolder( address holder )
public
lotteryOnly
{
// Add it to list, and set index in the mapping.
holders.push( holder );
holderIndexes[ holder ] = holders.length - 1;
}
/**
* Removes the holder 'sender' from the Holders Array.
* However, this holder's HolderData structure persists!
*
* Notice that no index validity checks are performed, so, if
* 'sender' is not present in "holderIndexes" mapping, this
* function will remove the 0th holder instead!
* This is not a problem for us, because Lottery calls this
* function only when it's absolutely certain that 'sender' is
* present in the holders array.
*
* @param sender - address of a holder to remove.
* Named 'sender', because when token sender sends away all
* his tokens, he must then be removed from holders array.
*/
function removeHolder( address sender )
public
lotteryOnly
{
// Get index of the sender address in the holders array.
uint index = holderIndexes[ sender ];
// Remove the sender from array, by copying last element's
// value into the index'th element, where sender was before.
holders[ index ] = holders[ holders.length - 1 ];
// Remove the last element of array, which we've just copied.
holders.pop();
// Update indexes: remove the sender's index from the mapping,
// and change the previoulsy-last element's index to the
// one where we copied it - where sender was before.
delete holderIndexes[ sender ];
holderIndexes[ holders[ index ] ] = index;
}
/**
* Get holder array length.
*/
function getHolderCount()
public view
returns( uint )
{
return holders.length;
}
/**
* Generate a referral ID for a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID( address holder )
public
lotteryOnly
returns( uint256 referralID )
{
// Check if holder has some tokens, and doesn't
// have his own referral ID yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referralID == 0 );
// Generate a referral ID with keccak.
uint256 refID = uint256( keccak256( abi.encodePacked(
holder, holderData[ holder ].tokenBalance, now ) ) );
// Specify the ID as current ID of this holder.
holderData[ holder ].referralID = refID;
// If this holder wasn't referred by anyone (his referrer is
// not set), and he's now generated his own ID, he won't
// be able to register as a referree of someone else
// from now on.
// This is done to prevent circular dependency in referrals.
// Do it by setting a referrer to ROOT_REFERRER address,
// which is an invalid address (address(1)).
if( holderData[ holder ].referrer == address( 0 ) )
holderData[ holder ].referrer = ROOT_REFERRER;
// Create a new referrer with this ID.
referrers[ refID ] = holder;
return refID;
}
/**
* Register a referral for a token holder, using a valid
* referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
address holder,
int16 referralRegisteringBonus,
uint256 referralID )
public
lotteryOnly
returns( address _referrerAddress )
{
// Check if this holder has some tokens, and if he hasn't
// registered a referral yet.
require( holderData[ holder ].tokenBalance != 0 );
require( holderData[ holder ].referrer == address( 0 ) );
// Get the referrer's address from his ID, and specify
// it as a referrer of holder.
holderData[ holder ].referrer = referrers[ referralID ];
// Bonus points are added to this holder's score for
// registering a referral!
holderData[ holder ].bonusScore = referralRegisteringBonus;
// Increment number of referrees for every parent referrer,
// by traversing a referral tree child->parent way.
address referrerAddr = holderData[ holder ].referrer;
// Set the return value.
_referrerAddress = referrerAddr;
// Traverse a tree.
while( referrerAddr != ROOT_REFERRER &&
referrerAddr != address( 0 ) )
{
// Increment referree count for this referrrer.
holderData[ referrerAddr ].referreeCount++;
// Update the Referrer Scores of the referrer, adding this
// referree's scores to it's current values.
holderData[ referrerAddr ].referree_etherContributed +=
holderData[ holder ].etherContributed;
holderData[ referrerAddr ].referree_timeFactors +=
holderData[ holder ].timeFactors;
holderData[ referrerAddr ].referree_tokenBalance +=
holderData[ holder ].tokenBalance;
// Move to the higher-level referrer.
referrerAddr = holderData[ referrerAddr ].referrer;
}
return _referrerAddress;
}
/**
* Sets our random seed to some value.
* Should be called from Lottery, after obtaining random seed from
* the Randomness Provider.
*/
function setRandomSeed( uint _seed )
external
lotteryOnly
{
randomSeed = uint64( _seed );
}
/**
* Initialization function.
* Here, we bind our contract to the Lottery contract that
* this Storage belongs to.
* The parent lottery must call this function - hence, we set
* "lottery" to msg.sender.
*
* When this function is called, our contract must be not yet
* initialized - "lottery" address must be Zero!
*
* Here, we also set our Winner Algorithm config, which is a
* subset of LotteryConfig, fitting into 1 storage slot.
*/
function initialize(
WinnerAlgorithmConfig memory _wcfg )
public
{
require( address( lottery ) == address( 0 ) );
// Set the Lottery address (msg.sender can't be zero),
// and thus, set our contract to initialized!
lottery = msg.sender;
// Set the Winner-Algo-Config.
algConfig = _wcfg;
// NOT-NEEDED: Set initial min-max scores: min is INT_MAX.
/*minMaxScores.holderScore_etherContributed_min = int80( 2 ** 78 );
minMaxScores.holderScore_timeFactors_min = int80( 2 ** 78 );
minMaxScores.holderScore_tokenBalance_min = int80( 2 ** 78 );
*/
}
// ==================== Views ==================== //
// Returns the current random seed.
// If the seed hasn't been set yet (or set to 0), returns 0.
//
function getRandomSeed()
external view
returns( uint )
{
return randomSeed;
}
// Check if Winner Selection Algorithm has beed executed.
//
function minedSelection_algorithmAlreadyExecuted()
external view
returns( bool )
{
return algorithmCompleted;
}
/**
* After lottery has completed, this function returns if "addr"
* is one of lottery winners, and the position in winner rankings.
* Function is used to obtain the ranking position before
* calling claimWinnerPrize() on Lottery.
*
* This function should be called off-chain, and then using the
* retrieved data, one can call claimWinnerPrize().
*/
function minedSelection_getWinnerStatus(
address addr )
public view
returns( bool isWinner,
uint32 rankingPosition )
{
// Loop through the whole winner indexes array, trying to
// find if "addr" is one of the winner addresses.
for( uint16 i = 0; i < numberOfWinners; i++ )
{
// Check if holder on this winner ranking's index position
// is addr, if so, good!
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
if( holders[ pos ] == addr )
{
return ( true, i );
}
}
// The "addr" is not a winner.
return ( false, 0 );
}
/**
* Checks if address is on specified winner ranking position.
* Used in Lottery, to check if msg.sender is really the
* winner #rankingPosition, as he claims to be.
*/
function minedSelection_isAddressOnWinnerPosition(
address addr,
uint32 rankingPosition )
external view
returns( bool )
{
if( rankingPosition >= numberOfWinners )
return false;
// Just check if address at "holders" array
// index "sortedWinnerIndexes[ position ]" is really the "addr".
uint pos = sortedWinnerIndexes[ rankingPosition / 16 ]
.indexes[ rankingPosition % 16 ];
return ( holders[ pos ] == addr );
}
/**
* Returns an array of all winner addresses, sorted by their
* ranking position (winner #1 first, #2 second, etc.).
*/
function minedSelection_getAllWinners()
external view
returns( address[] memory )
{
address[] memory winners = new address[] ( numberOfWinners );
for( uint i = 0; i < numberOfWinners; i++ )
{
uint pos = sortedWinnerIndexes[ i / 16 ].indexes[ i % 16 ];
winners[ i ] = holders[ pos ];
}
return winners;
}
/**
* Compute the Lottery Active Stage Score of a token holder.
*
* This function computes the Active Stage (pre-randomization)
* player score, and should generally be used to compute player
* intermediate scores - while lottery is still active or on
* finishing stage, before random random seed is obtained.
*/
function getPlayerActiveStageScore( address holderAddr )
external view
returns( uint playerScore )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Check if holderAddr is a holder at all!
if( holders[ holderIndexes[ holderAddr ] ] != holderAddr )
return 0;
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
holderData[ holderAddr ].bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, holderData[ holderAddr ] )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, holderData[ holderAddr ] );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Return the score!
return uint( totalPlayerScore );
}
/**
* Internal sub-procedure of the function below, used to obtain
* a final, randomized score of a Single Holder.
*/
function priv_getSingleHolderScore(
address hold3r,
int individualToReferralRatio,
int maxAvailablePlayerScore,
int SCORE_RAND_FACT,
WinnerAlgorithmConfig memory cfg,
MinMaxHolderScores memory minMaxCpy )
internal view
returns( uint endScore )
{
// Fetch the needed holder data to in-memory hdata variable,
// to save gas on score part computing functions.
HolderData memory hdata;
// Slot 1:
hdata.etherContributed =
holderData[ hold3r ].etherContributed;
hdata.timeFactors =
holderData[ hold3r ].timeFactors;
hdata.tokenBalance =
holderData[ hold3r ].tokenBalance;
hdata.referreeCount =
holderData[ hold3r ].referreeCount;
// Slot 2:
hdata.referree_etherContributed =
holderData[ hold3r ].referree_etherContributed;
hdata.referree_timeFactors =
holderData[ hold3r ].referree_timeFactors;
hdata.referree_tokenBalance =
holderData[ hold3r ].referree_tokenBalance;
hdata.bonusScore =
holderData[ hold3r ].bonusScore;
// Now, add bonus score, and compute total player's score:
// Bonus part, individual score part, and referree score part.
int totalPlayerScore =
hdata.bonusScore
+
computeHolderIndividualScores(
cfg, minMaxCpy, hdata )
+
computeReferreeScoresForHolder(
individualToReferralRatio, cfg,
minMaxCpy, hdata );
// Check if total player score <= 0. If so, make it equal
// to 1, because otherwise randomization won't be possible.
if( totalPlayerScore <= 0 )
totalPlayerScore = 1;
// Now, check if it's not more than max! If so, lowerify.
// This could have happen'd because of bonus.
if( totalPlayerScore > maxAvailablePlayerScore )
totalPlayerScore = maxAvailablePlayerScore;
// Multiply the score by the Random Modulo Adjustment
// Factor, to get fairer ratio of random-to-determined data.
totalPlayerScore = ( totalPlayerScore * SCORE_RAND_FACT ) /
( PRECISION );
// Score is computed!
// Now, randomize it, and add to Final Scores Array.
// We use keccak to generate a random number from random seed,
// using holder's address as a nonce.
uint modulizedRandomNumber = uint(
keccak256( abi.encodePacked( randomSeed, hold3r ) )
) % RANDOM_MODULO;
// Add the random number, to introduce the random factor.
// Ratio of (current) totalPlayerScore to modulizedRandomNumber
// is the same as ratio of randRatio_scorePart to
// randRatio_randPart.
return uint( totalPlayerScore ) + modulizedRandomNumber;
}
/**
* Winner Self-Validation algo-type main function.
* Here, we compute scores for all lottery holders iteratively
* in O(n) time, and thus get the winner ranking position of
* the holder in question.
*
* This function performs essentialy the same steps as the
* Mined-variant (executeWinnerSelectionAlgorithm), but doesn't
* write anything to blockchain.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function winnerSelfValidation_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is WinnerSelfValidation!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// How many holders had higher scores than "holderAddr".
// Used to obtain the final winner rank of "holderAddr".
uint numOfHoldersHigherThan = 0;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Index of holderAddr.
uint holderAddrIndex = holderIndexes[ holderAddr ];
// Loop through all the allowed holders.
for( uint i = 0;
i < ( holders.length < SELFVALIDATION_MAX_NUMBER_OF_HOLDERS ?
holders.length : SELFVALIDATION_MAX_NUMBER_OF_HOLDERS );
i++ )
{
// Skip the holderAddr's index.
if( i == holderAddrIndex )
continue;
// Compute the score using helper function.
uint endScore = priv_getSingleHolderScore(
holders[ i ],
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Check if score is higher than HolderAddr's, and if so, check.
if( endScore > holderAddrsFinalScore )
numOfHoldersHigherThan++;
}
// All scores are checked!
// Now, we can obtain holderAddr's winner rank based on how
// many scores were above holderAddr's score!
isWinner = ( numOfHoldersHigherThan < cfg.winnerCount );
rankingPosition = numOfHoldersHigherThan;
}
/**
* Rolled-Randomness algo-type main function.
* Here, we only compute the score of the holder in question,
* and compare it to maximum-available final score, divided
* by no-of-winners.
*
* @param holderAddr - address of a holder whose rank we want to find.
*/
function rolledRandomness_getWinnerStatus(
address holderAddr )
internal view
returns( bool isWinner, uint rankingPosition )
{
// Copy the Winner Algo Config into memory, to avoid using
// 400-gas costing SLOAD every time we need to load something.
WinnerAlgorithmConfig memory cfg = algConfig;
// Can only be performed if algorithm is RolledRandomness!
require( cfg.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) );
// Check if holderAddr is a holder at all!
require( holders[ holderIndexes[ holderAddr ] ] == holderAddr );
// Now, we gotta find the winners using a Randomized Score-Based
// Winner Selection Algorithm.
//
// During transfers, all player intermediate scores
// (etherContributed, timeFactors, and tokenBalances) were
// already set in every holder's HolderData structure,
// during operations of updateHolderData_preTransfer() function.
//
// Minimum and maximum values are also known, so normalization
// will be easy.
// All referral tree score data were also properly propagated
// during operations of updateAndPropagateScoreChanges() function.
//
// All we now have to do, is loop through holder array, and
// compute randomized final scores for every holder.
// Compute the precision-adjusted constant ratio of
// referralBonus max score to the player individual max scores.
int individualToReferralRatio =
( PRECISION * cfg.maxPlayerScore_refferalBonus ) /
( int( cfg.maxPlayerScore_etherContributed ) +
int( cfg.maxPlayerScore_timeFactor ) +
int( cfg.maxPlayerScore_tokenHoldingAmount ) );
// Max available player score.
int maxAvailablePlayerScore = int(
cfg.maxPlayerScore_etherContributed +
cfg.maxPlayerScore_timeFactor +
cfg.maxPlayerScore_tokenHoldingAmount +
cfg.maxPlayerScore_refferalBonus );
// Random Factor of scores, to maintain random-to-determined
// ratio equal to specific value (1:5 for example -
// "randPart" == 5, "scorePart" == 1).
//
// maxAvailablePlayerScore * FACT --- scorePart
// RANDOM_MODULO --- randPart
//
// RANDOM_MODULO * scorePart
// maxAvailablePlayerScore * FACT = -------------------------
// randPart
//
// RANDOM_MODULO * scorePart
// FACT = --------------------------------------
// randPart * maxAvailablePlayerScore
int SCORE_RAND_FACT =
( PRECISION * int(RANDOM_MODULO * cfg.randRatio_scorePart) ) /
( int(cfg.randRatio_randPart) * maxAvailablePlayerScore );
// Fix Min-Max scores, to avoid division by zero, if min == max.
// If min == max, make the difference equal to 1.
MinMaxHolderScores memory minMaxCpy = minMaxScores;
if( minMaxCpy.holderScore_etherContributed_min ==
minMaxCpy.holderScore_etherContributed_max )
minMaxCpy.holderScore_etherContributed_max =
minMaxCpy.holderScore_etherContributed_min + 1;
if( minMaxCpy.holderScore_timeFactors_min ==
minMaxCpy.holderScore_timeFactors_max )
minMaxCpy.holderScore_timeFactors_max =
minMaxCpy.holderScore_timeFactors_min + 1;
if( minMaxCpy.holderScore_tokenBalance_min ==
minMaxCpy.holderScore_tokenBalance_max )
minMaxCpy.holderScore_tokenBalance_max =
minMaxCpy.holderScore_tokenBalance_min + 1;
// The final (randomized) score of "holderAddr".
uint holderAddrsFinalScore = priv_getSingleHolderScore(
holderAddr,
individualToReferralRatio,
maxAvailablePlayerScore,
SCORE_RAND_FACT,
cfg, minMaxCpy );
// Now, compute the Max-Final-Random Score, divide it
// by the Holder Count, and get the ranking by placing this
// holder's score in it's corresponding part.
//
// In this approach, we assume linear randomness distribution.
// In practice, distribution might be a bit different, but this
// approach is the most efficient.
//
// Max-Final-Score (randomized) is the highest available score
// that can be achieved, and is made by adding together the
// maximum availabe Player Score Part and maximum available
// Random Part (equals RANDOM_MODULO).
// These parts have a ratio equal to config-specified
// randRatio_scorePart to randRatio_randPart.
//
// So, if player's active stage's score is low (1), but rand-part
// in ratio is huge, then the score is mostly random, so
// maxFinalScore is close to the RANDOM_MODULO - maximum random
// value that can be rolled.
//
// If, however, we use 1:1 playerScore-to-Random Ratio, then
// playerScore and RandomScore make up equal parts of end score,
// so the maxFinalScore is actually two times larger than
// RANDOM_MODULO, so player needs to score more
// player-points to get larger prizes.
//
// In default configuration, playerScore-to-random ratio is 1:3,
// so there's a good randomness factor, so even the low-scoring
// players can reasonably hope to get larger prizes, but
// the higher is player's active stage score, the more
// chances of scoring a high final score a player gets, with
// the higher-end of player scores basically guaranteeing
// themselves a specific prize amount, if winnerCount is
// big enough to overlap.
int maxRandomPart = int( RANDOM_MODULO - 1 );
int maxPlayerScorePart = ( SCORE_RAND_FACT * maxAvailablePlayerScore )
/ PRECISION;
uint maxFinalScore = uint( maxRandomPart + maxPlayerScorePart );
// Compute the amount that single-holder's virtual part
// might take up in the max-final score.
uint singleHolderPart = maxFinalScore / holders.length;
// Now, compute how many single-holder-parts are there in
// this holder's score.
uint holderAddrScorePartCount = holderAddrsFinalScore /
singleHolderPart;
// The ranking is that number, minus holders length.
// If very high score is scored, default to position 0 (highest).
rankingPosition = (
holderAddrScorePartCount < holders.length ?
holders.length - holderAddrScorePartCount : 0
);
isWinner = ( rankingPosition < cfg.winnerCount );
}
/**
* Genericized, algorithm type-dependent getWinnerStatus function.
*/
function getWinnerStatus(
address addr )
external view
returns( bool isWinner, uint32 rankingPosition )
{
bool _isW;
uint _rp;
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.RolledRandomness) )
{
(_isW, _rp) = rolledRandomness_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.WinnerSelfValidation) )
{
(_isW, _rp) = winnerSelfValidation_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
if( algConfig.endingAlgoType ==
uint8(Lottery.EndingAlgoType.MinedWinnerSelection) )
{
(_isW, _rp) = minedSelection_getWinnerStatus( addr );
return ( _isW, uint32( _rp ) );
}
}
}
contract UniLotteryStorageFactory
{
// The Pool Address.
address payable poolAddress;
// The Delegate Logic contract, containing all code for
// all LotteryStorage contracts to be deployed.
address immutable delegateContract;
// Pool-Only modifier.
modifier poolOnly
{
require( msg.sender == poolAddress );
_;
}
// Constructor.
// Deploy the Delegate Contract here.
//
constructor() public
{
delegateContract = address( new LotteryStorage() );
}
// Initialization function.
// Set the poolAddress as msg.sender, and lock it.
function initialize()
external
{
require( poolAddress == address( 0 ) );
// Set the Pool's Address.
poolAddress = msg.sender;
}
/**
* Deploy a new Lottery Storage Stub, to be used by it's corresponding
* Lottery Stub, which will be created later, passing this Storage
* we create here.
* @return newStorage - the Lottery Storage Stub contract just deployed.
*/
function createNewStorage()
public
poolOnly
returns( address newStorage )
{
return address( new LotteryStorageStub( delegateContract ) );
}
}
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;
}
}
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
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);
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;
}
}
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 virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public 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 virtual {
require(sender != address(0));
require(recipient != address(0));
_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));
_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));
_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 virtual {
require(owner != address(0));
require(spender != address(0));
_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"));
}
}
interface IUniswapPair is IERC20
{
// Addresses of the first and second pool-kens.
function token0() external view returns (address);
function token1() external view returns (address);
// Get the pair's token pool reserves.
function getReserves()
external view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
}
contract Lottery is ERC20, CoreUniLotterySettings
{
// ===================== Events ===================== //
// After initialize() function finishes.
event LotteryInitialized();
// Emitted when lottery active stage ends (Mining Stage starts),
// on Mining Stage Step 1, after transferring profits to their
// respective owners (pool and OWNER_ADDRESS).
event LotteryEnd(
uint128 totalReturn,
uint128 profitAmount
);
// Emitted when on final finish, we call Randomness Provider
// to callback us with random value.
event RandomnessProviderCalled();
// Requirements for finishing stage start have been reached -
// finishing stage has started.
event FinishingStageStarted();
// We were currently on the finishing stage, but some requirement
// is no longer met. We must stop the finishing stage.
event FinishingStageStopped();
// New Referral ID has been generated.
event ReferralIDGenerated(
address referrer,
uint256 id
);
// New referral has been registered with a valid referral ID.
event ReferralRegistered(
address referree,
address referrer,
uint256 id
);
// Fallback funds received.
event FallbackEtherReceiver(
address sender,
uint value
);
// ====================== Structs & Enums ====================== //
// Lottery Stages.
// Described in more detail above, on contract's main doc.
enum STAGE
{
// Initial stage - before the initialize() function is called.
INITIAL,
// Active Stage: On this stage, all token trading occurs.
ACTIVE,
// Finishing stage:
// This is when all finishing criteria are met, and for every
// transfer, we're rolling a pseudo-random number to determine
// if we should end the lottery (move to Ending stage).
FINISHING,
// Ending - Mining Stage:
// This stage starts after we lottery is no longer active,
// finishing stage ends. On this stage, Miners perform the
// Ending Algorithm and other operations.
ENDING_MINING,
// Lottery is completed - this is set after the Mining Stage ends.
// In this stage, Lottery Winners can claim their prizes.
COMPLETION,
// DISABLED stage. Used when we want a lottery contract to be
// absolutely disabled - so no state-modifying functions could
// be called.
// This is used in DelegateCall scenarios, where state-contract
// delegate-calls code contract, to save on deployment costs.
DISABLED
}
// Ending algorithm types enum.
enum EndingAlgoType
{
// 1. Mined Winner Selection Algorithm.
// This algorithm is executed by a Lottery Miner in a single
// transaction, on Mining Step 2.
//
// On that single transaction, all ending scores for all
// holders are computed, and a sorted winner array is formed,
// which is written onto the LotteryStorage state.
// Thus, it's gas expensive, and suitable only for small
// holder numbers (up to 300).
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution - for example, if we specify that there
// must be 2 winners, of which first gets 60% of prize funds,
// and second gets 40% of prize funds, then it's
// guarateed that prize funds will be distributed just
// like that.
//
// + Low gas cost of prize claims - only ~ 40,000 gas for
// claiming a prize.
//
// Cons:
// - Not scaleable - as the Winner Selection Algorithm is
// executed in a single transaction, it's limited by
// block gas limit - 12,500,000 on the MainNet.
// Thus, the lottery is limited to ~300 holders, and
// max. ~200 winners of those holders.
// So, it's suitable for only express-lotteries, where
// a lottery runs only until ~300 holders are reached.
//
// - High mining costs - if lottery has 300 holders,
// mining transaction takes up whole block gas limit.
//
MinedWinnerSelection,
// 2. Winner Self-Validation Algorithm.
//
// This algorithm does no operations during the Mining Stage
// (except for setting up a Random Seed in Lottery Storage) -
// the winner selection (obtaining a winner rank) is done by
// the winners themselves, when calling the prize claim
// functions.
//
// This algorithm relies on a fact that by the time that
// random seed is obtained, all data needed for winner selection
// is already there - the holder scores of the Active Stage
// (ether contributed, time factors, token balance), and
// the Random Data (random seed + nonce (holder's address)),
// so, there is no need to compute and sort the scores for the
// whole holder array.
//
// It's done like this: the holder checks if he's a winner, using
// a view-function off-chain, and if so, he calls the
// claimWinnerPrize() function, which obtains his winner rank
// on O(n) time, and does no writing to contract states,
// except for prize transfer-related operations.
//
// When computing the winner's rank on LotteryStorage,
// O(n) time is needed, as we loop through the holders array,
// computing ending scores for each holder, using already-known
// data.
// However that means that for every prize claim, all scores of
// all holders must be re-computed.
// Computing a score for a single holder takes roughly 1500 gas
// (400 for 3 slots SLOAD, and ~300 for arithmetic operations).
//
// So, this algorithm makes prize claims more expensive for
// every lottery holder.
// If there's 1000 holders, prize claim takes up 1,500,000 gas,
// so, this algorithm is not suitable for small prizes,
// because gas fee would be higher than the prize amount won.
//
// Pros:
// + Guaranteed deterministically specifiable winner prize
// distribution (same as for algorithm 1).
//
// + No mining costs for winner selection algorithm.
//
// + More scalable than algorithm 1.
//
// Cons:
// - High gas costs of prize claiming, rising with the number
// of lottery holders - 1500 for every lottery holder.
// Thus, suitable for only large prize amounts.
//
WinnerSelfValidation,
// 3. Rolled-Randomness algorithm.
//
// This algorithm is the most cheapest in terms of gas, but
// the winner prize distribution is non-deterministic.
//
// This algorithm doesn't employ miners (no mining costs),
// and doesn't require to compute scores for every holder
// prior to getting a winner's rank, thus is the most scalable.
//
// It works like this: a holder checks his winner status by
// computing only his own randomized score (rolling a random
// number from the random seed, and multiplying it by holder's
// Active Stage score), and computing this randomized-score's
// ratio relative to maximum available randomized score.
// The higher the ratio, the higher the winner rank is.
//
// However, many players can roll very high or low scores, and
// get the same prizes, so it's difficult to make a fair and
// efficient deterministic prize distribution mechanism, so
// we have to fallback to specific heuristic workarounds.
//
// Pros:
// + Scalable: O(1) complexity for computing a winner rank,
// so there can be an unlimited amount of lottery holders,
// and gas costs for winner selection and prize claim would
// still be constant & low.
//
// + Gas-efficient: gas costs for all winner-related operations
// are constant and low, because only single holder's score
// is computed.
//
// + Doesn't require mining - even more gas savings.
//
// Cons:
// + Hard to make a deterministic and fair prize distribution
// mechanism, because of un-known environment - as only
// single holder's score is compared to max-available
// random score, not taking into account other holder
// scores.
//
RolledRandomness
}
/**
* Gas-efficient, minimal config, which specifies only basic,
* most-important and most-used settings.
*/
struct LotteryConfig
{
// ================ Misc Settings =============== //
// --------- Slot --------- //
// Initial lottery funds (initial market cap).
// Specified by pool, and is used to check if initial funds
// transferred to fallback are correct - equal to this value.
uint initialFunds;
// --------- Slot --------- //
// The minimum ETH value of lottery funds, that, once
// reached on an exchange liquidity pool (Uniswap, or our
// contract), must be guaranteed to not shrink below this value.
//
// This is accomplished in _transfer() function, by denying
// all sells that would drop the ETH amount in liquidity pool
// below this value.
//
// But on initial lottery stage, before this minimum requirement
// is reached for the first time, all sells are allowed.
//
// This value is expressed in ETH - total amount of ETH funds
// that we own in Uniswap liquidity pair.
//
// So, if initial funds were 10 ETH, and this is set to 100 ETH,
// after liquidity pool's ETH value reaches 100 ETH, all further
// sells which could drop the liquidity amount below 100 ETH,
// would be denied by require'ing in _transfer() function
// (transactions would be reverted).
//
uint128 fundRequirement_denySells;
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
uint128 finishCriteria_minFunds;
// --------- Slot --------- //
// Maximum lifetime of a lottery - maximum amount of time
// allowed for lottery to stay active.
// By default, it's two weeks.
// If lottery is still active (hasn't returned funds) after this
// time, lottery will stop on the next token transfer.
uint32 maxLifetime;
// Maximum prize claiming time - for how long the winners
// may be able to claim their prizes after lottery ending.
uint32 prizeClaimTime;
// Token transfer burn rates for buyers, and a default rate for
// sells and non-buy-sell transfers.
uint32 burn_buyerRate;
uint32 burn_defaultRate;
// Maximum amount of tokens (in percentage of initial supply)
// to be allowed to own by a single wallet.
uint32 maxAmountForWallet_percentageOfSupply;
// The required amount of time that must pass after
// the request to Randomness Provider has been made, for
// external actors to be able to initiate alternative
// seed generation algorithm.
uint32 REQUIRED_TIME_WAITING_FOR_RANDOM_SEED;
// ================ Profit Shares =============== //
// "Mined Uniswap Lottery" ending Ether funds, which were obtained
// by removing token liquidity from Uniswap, are transfered to
// these recipient categories:
//
// 1. The Main Pool: Initial funds, plus Pool's profit share.
// 2. The Owner: Owner's profit share.
//
// 3. The Miners: Miner rewards for executing the winner
// selection algorithm stages.
// The more holders there are, the more stages the
// winner selection algorithm must undergo.
// Each Miner, who successfully completed an algorithm
// stage, will get ETH reward equal to:
// (minerProfitShare / totalAlgorithmStages).
//
// 4. The Lottery Winners: All remaining funds are given to
// Lottery Winners, which were determined by executing
// the Winner Selection Algorithm at the end of the lottery
// (Miners executed it).
// The Winners can claim their prizes by calling a
// dedicated function in our contract.
//
// The profit shares of #1 and #2 have controlled value ranges
// specified in CoreUniLotterySettings.
//
// All these shares are expressed as percentages of the
// lottery profit amount (totalReturn - initialFunds).
// Percentages are expressed using the PERCENT constant,
// defined in CoreUniLotterySettings.
//
// Here we specify profit shares of Pool, Owner, and the Miners.
// Winner Prize Fund is all that's left (must be more than 50%
// of all profits).
//
uint32 poolProfitShare;
uint32 ownerProfitShare;
// --------- Slot --------- //
uint32 minerProfitShare;
// =========== Lottery Finish criteria =========== //
// Lottery finish by design is a whole soft stage, that
// starts when criteria for holders and fund gains are met.
// During this stage, for every token transfer, a pseudo-random
// number will be rolled for lottery finish, with increasing
// probability.
//
// There are 2 ways that this probability increase is
// implemented:
// 1. Increasing on every new holder.
// 2. Increasing on every transaction after finish stage
// was initiated.
//
// On every new holder, probability increases more than on
// new transactions.
//
// However, if during this stage some criteria become
// no-longer-met, the finish stage is cancelled.
// This cancel can be implemented by setting finish probability
// to zero, or leaving it as it was, but pausing the finishing
// stage.
// This is controlled by finish_resetProbabilityOnStop flag -
// if not set, probability stays the same, when the finishing
// stage is discontinued.
// ETH value of our funds that we own in Uniswap Liquidity Pair,
// that's needed to start the Finishing Stage.
//
// LOOK ABOVE - arranged for tight-packing.
// Minimum number of token holders required to start the
// finishing stage.
uint32 finishCriteria_minNumberOfHolders;
// Minimum amount of time that lottery must be active.
uint32 finishCriteria_minTimeActive;
// Initial finish probability, when finishing stage was
// just initiated.
uint32 finish_initialProbability;
// Finishing probability increase steps, for every new
// transaction and every new holder.
// If holder number decreases, probability decreases.
uint32 finish_probabilityIncreaseStep_transaction;
uint32 finish_probabilityIncreaseStep_holder;
// =========== Winner selection config =========== //
// Winner selection algorithm settings.
//
// Algorithm is based on score, which is calculated for
// every holder on lottery finish, and is comprised of
// the following parts.
// Each part is normalized to range ( 0 - scorePoints ),
// from smallest to largest value of each holder;
//
// After scores are computed, they are multiplied by
// holder count factor (holderCount / holderCountDivisor),
// and finally, multiplied by safely-generated random values,
// to get end winning scores.
// The top scorers win prizes.
//
// By default setting, max score is 40 points, and it's
// comprised of the following parts:
//
// 1. Ether contributed (when buying from Uniswap or contract).
// Gets added when buying, and subtracted when selling.
// Default: 10 points.
//
// 2. Amount of lottery tokens holder has on finish.
// Default: 5 points.
//
// 3. Ether contributed, multiplied by the relative factor
// of time - that is, "now" minus "lotteryStartTime".
// This way, late buyers can get more points even if
// they get little tokens and don't spend much ether.
// Default: 5 points.
//
// 4. Refferrer bonus. For every player that joined with
// your referral ID, you get (that player's score) / 10
// points! This goes up to specified max score.
// Also, every player who provides a valid referral ID,
// gets 2 points for free!
// Default max bonus: 20 points.
//
int16 maxPlayerScore_etherContributed;
int16 maxPlayerScore_tokenHoldingAmount;
int16 maxPlayerScore_timeFactor;
int16 maxPlayerScore_refferalBonus;
// --------- Slot --------- //
// Score-To-Random ration data (as a rational ratio number).
// For example if 1:5, then scorePart = 1, and randPart = 5.
uint16 randRatio_scorePart;
uint16 randRatio_randPart;
// Time factor divisor - interval of time, in seconds, after
// which time factor is increased by one.
uint16 timeFactorDivisor;
// Bonus score a player should get when registering a valid
// referral code obtained from a referrer.
int16 playerScore_referralRegisteringBonus;
// Are we resetting finish probability when finishing stage
// stops, if some criteria are no longer met?
bool finish_resetProbabilityOnStop;
// =========== Winner Prize Fund Settings =========== //
// There are 2 available modes that we can use to distribute
// winnings: a computable sequence (geometrical progression),
// or an array of winner prize fund share percentages.
// More gas efficient is to use a computable sequence,
// where each winner gets a share equal to (factor * fundsLeft).
// Factor is in range [0.01 - 1.00] - simulated as [1% - 100%].
//
// For example:
// Winner prize fund is 100 ethers, Factor is 1/4 (25%), and
// there are 5 winners total (winnerCount), and sequenced winner
// count is 2 (sequencedWinnerCount).
//
// So, we pre-compute the upper shares, till we arrive to the
// sequenced winner count, in a loop:
// - Winner 1: 0.25 * 100 = 25 eth; 100 - 25 = 75 eth left.
// - Winner 2: 0.25 * 75 ~= 19 eth; 75 - 19 = 56 eth left.
//
// Now, we compute the left-over winner shares, which are
// winners that get their prizes from the funds left after the
// sequence winners.
//
// So, we just divide the leftover funds (56 eth), by 3,
// because winnerCount - sequencedWinnerCount = 3.
// - Winner 3 = 56 / 3 = 18 eth;
// - Winner 4 = 56 / 3 = 18 eth;
// - Winner 5 = 56 / 3 = 18 eth;
//
// If this value is 0, then we'll assume that array-mode is
// to be used.
uint32 prizeSequenceFactor;
// Maximum number of winners that the prize sequence can yield,
// plus the leftover winners, which will get equal shares of
// the remainder from the first-prize sequence.
uint16 prizeSequence_winnerCount;
// How many winners would get sequence-computed prizes.
// The left-over winners
// This is needed because prizes in sequence tend to zero, so
// we need to limit the sequence to avoid very small prizes,
// and to avoid the remainder.
uint16 prizeSequence_sequencedWinnerCount;
// Initial token supply (without decimals).
uint48 initialTokenSupply;
// Ending Algorithm type.
// More about the 3 algorithm types above.
uint8 endingAlgoType;
// --------- Slot --------- //
// Array mode: The winner profit share percentages array.
// For example, lottery profits can be distributed this way:
//
// Winner profit shares (8 winners):
// [ 20%, 15%, 10%, 5%, 4%, 3%, 2%, 1% ] = 60% of profits.
// Owner profits: 10%
// Pool profits: 30%
//
// Pool profit share is not defined explicitly in the config, so
// when we internally validate specified profit shares, we
// assume the pool share to be the left amount until 100% ,
// but we also make sure that this amount is at least equal to
// MIN_POOL_PROFITS, defined in CoreSettings.
//
uint32[] winnerProfitShares;
}
// ========================= Constants ========================= //
// The Miner Profits - max/min values.
// These aren't defined in Core Settings, because Miner Profits
// are only specific to this lottery type.
uint32 constant MIN_MINER_PROFITS = 1 * PERCENT;
uint32 constant MAX_MINER_PROFITS = 10 * PERCENT;
// Uniswap Router V2 contract instance.
// Address is the same for MainNet, and all public testnets.
IUniswapRouter constant uniswapRouter = IUniswapRouter(
address( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ) );
// Public-accessible ERC20 token specific constants.
string constant public name = "UniLottery Token";
string constant public symbol = "ULT";
uint256 constant public decimals = 18;
// =================== State Variables =================== //
// ------- Initial Slots ------- //
// The config which is passed to constructor.
LotteryConfig internal cfg;
// ------- Slot ------- //
// The Lottery Storage contract, which stores all holder data,
// such as scores, referral tree data, etc.
LotteryStorage public lotStorage;
// ------- Slot ------- //
// Pool address. Set on constructor from msg.sender.
address payable public poolAddress;
// ------- Slot ------- //
// Randomness Provider address.
address public randomnessProvider;
// ------- Slot ------- //
// Exchange address. In Uniswap mode, it's the Uniswap liquidity
// pair's address, where trades execute.
address public exchangeAddress;
// Start date.
uint32 public startDate;
// Completion (Mining Phase End) date.
uint32 public completionDate;
// The date when Randomness Provider was called, requesting a
// random seed for the lottery finish.
// Also, when this variable becomes Non-Zero, it indicates that we're
// on Ending Stage Part One: waiting for the random seed.
uint32 finish_timeRandomSeedRequested;
// ------- Slot ------- //
// WETH address. Set by calling Router's getter, on constructor.
address WETHaddress;
// Is the WETH first or second token in our Uniswap Pair?
bool uniswap_ethFirst;
// If we are, or were before, on finishing stage, this is the
// probability of lottery going to Ending Stage on this transaction.
uint32 finishProbablity;
// Re-Entrancy Lock (Mutex).
// We protect for reentrancy in the Fund Transfer functions.
bool reEntrancyMutexLocked;
// On which stage we are currently.
uint8 public lotteryStage;
// Indicator for whether the lottery fund gains have passed a
// minimum fund gain requirement.
// After that time point (when this bool is set), the token sells
// which could drop the fund value below the requirement, would
// be denied.
bool fundGainRequirementReached;
// The current step of the Mining Stage.
uint16 miningStep;
// If we're currently on Special Transfer Mode - that is, we allow
// direct transfers between parties even in NON-ACTIVE state.
bool specialTransferModeEnabled;
// ------- Slot ------- //
// Per-Transaction Pseudo-Random hash value (transferHashValue).
// This value is computed on every token transfer, by keccak'ing
// the last (current) transferHashValue, msg.sender, now, and
// transaction count.
//
// This is used on Finishing Stage, as a pseudo-random number,
// which is used to check if we should end the lottery (move to
// Ending Stage).
uint256 transferHashValue;
// ------- Slot ------- //
// On lottery end, get & store the lottery total ETH return
// (including initial funds), and profit amount.
uint128 public ending_totalReturn;
uint128 public ending_profitAmount;
// ------- Slot ------- //
// The mapping that contains TRUE for addresses that already claimed
// their lottery winner prizes.
// Used only in COMPLETION, on claimWinnerPrize(), to check if
// msg.sender has already claimed his prize.
mapping( address => bool ) public prizeClaimersAddresses;
// ============= Private/internal functions ============= //
// Pool Only modifier.
modifier poolOnly {
require( msg.sender == poolAddress );
_;
}
// Only randomness provider allowed modifier.
modifier randomnessProviderOnly {
require( msg.sender == randomnessProvider );
_;
}
// Execute function only on specific lottery stage.
modifier onlyOnStage( STAGE _stage )
{
require( lotteryStage == uint8( _stage ) );
_;
}
// Modifier for protecting the function from re-entrant calls,
// by using a locked Re-Entrancy Lock (Mutex).
modifier mutexLOCKED
{
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
_;
reEntrancyMutexLocked = false;
}
// Check if we're currently on a specific stage.
function onStage( STAGE _stage )
internal view
returns( bool )
{
return ( lotteryStage == uint8( _stage ) );
}
/**
* Check if token transfer to specific wallet won't exceed
* maximum token amount allowed to own by a single wallet.
*
* @return true, if holder's balance with "amount" added,
* would exceed the max allowed single holder's balance
* (by default, that is 5% of total supply).
*/
function transferExceedsMaxBalance(
address holder, uint amount )
internal view
returns( bool )
{
uint maxAllowedBalance =
( totalSupply() * cfg.maxAmountForWallet_percentageOfSupply ) /
( _100PERCENT );
return ( ( balanceOf( holder ) + amount ) > maxAllowedBalance );
}
/**
* Update holder data.
* This function is called by _transfer() function, just before
* transfering final amount of tokens directly from sender to
* receiver.
* At this point, all burns/mints have been done, and we're sure
* that this transfer is valid and must be successful.
*
* In all modes, this function is used to update the holder array.
*
* However, on external exchange modes (e.g. on Uniswap mode),
* it is also used to track buy/sell ether value, to update holder
* scores, when token buys/sells cannot be tracked directly.
*
* If, however, we use Standalone mode, we are the exchange,
* so on _transfer() we already know the ether value, which is
* set to currentBuySellEtherValue variable.
*
* @param amountSent - the token amount that is deducted from
* sender's balance. This includes burn, and owner fee.
*
* @param amountReceived - the token amount that receiver
* actually receives, after burns and fees.
*
* @return holderCountChanged - indicates whether holder count
* changes during this transfer - new holder joins or leaves
* (true), or no change occurs (false).
*/
function updateHolderData_preTransfer(
address sender,
address receiver,
uint256 amountSent,
uint256 amountReceived )
internal
returns( bool holderCountChanged )
{
// Update holder array, if new token holder joined, or if
// a holder transfered his whole balance.
holderCountChanged = false;
// Sender transferred his whole balance - no longer a holder.
if( balanceOf( sender ) == amountSent )
{
lotStorage.removeHolder( sender );
holderCountChanged = true;
}
// Receiver didn't have any tokens before - add it to holders.
if( balanceOf( receiver ) == 0 && amountReceived > 0 )
{
lotStorage.addHolder( receiver );
holderCountChanged = true;
}
// Update holder score factors: if buy/sell occured, update
// etherContributed and timeFactors scores,
// and also propagate the scores through the referral chain
// to the parent referrers (this is done in Storage contract).
// This lottery operates only on external exchange (Uniswap)
// mode, so we have to find out the buy/sell Ether value by
// calling the external exchange (Uniswap pair) contract.
// Temporary variable to store current transfer's buy/sell
// value in Ethers.
int buySellValue;
// Sender is an exchange - buy detected.
if( sender == exchangeAddress && receiver != exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to WETH -> ULT
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = WETHaddress;
path[ 1 ] = address(this);
uint[] memory ethAmountIn = uniswapRouter.getAmountsIn(
amountSent, // uint amountOut,
path // address[] path
);
buySellValue = int( ethAmountIn[ 0 ] );
// Compute time factor value for the current ether value.
// buySellValue is POSITIVE.
// When computing Time Factors, leave only 6 ether decimals.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the buyer (receiver) scores.
lotStorage.updateAndPropagateScoreChanges(
receiver,
int80( buySellValue ),
int80( timeFactorValue ),
int80( amountReceived ) );
}
// Receiver is an exchange - sell detected.
else if( sender != exchangeAddress && receiver == exchangeAddress )
{
// Use the Router's functionality.
// Set the exchange path to ULT -> WETH
// (ULT is Lottery Token, and it's address is our address).
address[] memory path = new address[]( 2 );
path[ 0 ] = address(this);
path[ 1 ] = WETHaddress;
uint[] memory ethAmountOut = uniswapRouter.getAmountsOut(
amountReceived, // uint amountIn
path // address[] path
);
// It's a sell (ULT -> WETH), so set value to NEGATIVE.
buySellValue = int( -1 ) * int( ethAmountOut[ 1 ] );
// Compute time factor value for the current ether value.
// buySellValue is NEGATIVE.
int timeFactorValue = ( buySellValue / (10 ** 12) ) *
int( (now - startDate) / cfg.timeFactorDivisor );
// Update and propagate the seller (sender) scores.
lotStorage.updateAndPropagateScoreChanges(
sender,
int80( buySellValue ),
int80( timeFactorValue ),
-1 * int80( amountSent ) );
}
// Neither Sender nor Receiver are exchanges - default transfer.
// Tokens just got transfered between wallets, without
// exchanging for ETH - so etherContributed_change = 0.
// On this case, update both sender's & receiver's scores.
//
else {
buySellValue = 0;
lotStorage.updateAndPropagateScoreChanges( sender, 0, 0,
-1 * int80( amountSent ) );
lotStorage.updateAndPropagateScoreChanges( receiver, 0, 0,
int80( amountReceived ) );
}
// Check if lottery liquidity pool funds have already
// reached a minimum required ETH value.
uint ethFunds = getCurrentEthFunds();
if( !fundGainRequirementReached &&
ethFunds >= cfg.fundRequirement_denySells )
{
fundGainRequirementReached = true;
}
// Check whether this token transfer is allowed if it's a sell
// (if buySellValue is negative):
//
// If we've already reached the minimum fund gain requirement,
// and this sell would shrink lottery liquidity pool's ETH funds
// below this requirement, then deny this sell, causing this
// transaction to fail.
if( fundGainRequirementReached &&
buySellValue < 0 &&
( uint( -1 * buySellValue ) >= ethFunds ||
ethFunds - uint( -1 * buySellValue ) <
cfg.fundRequirement_denySells ) )
{
require( false );
}
}
/**
* Check for finishing stage start conditions.
* - If some conditions are met, start finishing stage!
* Do it by setting "onFinishingStage" bool.
* - If we're currently on finishing stage, and some condition
* is no longer met, then stop the finishing stage.
*/
function checkFinishingStageConditions()
internal
{
// Firstly, check if lottery hasn't exceeded it's maximum lifetime.
// If so, don't check anymore, just set finishing stage, and
// end the lottery on further call of checkForEnding().
if( (now - startDate) > cfg.maxLifetime )
{
lotteryStage = uint8( STAGE.FINISHING );
return;
}
// Compute & check the finishing criteria.
// Notice that we adjust the config-specified fund gain
// percentage increase to uint-mode, by adding 100 percents,
// because we don't deal with negative percentages, and here
// we represent loss as a percentage below 100%, and gains
// as percentage above 100%.
// So, if in regular gains notation, it's said 10% gain,
// in uint mode, it's said 110% relative increase.
//
// (Also, remember that losses are impossible in our lottery
// working scheme).
if( lotStorage.getHolderCount() >= cfg.finishCriteria_minNumberOfHolders
&&
getCurrentEthFunds() >= cfg.finishCriteria_minFunds
&&
(now - startDate) >= cfg.finishCriteria_minTimeActive )
{
if( onStage( STAGE.ACTIVE ) )
{
// All conditions are met - start the finishing stage.
lotteryStage = uint8( STAGE.FINISHING );
emit FinishingStageStarted();
}
}
else if( onStage( STAGE.FINISHING ) )
{
// However, what if some condition was not met, but we're
// already on the finishing stage?
// If so, we must stop the finishing stage.
// But what to do with the finishing probability?
// Config specifies if it should be reset or maintain it's
// value until the next time finishing stage is started.
lotteryStage = uint8( STAGE.ACTIVE );
if( cfg.finish_resetProbabilityOnStop )
finishProbablity = cfg.finish_initialProbability;
emit FinishingStageStopped();
}
}
/**
* We're currently on finishing stage - so let's check if
* we should end the lottery now!
*
* This function is called from _transfer(), only if we're sure
* that we're currently on finishing stage (onFinishingStage
* variable is set).
*
* Here, we compute the pseudo-random number from hash of
* current message's sender, now, and other values,
* and modulo it to the current finish probability.
* If it's equal to 1, then we end the lottery!
*
* Also, here we update the finish probability according to
* probability update criteria - holder count, and tx count.
*
* @param holderCountChanged - indicates whether Holder Count
* has changed during this transfer (new holder joined, or
* a holder sold all his tokens).
*/
function checkForEnding( bool holderCountChanged )
internal
{
// At first, check if lottery max lifetime is exceeded.
// If so, start ending procedures right now.
if( (now - startDate) > cfg.maxLifetime )
{
startEndingStage();
return;
}
// Now, we know that lottery lifetime is still OK, and we're
// currently on Finishing Stage (because this function is
// called only when onFinishingStage is set).
//
// Now, check if we should End the lottery, by computing
// a modulo on a pseudo-random number, which is a transfer
// hash, computed for every transfer on _transfer() function.
//
// Get the modulo amount according to current finish
// probability.
// We use precision of 0.01% - notice the "10000 *" before
// 100 PERCENT.
// Later, when modulo'ing, we'll check if value is below 10000.
//
uint prec = 10000;
uint modAmount = (prec * _100PERCENT) / finishProbablity;
if( ( transferHashValue % modAmount ) <= prec )
{
// Finish probability is met! Commence lottery end -
// start Ending Stage.
startEndingStage();
return;
}
// Finish probability wasn't met.
// Update the finish probability, by increasing it!
// Transaction count criteria.
// As we know that this function is called on every new
// transfer (transaction), we don't check if transactionCount
// increased or not - we just perform probability update.
finishProbablity += cfg.finish_probabilityIncreaseStep_transaction;
// Now, perform holder count criteria update.
// Finish probability increases, no matter if holder count
// increases or decreases.
if( holderCountChanged )
finishProbablity += cfg.finish_probabilityIncreaseStep_holder;
}
/**
* Start the Ending Stage, by De-Activating the lottery,
* to deny all further token transfers (excluding the one when
* removing liquidity from Uniswap), and transition into the
* Mining Phase - set the lotteryStage to MINING.
*/
function startEndingStage()
internal
{
lotteryStage = uint8( STAGE.ENDING_MINING );
}
/**
* Execute the first step of the Mining Stage - request a
* Random Seed from the Randomness Provider.
*
* Here, we call the Randomness Provider, asking for a true random seed
* to be passed to us into our callback, named
* "finish_randomnessProviderCallback()".
*
* When that callback will be called, our storage's random seed will
* be set, and we'll be able to start the Ending Algorithm on
* further mining steps.
*
* Notice that Randomness Provider must already be funded, to
* have enough Ether for Provable fee and the gas costs of our
* callback function, which are quite high, because of winner
* selection algorithm, which is computationally expensive.
*
* The Randomness Provider is always funded by the Pool,
* right before the Pool deploys and starts a new lottery, so
* as every lottery calls the Randomness Provider only once,
* the one-call-fund method for every lottery is sufficient.
*
* Also notice, that Randomness Provider might fail to call
* our callback due to some unknown reasons!
* Then, the lottery profits could stay locked in this
* lottery contract forever ?!!
*
* No! We've thought about that - we've implemented the
* Alternative Ending mechanism, where, if specific time passes
* after we've made a request to Randomness Provider, and
* callback hasn't been called yet, we allow external actor to
* execute the Alternative ending, which basically does the
* same things as the default ending, just that the Random Seed
* will be computed locally in our contract, using the
* Pseudo-Random mechanism, which could compute a reasonably
* fair and safe value using data from holder array, and other
* values, described in more detail on corresponding function's
* description.
*/
function mine_requestRandomSeed()
internal
{
// We're sure that the Randomness Provider has enough funds.
// Execute the random request, and get ready for Ending Algorithm.
IRandomnessProvider( randomnessProvider )
.requestRandomSeedForLotteryFinish();
// Store the time when random seed has been requested, to
// be able to alternatively handle the lottery finish, if
// randomness provider doesn't call our callback for some
// reason.
finish_timeRandomSeedRequested = uint32( now );
// Emit appropriate events.
emit RandomnessProviderCalled();
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the Owner & Pool profit shares, when lottery ends.
* This function is the first one that's executed on the Mining
* Stage.
* This is the first step of Mining. So, the Miner who executes this
* function gets the mining reward.
*
* This function's job is to Gather the Profits & Initial Funds,
* and Transfer them to Profiters - that is, to The Pool, and
* to The Owner.
*
* The Miners' profit share and Winner Prize Fund stay in this
* contract.
*
* On this function, we (in this order):
*
* 1. Remove all liquidity from Uniswap (if using Uniswap Mode),
* pulling it to our contract's wallet.
*
* 2. Transfer the Owner and the Pool ETH profit shares to
* Owner and Pool addresses.
*
* * This function transfers Ether out of our contract:
* - We transfer the Profits to Pool and Owner addresses.
*/
function mine_removeUniswapLiquidityAndTransferProfits()
internal
mutexLOCKED
{
// We've already approved our token allowance to Router.
// Now, approve Uniswap liquidity token's Router allowance.
ERC20( exchangeAddress ).approve( address(uniswapRouter), uint(-1) );
// Enable the SPECIAL-TRANSFER mode, to allow Uniswap to transfer
// the tokens from Pair to Router, and then from Router to us.
specialTransferModeEnabled = true;
// Remove liquidity!
uint amountETH = uniswapRouter
.removeLiquidityETHSupportingFeeOnTransferTokens(
address(this), // address token,
ERC20( exchangeAddress ).balanceOf( address(this) ),
0, // uint amountTokenMin,
0, // uint amountETHMin,
address(this), // address to,
(now + 10000000) // uint deadline
);
// Tokens are transfered. Disable the special transfer mode.
specialTransferModeEnabled = false;
// Check that we've got a correct amount of ETH.
require( address(this).balance >= amountETH &&
address(this).balance >= cfg.initialFunds );
// Compute the Profit Amount (current balance - initial funds).
ending_totalReturn = uint128( address(this).balance );
ending_profitAmount = ending_totalReturn - uint128( cfg.initialFunds );
// Compute, and Transfer Owner's profit share and
// Pool's profit share to their respective addresses.
uint poolShare = ( ending_profitAmount * cfg.poolProfitShare ) /
( _100PERCENT );
uint ownerShare = ( ending_profitAmount * cfg.ownerProfitShare ) /
( _100PERCENT );
// To pool, transfer it's profit share plus initial funds.
IUniLotteryPool( poolAddress ).lotteryFinish
{ value: poolShare + cfg.initialFunds }
( ending_totalReturn, ending_profitAmount );
// Transfer Owner's profit share.
OWNER_ADDRESS.transfer( ownerShare );
// Emit ending event.
emit LotteryEnd( ending_totalReturn, ending_profitAmount );
}
/**
* Executes a single step of the Winner Selection Algorithm
* (the Ending Algorithm).
* The algorithm itself is being executed in the Storage contract.
*
* On current design, whole algorithm is executed in a single step.
*
* This function is executed only in the Mining stage, and
* accounts for most of the gas spent during mining.
*/
function mine_executeEndingAlgorithmStep()
internal
{
// Launch the winner algorithm, to execute the next step.
lotStorage.executeWinnerSelectionAlgorithm();
}
// =============== Public functions =============== //
/**
* Constructor of this delegate code contract.
* Here, we set OUR STORAGE's lotteryStage to DISABLED, because
* we don't want anybody to call this contract directly.
*/
constructor() public
{
lotteryStage = uint8( STAGE.DISABLED );
}
/**
* Construct the lottery contract which is delegating it's
* call to us.
*
* @param config - LotteryConfig structure to use in this lottery.
*
* Future approach: ABI-encoded Lottery Config
* (different implementations might use different config
* structures, which are ABI-decoded inside the implementation).
*
* Also, this "config" includes the ABI-encoded temporary values,
* which are not part of persisted LotteryConfig, but should
* be used only in constructor - for example, values to be
* assigned to storage variables, such as ERC20 token's
* name, symbol, and decimals.
*
* @param _poolAddress - Address of the Main UniLottery Pool, which
* provides initial funds, and receives it's profit share.
*
* @param _randomProviderAddress - Address of a Randomness Provider,
* to use for obtaining random seeds.
*
* @param _storageAddress - Address of a Lottery Storage.
* Storage contract is a separate contract which holds all
* lottery token holder data, such as intermediate scores.
*
*/
function construct(
LotteryConfig memory config,
address payable _poolAddress,
address _randomProviderAddress,
address _storageAddress )
external
{
// Check if contract wasn't already constructed!
require( poolAddress == address( 0 ) );
// Set the Pool's Address - notice that it's not the
// msg.sender, because lotteries aren't created directly
// by the Pool, but by the Lottery Factory!
poolAddress = _poolAddress;
// Set the Randomness Provider address.
randomnessProvider = _randomProviderAddress;
// Check the minimum & maximum requirements for config
// profit & lifetime parameters.
require( config.maxLifetime <= MAX_LOTTERY_LIFETIME );
require( config.poolProfitShare >= MIN_POOL_PROFITS &&
config.poolProfitShare <= MAX_POOL_PROFITS );
require( config.ownerProfitShare >= MIN_OWNER_PROFITS &&
config.ownerProfitShare <= MAX_OWNER_PROFITS );
require( config.minerProfitShare >= MIN_MINER_PROFITS &&
config.minerProfitShare <= MAX_MINER_PROFITS );
// Check if winner profit share is good.
uint32 totalWinnerShare =
(_100PERCENT) - config.poolProfitShare
- config.ownerProfitShare
- config.minerProfitShare;
require( totalWinnerShare >= MIN_WINNER_PROFIT_SHARE );
// Check if ending algorithm params are good.
require( config.randRatio_scorePart != 0 &&
config.randRatio_randPart != 0 &&
( config.randRatio_scorePart +
config.randRatio_randPart ) < 10000 );
require( config.endingAlgoType ==
uint8( EndingAlgoType.MinedWinnerSelection ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.WinnerSelfValidation ) ||
config.endingAlgoType ==
uint8( EndingAlgoType.RolledRandomness ) );
// Set the number of winners (winner count).
// If using Computed Sequence winner prize shares, set that
// value, and if it's zero, then we're using the Array-Mode
// prize share specification.
if( config.prizeSequence_winnerCount == 0 &&
config.winnerProfitShares.length != 0 )
config.prizeSequence_winnerCount =
uint16( config.winnerProfitShares.length );
// Setup our Lottery Storage - initialize, and set the
// Algorithm Config.
LotteryStorage _lotStorage = LotteryStorage( _storageAddress );
// Setup a Winner Score Config for the winner selection algo,
// to be used in the Lottery Storage.
LotteryStorage.WinnerAlgorithmConfig memory winnerConfig;
// Algorithm type.
winnerConfig.endingAlgoType = config.endingAlgoType;
// Individual player max score parts.
winnerConfig.maxPlayerScore_etherContributed =
config.maxPlayerScore_etherContributed;
winnerConfig.maxPlayerScore_tokenHoldingAmount =
config.maxPlayerScore_tokenHoldingAmount;
winnerConfig.maxPlayerScore_timeFactor =
config.maxPlayerScore_timeFactor;
winnerConfig.maxPlayerScore_refferalBonus =
config.maxPlayerScore_refferalBonus;
// Score-To-Random ratio parts.
winnerConfig.randRatio_scorePart = config.randRatio_scorePart;
winnerConfig.randRatio_randPart = config.randRatio_randPart;
// Set winner count (no.of winners).
winnerConfig.winnerCount = config.prizeSequence_winnerCount;
// Initialize the storage (bind it to our contract).
_lotStorage.initialize( winnerConfig );
// Set our immutable variable.
lotStorage = _lotStorage;
// Now, set our config to the passed config.
cfg = config;
// Might be un-needed (can be replaced by Constant on the MainNet):
WETHaddress = uniswapRouter.WETH();
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
*
* Fallback Receive Ether function.
* Used to receive ETH funds back from Uniswap, on lottery's end,
* when removing liquidity.
*/
receive() external payable
{
emit FallbackEtherReceiver( msg.sender, msg.value );
}
/** PAYABLE [ IN ] <<<<<<<<<<<<<<<<<<<<<<<<<<<<
* PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Initialization function.
* Here, the most important startup operations are made -
* such as minting initial token supply and transfering it to
* the Uniswap liquidity pair, in exchange for UNI-v2 tokens.
*
* This function is called by the pool, when transfering
* initial funds to this contract.
*
* What's payable?
* - Pool transfers initial funds to our contract.
* - We transfer that initial fund Ether to Uniswap liquidity pair
* when creating/providing it.
*/
function initialize()
external
payable
poolOnly
mutexLOCKED
onlyOnStage( STAGE.INITIAL )
{
// Check if pool transfered correct amount of funds.
require( address( this ).balance == cfg.initialFunds );
// Set start date.
startDate = uint32( now );
// Set the initial transfer hash value.
transferHashValue = uint( keccak256(
abi.encodePacked( msg.sender, now ) ) );
// Set initial finish probability, to be used when finishing
// stage starts.
finishProbablity = cfg.finish_initialProbability;
// ===== Active operations - mint & distribute! ===== //
// Mint full initial supply of tokens to our contract address!
_mint( address(this),
uint( cfg.initialTokenSupply ) * (10 ** decimals) );
// Now - prepare to create a new Uniswap Liquidity Pair,
// with whole our total token supply and initial funds ETH
// as the two liquidity reserves.
// Approve Uniswap Router to allow it to spend our tokens.
// Set maximum amount available.
_approve( address(this), address( uniswapRouter ), uint(-1) );
// Provide liquidity - the Router will automatically
// create a new Pair.
uniswapRouter.addLiquidityETH
{ value: address(this).balance }
(
address(this), // address token,
totalSupply(), // uint amountTokenDesired,
totalSupply(), // uint amountTokenMin,
address(this).balance, // uint amountETHMin,
address(this), // address to,
(now + 1000) // uint deadline
);
// Get the Pair address - that will be the exchange address.
exchangeAddress = IUniswapFactory( uniswapRouter.factory() )
.getPair( WETHaddress, address(this) );
// We assume that the token reserves of the pair are good,
// and that we own the full amount of liquidity tokens.
// Find out which of the pair tokens is WETH - is it the
// first or second one. Use it later, when getting our share.
if( IUniswapPair( exchangeAddress ).token0() == WETHaddress )
uniswap_ethFirst = true;
else
uniswap_ethFirst = false;
// Move to ACTIVE lottery stage.
// Now, all token transfers will be allowed.
lotteryStage = uint8( STAGE.ACTIVE );
// Lottery is initialized. We're ready to emit event.
emit LotteryInitialized();
}
// Return this lottery's initial funds, as were specified in the config.
//
function getInitialFunds() external view
returns( uint )
{
return cfg.initialFunds;
}
// Return active (still not returned to pool) initial fund value.
// If no-longer-active, return 0 (default) - because funds were
// already returned back to the pool.
//
function getActiveInitialFunds() external view
returns( uint )
{
if( onStage( STAGE.ACTIVE ) )
return cfg.initialFunds;
return 0;
}
/**
* Get current Exchange's Token and ETH reserves.
* We're on Uniswap mode, so get reserves from Uniswap.
*/
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
// Use data from Uniswap pair contract.
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
/**
* Get our share (ETH amount) of the Uniswap Pair ETH reserve,
* of our Lottery tokens ULT-WETH liquidity pair.
*/
function getCurrentEthFunds()
public view
returns( uint ethAmount )
{
IUniswapPair pair = IUniswapPair( exchangeAddress );
( uint112 res0, uint112 res1, ) = pair.getReserves();
uint resEth = uint( uniswap_ethFirst ? res0 : res1 );
// Compute our amount of the ETH reserve, based on our
// percentage of our liquidity token balance to total supply.
uint liqTokenPercentage =
( pair.balanceOf( address(this) ) * (_100PERCENT) ) /
( pair.totalSupply() );
// Compute and return the ETH reserve.
return ( resEth * liqTokenPercentage ) / (_100PERCENT);
}
/**
* Get current finish probability.
* If it's ACTIVE stage, return 0 automatically.
*/
function getFinishProbability()
external view
returns( uint32 )
{
if( onStage( STAGE.FINISHING ) )
return finishProbablity;
return 0;
}
/**
* Generate a referral ID for msg.sender, who must be a token holder.
* Referral ID is used to refer other wallets into playing our
* lottery.
* - Referrer gets bonus points for every wallet that bought
* lottery tokens and specified his referral ID.
* - Referrees (wallets who got referred by registering a valid
* referral ID, corresponding to some referrer), get some
* bonus points for specifying (registering) a referral ID.
*
* Referral ID is a uint256 number, which is generated by
* keccak256'ing the holder's address, holder's current
* token ballance, and current time.
*/
function generateReferralID()
external
onlyOnStage( STAGE.ACTIVE )
{
uint256 refID = lotStorage.generateReferralID( msg.sender );
// Emit approppriate events.
emit ReferralIDGenerated( msg.sender, refID );
}
/**
* Register a referral for a msg.sender (must be token holder),
* using a valid referral ID got from a referrer.
* This function is called by a referree, who obtained a
* valid referral ID from some referrer, who previously
* generated it using generateReferralID().
*
* You can only register a referral once!
* When you do so, you get bonus referral points!
*/
function registerReferral(
uint256 referralID )
external
onlyOnStage( STAGE.ACTIVE )
{
address referrer = lotStorage.registerReferral(
msg.sender,
cfg.playerScore_referralRegisteringBonus,
referralID );
// Emit approppriate events.
emit ReferralRegistered( msg.sender, referrer, referralID );
}
/**
* The most important function of this contract - Transfer Function.
*
* Here, all token burning, intermediate score tracking, and
* finish condition checking is performed, according to the
* properties specified in config.
*/
function _transfer( address sender,
address receiver,
uint256 amount )
internal
override
{
// Check if transfers are allowed in current state.
// On Non-Active stage, transfers are allowed only from/to
// our contract.
// As we don't have Standalone Mode on this lottery variation,
// that means that tokens to/from our contract are travelling
// only when we transfer them to Uniswap Pair, and when
// Uniswap transfers them back to us, on liquidity remove.
//
// On this state, we also don't perform any burns nor
// holding trackings - just transfer and return.
if( !onStage( STAGE.ACTIVE ) &&
!onStage( STAGE.FINISHING ) &&
( sender == address(this) || receiver == address(this) ||
specialTransferModeEnabled ) )
{
super._transfer( sender, receiver, amount );
return;
}
// Now, we know that we're NOT on special mode.
// Perform standard checks & brecks.
require( ( onStage( STAGE.ACTIVE ) ||
onStage( STAGE.FINISHING ) ) );
// Can't transfer zero tokens, or use address(0) as sender.
require( amount != 0 && sender != address(0) );
// Compute the Burn Amount - if buying tokens from an exchange,
// we use a lower burn rate - to incentivize buying!
// Otherwise (if selling or just transfering between wallets),
// we use a higher burn rate.
uint burnAmount;
// It's a buy - sender is an exchange.
if( sender == exchangeAddress )
burnAmount = ( amount * cfg.burn_buyerRate ) / (_100PERCENT);
else
burnAmount = ( amount * cfg.burn_defaultRate ) / (_100PERCENT);
// Now, compute the final amount to be gotten by the receiver.
uint finalAmount = amount - burnAmount;
// Check if receiver's balance won't exceed the max-allowed!
// Receiver must not be an exchange.
if( receiver != exchangeAddress )
{
require( !transferExceedsMaxBalance( receiver, finalAmount ) );
}
// Now, update holder data array accordingly.
bool holderCountChanged = updateHolderData_preTransfer(
sender,
receiver,
amount, // Amount Sent (Pre-Fees)
finalAmount // Amount Received (Post-Fees).
);
// All is ok - perform the burn and token transfers now.
// Burn token amount from sender's balance.
super._burn( sender, burnAmount );
// Finally, transfer the final amount from sender to receiver.
super._transfer( sender, receiver, finalAmount );
// Compute new Pseudo-Random transfer hash, which must be
// computed for every transfer, and is used in the
// Finishing Stage as a pseudo-random unique value for
// every transfer, by which we determine whether lottery
// should end on this transfer.
//
// Compute it like this: keccak the last (current)
// transferHashValue, msg.sender, sender, receiver, amount.
transferHashValue = uint( keccak256( abi.encodePacked(
transferHashValue, msg.sender, sender, receiver, amount ) ) );
// Check if we should be starting a finishing stage now.
checkFinishingStageConditions();
// If we're on finishing stage, check for ending conditions.
// If ending check is satisfied, the checkForEnding() function
// starts ending operations.
if( onStage( STAGE.FINISHING ) )
checkForEnding( holderCountChanged );
}
/**
* Callback function, which is called from Randomness Provider,
* after it obtains a random seed to be passed to us, after
* we have initiated The Ending Stage, on which random seed
* is used to generate random factors for Winner Selection
* algorithm.
*/
function finish_randomnessProviderCallback(
uint256 randomSeed,
uint256 /*callID*/ )
external
randomnessProviderOnly
{
// Set the random seed in the Storage Contract.
lotStorage.setRandomSeed( randomSeed );
// If algo-type is not Mined Winner Selection, then by now
// we assume lottery as COMPL3T3D.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
}
}
/**
* Function checks if we can initiate Alternative Seed generation.
*
* Alternative approach to Lottery Random Seed is used only when
* Randomness Provider doesn't work, and doesn't call the
* above callback.
*
* This alternative approach can be initiated by Miners, when
* these conditions are met:
* - Lottery is on Ending (Mining) stage.
* - Request to Randomness Provider was made at least X time ago,
* and our callback hasn't been called yet.
*
* If these conditions are met, we can initiate the Alternative
* Random Seed generation, which generates a seed based on our
* state.
*/
function alternativeSeedGenerationPossible()
internal view
returns( bool )
{
return ( onStage( STAGE.ENDING_MINING ) &&
( (now - finish_timeRandomSeedRequested) >
cfg.REQUIRED_TIME_WAITING_FOR_RANDOM_SEED ) );
}
/**
* Return this lottery's config, using ABIEncoderV2.
*/
/*function getLotteryConfig()
external view
returns( LotteryConfig memory ourConfig )
{
return cfg;
}*/
/**
* Checks if Mining is currently available.
*/
function isMiningAvailable()
external view
returns( bool )
{
return onStage( STAGE.ENDING_MINING ) &&
( miningStep == 0 ||
( miningStep == 1 &&
( lotStorage.getRandomSeed() != 0 ||
alternativeSeedGenerationPossible() )
) );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Mining function, to be executed on Ending (Mining) stage.
*
* "Mining" approach is used in this lottery, to use external
* actors for executing the gas-expensive Ending Algorithm,
* and other ending operations, such as profit transfers.
*
* "Miners" can be any external actors who call this function.
* When Miner successfully completes a Mining Step, he gets
* a Mining Reward, which is a certain portion of lottery's profit
* share, dedicated to Miners.
*
* NOT-IMPLEMENTED APPROACH:
*
* All these operations are divided into "mining steps", which are
* smaller components, which fit into reasonable gas limits.
* All "steps" are designed to take up similar amount of gas.
*
* For example, if total lottery profits (total ETH got from
* pulling liquidity out of Uniswap, minus initial funds),
* is 100 ETH, Miner Profit Share is 10%, and there are 5 mining
* steps total, then for a singe step executed, miner will get:
*
* (100 * 0.1) / 5 = 2 ETH.
*
* ---------------------------------
*
* CURRENTLY IMPLEMENTED APPROACH:
*
* As the above-defined approach would consume very much gas for
* inter-step intermediate state storage, we have thought that
* for now, it's better to have only 2 mining steps, the second of
* which performs the whole Winner Selection Algorithm.
*
* This is because performing the whole algorithm at once would save
* us up to 10x more gas in total, than executing it in steps.
*
* However, this solution is not scalable, because algorithm has
* to fit into block gas limit (10,000,000 gas), so we are limited
* to a certain safe maximum number of token holders, which is
* empirically determined during testing, and defined in the
* MAX_SAFE_NUMBER_OF_HOLDERS constant, which is checked against the
* config value "finishCriteria_minNumberOfHolders" in constructor.
*
* So, in this approach, there are only 2 mining steps:
*
* 1. Remove liquidity from Uniswap, transfer profit shares to
* the Pool and the Owner Address, and request Random Seed
* from the Randomness Provider.
* Reward: 25% of total Mining Rewards.
*
* 2. Perform the whole Winner Selection Algorithm inside the
* Lottery Storage contract.
* Reward: 75% of total Mining Rewards.
*
* * Function transfers Ether out of our contract:
* - Transfers the current miner's reward to msg.sender.
*/
function mine()
external
onlyOnStage( STAGE.ENDING_MINING )
{
uint currentStepReward;
// Perform different operations on different mining steps.
// Step 0: Remove liquidity from Uniswap, transfer profits to
// Pool and Owner addresses. Also, request a Random Seed
// from the Randomness Provider.
if( miningStep == 0 )
{
mine_requestRandomSeed();
mine_removeUniswapLiquidityAndTransferProfits();
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Step 0 reward is 10% for Algo type 1.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward = ( totalMinerRewards * (10 * PERCENT) ) /
( _100PERCENT );
}
// If other algo-types, second step is not normally needed,
// so here we take 80% of miner rewards.
// If Randomness Provider won't give us a seed after
// specific amount of time, we'll initiate a second step,
// with remaining 20% of miner rewords.
else
{
currentStepReward = ( totalMinerRewards * (80 * PERCENT) ) /
( _100PERCENT );
}
require( currentStepReward <= totalMinerRewards );
}
// Step 1:
// If we use MinedWinnerSelection algo-type, then execute the
// winner selection algorithm.
// Otherwise, check if Random Provider hasn't given us a
// random seed long enough, so that we have to generate a
// seed locally.
else
{
// Check if we can go into this step when using specific
// ending algorithm types.
if( cfg.endingAlgoType != uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.getRandomSeed() == 0 &&
alternativeSeedGenerationPossible() );
}
// Compute total miner reward amount, then compute this
// step's reward later.
uint totalMinerRewards =
( ending_profitAmount * cfg.minerProfitShare ) /
( _100PERCENT );
// Firstly, check if random seed is already obtained.
// If not, check if we should generate it locally.
if( lotStorage.getRandomSeed() == 0 )
{
if( alternativeSeedGenerationPossible() )
{
// Set random seed inside the Storage Contract,
// but using our contract's transferHashValue as the
// random seed.
// We believe that this hash has enough randomness
// to be considered a fairly good random seed,
// because it has beed chain-computed for every
// token transfer that has occured in ACTIVE stage.
//
lotStorage.setRandomSeed( transferHashValue );
// If using Non-Mined algorithm types, reward for this
// step is 20% of miner funds.
if( cfg.endingAlgoType !=
uint8(EndingAlgoType.MinedWinnerSelection) )
{
currentStepReward =
( totalMinerRewards * (20 * PERCENT) ) /
( _100PERCENT );
}
}
else
{
// If alternative seed generation is not yet possible
// (not enough time passed since the rand.provider
// request was made), then mining is not available
// currently.
require( false );
}
}
// Now, we know that Random Seed is obtained.
// If we use this algo-type, perform the actual
// winner selection algorithm.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
mine_executeEndingAlgorithmStep();
// Set the prize amount to SECOND STEP prize amount (90%).
currentStepReward = ( totalMinerRewards * (90 * PERCENT) ) /
( _100PERCENT );
}
// Now we've completed both Mining Steps, it means MINING stage
// is finally completed!
// Transition to COMPLETION stage, and set lottery completion
// time to NOW.
lotteryStage = uint8( STAGE.COMPLETION );
completionDate = uint32( now );
require( currentStepReward <= totalMinerRewards );
}
// Now, transfer the reward to miner!
// Check for bugs too - if the computed amount doesn't exceed.
// Increment the mining step - move to next step (if there is one).
miningStep++;
// Check & Lock the Re-Entrancy Lock for transfers.
require( ! reEntrancyMutexLocked );
reEntrancyMutexLocked = true;
// Finally, transfer the reward to message sender!
msg.sender.transfer( currentStepReward );
// UnLock ReEntrancy Lock.
reEntrancyMutexLocked = false;
}
/**
* Function computes winner prize amount for winner at rank #N.
* Prerequisites: Must be called only on STAGE.COMPLETION stage,
* because we use the final profits amount here, and that value
* (ending_profitAmount) is known only on COMPLETION stage.
*
* @param rankingPosition - ranking position of a winner.
* @return finalPrizeAmount - prize amount, in Wei, of this winner.
*/
function getWinnerPrizeAmount(
uint rankingPosition )
public view
returns( uint finalPrizeAmount )
{
// Calculate total winner prize fund profit percentage & amount.
uint winnerProfitPercentage =
(_100PERCENT) - cfg.poolProfitShare -
cfg.ownerProfitShare - cfg.minerProfitShare;
uint totalPrizeAmount =
( ending_profitAmount * winnerProfitPercentage ) /
( _100PERCENT );
// We compute the prize amounts differently for the algo-type
// RolledRandomness, because distribution of these prizes is
// non-deterministic - multiple holders could fall onto the
// same ranking position, due to randomness of rolled score.
//
if( cfg.endingAlgoType == uint8(EndingAlgoType.RolledRandomness) )
{
// Here, we'll use Prize Sequence Factor approach differently.
// We'll use the prizeSequenceFactor value not to compute
// a geometric progression, but to compute an arithmetic
// progression, where each ranking position will get a
// prize equal to
// "totalPrizeAmount - rankingPosition * singleWinnerShare"
//
// singleWinnerShare is computed as a value corresponding
// to single-winner's share of total prize amount.
//
// Using such an approach, winner at rank 0 would get a
// prize equal to whole totalPrizeAmount, but, as the
// scores are rolled using random factor, it's very unlikely
// to get a such high score, so most likely such prize
// won't ever be claimed, but it is a possibility.
//
// Most of the winners in this approach are likely to
// roll scores in the middle, so would get prizes equal to
// 1-10% of total prize funds.
uint singleWinnerShare = totalPrizeAmount /
cfg.prizeSequence_winnerCount;
return totalPrizeAmount - rankingPosition * singleWinnerShare;
}
// Now, we know that ending algorithm is normal (deterministic).
// So, compute the prizes in a standard way.
// If using Computed Sequence: loop for "rankingPosition"
// iterations, while computing the prize shares.
// If "rankingPosition" is larger than sequencedWinnerCount,
// then compute the prize from sequence-leftover amount.
if( cfg.prizeSequenceFactor != 0 )
{
require( rankingPosition < cfg.prizeSequence_winnerCount );
// Leftover: If prizeSequenceFactor is 25%, it's 75%.
uint leftoverPercentage =
(_100PERCENT) - cfg.prizeSequenceFactor;
// Loop until the needed iteration.
uint loopCount = (
rankingPosition >= cfg.prizeSequence_sequencedWinnerCount ?
cfg.prizeSequence_sequencedWinnerCount :
rankingPosition
);
for( uint i = 0; i < loopCount; i++ )
{
totalPrizeAmount =
( totalPrizeAmount * leftoverPercentage ) /
( _100PERCENT );
}
// Get end prize amount - sequenced, or leftover.
// Leftover-mode.
if( loopCount == cfg.prizeSequence_sequencedWinnerCount &&
cfg.prizeSequence_winnerCount >
cfg.prizeSequence_sequencedWinnerCount )
{
// Now, totalPrizeAmount equals all leftover-group winner
// prize funds.
// So, just divide it by number of leftover winners.
finalPrizeAmount =
( totalPrizeAmount ) /
( cfg.prizeSequence_winnerCount -
cfg.prizeSequence_sequencedWinnerCount );
}
// Sequenced-mode
else
{
finalPrizeAmount =
( totalPrizeAmount * cfg.prizeSequenceFactor ) /
( _100PERCENT );
}
}
// Else, if we're using Pre-Specified Array of winner profit
// shares, just get the share at the corresponding index.
else
{
require( rankingPosition < cfg.winnerProfitShares.length );
finalPrizeAmount =
( totalPrizeAmount *
cfg.winnerProfitShares[ rankingPosition ] ) /
( _100PERCENT );
}
}
/**
* After lottery has completed, this function returns if msg.sender
* is one of lottery winners, and the position in winner rankings.
*
* Function must be used to obtain the ranking position before
* calling claimWinnerPrize().
*
* @param addr - address whose status to check.
*/
function getWinnerStatus( address addr )
external view
returns( bool isWinner, uint32 rankingPosition,
uint prizeAmount )
{
if( !onStage( STAGE.COMPLETION ) || balanceOf( addr ) == 0 )
return (false , 0, 0);
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( addr );
if( isWinner )
{
prizeAmount = getWinnerPrizeAmount( rankingPosition );
if( prizeAmount > address(this).balance )
prizeAmount = address(this).balance;
}
}
/**
* Compute the intermediate Active Stage player score.
* This score is Player Score, not randomized.
* @param addr - address to check.
*/
function getPlayerIntermediateScore( address addr )
external view
returns( uint )
{
return lotStorage.getPlayerActiveStageScore( addr );
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Claim the winner prize of msg.sender, if he is one of the winners.
*
* This function must be provided a ranking position of msg.sender,
* which must be obtained using the function above.
*
* The Lottery Storage then just checks if holder address in the
* winner array element at position rankingPosition is the same
* as msg.sender's.
*
* If so, then claim request is valid, and we can give the appropriate
* prize to that winner.
* Prize can be determined by a computed factor-based sequence, or
* from the pre-specified winner array.
*
* * This function transfers Ether out of our contract:
* - Sends the corresponding winner prize to the msg.sender.
*
* @param rankingPosition - the position of Winner Array, that
* msg.sender says he is in (obtained using getWinnerStatus).
*/
function claimWinnerPrize(
uint32 rankingPosition )
external
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if msg.sender hasn't already claimed his prize.
require( ! prizeClaimersAddresses[ msg.sender ] );
// msg.sender must have at least some of UniLottery Tokens.
require( balanceOf( msg.sender ) != 0 );
// Check if there are any prize funds left yet.
require( address(this).balance != 0 );
// If using Mined Selection Algo, check if msg.sender is
// really on that ranking position - algo was already executed.
if( cfg.endingAlgoType == uint8(EndingAlgoType.MinedWinnerSelection) )
{
require( lotStorage.minedSelection_isAddressOnWinnerPosition(
msg.sender, rankingPosition ) );
}
// For other algorithms, get ranking position by executing
// a specific algorithm of that algo-type.
else
{
bool isWinner;
( isWinner, rankingPosition ) =
lotStorage.getWinnerStatus( msg.sender );
require( isWinner );
}
// Compute the prize amount, using our internal function.
uint finalPrizeAmount = getWinnerPrizeAmount( rankingPosition );
// If prize is small and computation precision errors occured,
// leading it to be larger than our balance, fix it.
if( finalPrizeAmount > address(this).balance )
finalPrizeAmount = address(this).balance;
// Transfer the Winning Prize to msg.sender!
msg.sender.transfer( finalPrizeAmount );
// Mark msg.sender as already claimed his prize.
prizeClaimersAddresses[ msg.sender ] = true;
}
/** PAYABLE [ OUT ] >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
*
* Transfer the leftover Winner Prize Funds of this contract to the
* Main UniLottery Pool, if prize claim deadline has been exceeded.
*
* Function can only be called from the Main Pool, and if some
* winners haven't managed to claim their prizes on time, their
* prizes will go back to UniLottery Pool.
*
* * Function transfers Ether out of our contract:
* - Transfer the leftover funds to the Pool (msg.sender).
*/
function getUnclaimedPrizes()
external
poolOnly
onlyOnStage( STAGE.COMPLETION )
mutexLOCKED
{
// Check if prize claim deadline has passed.
require( completionDate != 0 &&
( now - completionDate ) > cfg.prizeClaimTime );
// Just transfer it all to the Pool.
poolAddress.transfer( address(this).balance );
}
}
|
Use data from Uniswap pair contract.
|
function getReserves()
external view
returns( uint _ethReserve, uint _tokenReserve )
{
( uint112 res0, uint112 res1, ) =
IUniswapPair( exchangeAddress ).getReserves();
if( uniswap_ethFirst )
return ( res0, res1 );
else
return ( res1, res0 );
}
| 7,490,250 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./interfaces/IVotingPower.sol";
import "./interfaces/ITokenRegistry.sol";
import "./interfaces/IVotingPowerFormula.sol";
import "./interfaces/ILockManager.sol";
import "./lib/AccessControlEnumerable.sol";
/**
* @title LockManager
* @dev Manages voting power for stakes that are locked within the Eden ecosystem, but not in the Voting Power prism
*/
contract LockManager is AccessControlEnumerable, ILockManager {
/// @notice Admin role to create voting power from locked stakes
bytes32 public constant LOCKER_ROLE = keccak256("LOCKER_ROLE");
// Official record of staked balances for each account > token > locked stake
mapping (address => mapping (address => LockedStake)) internal lockedStakes;
/// @notice Voting power contract
IVotingPower public immutable votingPower;
/// @notice modifier to restrict functions to only contracts that have been added as lockers
modifier onlyLockers() {
require(hasRole(LOCKER_ROLE, msg.sender), "Caller must have LOCKER_ROLE role");
_;
}
/// @notice An event that's emitted when a user's staked balance increases
event StakeLocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/// @notice An event that's emitted when a user's staked balance decreases
event StakeUnlocked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
/**
* @notice Create new LockManager contract
* @param _votingPower VotingPower prism contract
* @param _roleManager address that is in charge of assigning roles
*/
constructor(address _votingPower, address _roleManager) {
votingPower = IVotingPower(_votingPower);
_setupRole(DEFAULT_ADMIN_ROLE, _roleManager);
}
/**
* @notice Get total amount of tokens staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total amount staked
*/
function getAmountStaked(address staker, address stakedToken) external view override returns (uint256) {
return getStake(staker, stakedToken).amount;
}
/**
* @notice Get total staked amount and voting power from `stakedToken` staked in contract by `staker`
* @param staker The user with staked tokens
* @param stakedToken The staked token
* @return total staked
*/
function getStake(address staker, address stakedToken) public view override returns (LockedStake memory) {
return lockedStakes[staker][stakedToken];
}
/**
* @notice Calculate the voting power that will result from locking `amount` of `token`
* @param token token that will be locked
* @param amount amount of token that will be locked
* @return resulting voting power
*/
function calculateVotingPower(address token, uint256 amount) public view override returns (uint256) {
address registry = votingPower.tokenRegistry();
require(registry != address(0), "LM::calculateVotingPower: registry not set");
address tokenFormulaAddress = ITokenRegistry(registry).tokenFormulas(token);
require(tokenFormulaAddress != address(0), "LM::calculateVotingPower: token not supported");
IVotingPowerFormula tokenFormula = IVotingPowerFormula(tokenFormulaAddress);
return tokenFormula.convertTokensToVotingPower(amount);
}
/**
* @notice Grant voting power from locked `tokenAmount` of `token`
* @param receiver recipient of voting power
* @param token token that is locked
* @param tokenAmount amount of token that is locked
* @return votingPowerGranted amount of voting power granted
*/
function grantVotingPower(
address receiver,
address token,
uint256 tokenAmount
) external override onlyLockers returns (uint256 votingPowerGranted){
votingPowerGranted = calculateVotingPower(token, tokenAmount);
lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount + tokenAmount;
lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower + votingPowerGranted;
votingPower.addVotingPowerForLockedTokens(receiver, votingPowerGranted);
emit StakeLocked(receiver, token, tokenAmount, votingPowerGranted);
}
/**
* @notice Remove voting power by unlocking `tokenAmount` of `token`
* @param receiver holder of voting power
* @param token token that is being unlocked
* @param tokenAmount amount of token that is being unlocked
* @return votingPowerRemoved amount of voting power removed
*/
function removeVotingPower(
address receiver,
address token,
uint256 tokenAmount
) external override onlyLockers returns (uint256 votingPowerRemoved) {
require(lockedStakes[receiver][token].amount >= tokenAmount, "LM::removeVotingPower: not enough tokens staked");
LockedStake memory s = getStake(receiver, token);
votingPowerRemoved = tokenAmount * s.votingPower / s.amount;
lockedStakes[receiver][token].amount = lockedStakes[receiver][token].amount - tokenAmount;
lockedStakes[receiver][token].votingPower = lockedStakes[receiver][token].votingPower - votingPowerRemoved;
votingPower.removeVotingPowerForUnlockedTokens(receiver, votingPowerRemoved);
emit StakeUnlocked(receiver, token, tokenAmount, votingPowerRemoved);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
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: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable {
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// 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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ILockManager {
struct LockedStake {
uint256 amount;
uint256 votingPower;
}
function getAmountStaked(address staker, address stakedToken) external view returns (uint256);
function getStake(address staker, address stakedToken) external view returns (LockedStake memory);
function calculateVotingPower(address token, uint256 amount) external view returns (uint256);
function grantVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerGranted);
function removeVotingPower(address receiver, address token, uint256 tokenAmount) external returns (uint256 votingPowerRemoved);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITokenRegistry {
function owner() external view returns (address);
function tokenFormulas(address) external view returns (address);
function setTokenFormula(address token, address formula) external;
function removeToken(address token) external;
function changeOwner(address newOwner) external;
event ChangedOwner(address indexed oldOwner, address indexed newOwner);
event TokenAdded(address indexed token, address indexed formula);
event TokenRemoved(address indexed token);
event TokenFormulaUpdated(address indexed token, address indexed formula);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../lib/PrismProxy.sol";
interface IVotingPower {
struct Stake {
uint256 amount;
uint256 votingPower;
}
function setPendingProxyImplementation(address newPendingImplementation) external returns (bool);
function acceptProxyImplementation() external returns (bool);
function setPendingProxyAdmin(address newPendingAdmin) external returns (bool);
function acceptProxyAdmin() external returns (bool);
function proxyAdmin() external view returns (address);
function pendingProxyAdmin() external view returns (address);
function proxyImplementation() external view returns (address);
function pendingProxyImplementation() external view returns (address);
function proxyImplementationVersion() external view returns (uint8);
function become(PrismProxy prism) external;
function initialize(address _edenToken, address _owner) external;
function owner() external view returns (address);
function edenToken() external view returns (address);
function tokenRegistry() external view returns (address);
function lockManager() external view returns (address);
function changeOwner(address newOwner) external;
function setTokenRegistry(address registry) external;
function setLockManager(address newLockManager) external;
function stake(uint256 amount) external;
function stakeWithPermit(uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
function withdraw(uint256 amount) external;
function addVotingPowerForLockedTokens(address account, uint256 amount) external;
function removeVotingPowerForUnlockedTokens(address account, uint256 amount) external;
function getEDENAmountStaked(address staker) external view returns (uint256);
function getAmountStaked(address staker, address stakedToken) external view returns (uint256);
function getEDENStake(address staker) external view returns (Stake memory);
function getStake(address staker, address stakedToken) external view returns (Stake memory);
function balanceOf(address account) external view returns (uint256);
function balanceOfAt(address account, uint256 blockNumber) external view returns (uint256);
event NewPendingImplementation(address indexed oldPendingImplementation, address indexed newPendingImplementation);
event NewImplementation(address indexed oldImplementation, address indexed newImplementation);
event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin);
event NewAdmin(address indexed oldAdmin, address indexed newAdmin);
event Staked(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
event Withdrawn(address indexed user, address indexed token, uint256 indexed amount, uint256 votingPower);
event VotingPowerChanged(address indexed voter, uint256 indexed previousBalance, uint256 indexed newBalance);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IVotingPowerFormula {
function convertTokensToVotingPower(uint256 amount) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IAccessControl.sol";
import "./Context.sol";
import "./Strings.sol";
import "./ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been 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) internal {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "./EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).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 {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override {
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);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../interfaces/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 Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract PrismProxy {
/// @notice Proxy admin and implementation storage variables
struct ProxyStorage {
// Administrator for this contract
address admin;
// Pending administrator for this contract
address pendingAdmin;
// Active implementation of this contract
address implementation;
// Pending implementation of this contract
address pendingImplementation;
// Implementation version of this contract
uint8 version;
}
/// @dev Position in contract storage where prism ProxyStorage struct will be stored
bytes32 constant PRISM_PROXY_STORAGE_POSITION = keccak256("prism.proxy.storage");
/// @notice Emitted when pendingImplementation is changed
event NewPendingImplementation(address indexed oldPendingImplementation, address indexed newPendingImplementation);
/// @notice Emitted when pendingImplementation is accepted, which means implementation is updated
event NewImplementation(address indexed oldImplementation, address indexed newImplementation);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address indexed oldPendingAdmin, address indexed newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address indexed oldAdmin, address indexed newAdmin);
/**
* @notice Load proxy storage struct from specified PRISM_PROXY_STORAGE_POSITION
* @return ps ProxyStorage struct
*/
function proxyStorage() internal pure returns (ProxyStorage storage ps) {
bytes32 position = PRISM_PROXY_STORAGE_POSITION;
assembly {
ps.slot := position
}
}
/*** Admin Functions ***/
/**
* @notice Create new pending implementation for prism. msg.sender must be admin
* @dev Admin function for proposing new implementation contract
* @return boolean indicating success of operation
*/
function setPendingProxyImplementation(address newPendingImplementation) public returns (bool) {
ProxyStorage storage s = proxyStorage();
require(msg.sender == s.admin, "Prism::setPendingProxyImp: caller must be admin");
address oldPendingImplementation = s.pendingImplementation;
s.pendingImplementation = newPendingImplementation;
emit NewPendingImplementation(oldPendingImplementation, s.pendingImplementation);
return true;
}
/**
* @notice Accepts new implementation for prism. msg.sender must be pendingImplementation
* @dev Admin function for new implementation to accept it's role as implementation
* @return boolean indicating success of operation
*/
function acceptProxyImplementation() public returns (bool) {
ProxyStorage storage s = proxyStorage();
// Check caller is pendingImplementation and pendingImplementation ≠ address(0)
require(msg.sender == s.pendingImplementation && s.pendingImplementation != address(0), "Prism::acceptProxyImp: caller must be pending implementation");
// Save current values for inclusion in log
address oldImplementation = s.implementation;
address oldPendingImplementation = s.pendingImplementation;
s.implementation = s.pendingImplementation;
s.pendingImplementation = address(0);
s.version++;
emit NewImplementation(oldImplementation, s.implementation);
emit NewPendingImplementation(oldPendingImplementation, s.pendingImplementation);
return true;
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return boolean indicating success of operation
*/
function setPendingProxyAdmin(address newPendingAdmin) public returns (bool) {
ProxyStorage storage s = proxyStorage();
// Check caller = admin
require(msg.sender == s.admin, "Prism::setPendingProxyAdmin: caller must be admin");
// Save current value, if any, for inclusion in log
address oldPendingAdmin = s.pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
s.pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return true;
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return boolean indicating success of operation
*/
function acceptProxyAdmin() public returns (bool) {
ProxyStorage storage s = proxyStorage();
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
require(msg.sender == s.pendingAdmin && msg.sender != address(0), "Prism::acceptProxyAdmin: caller must be pending admin");
// Save current values for inclusion in log
address oldAdmin = s.admin;
address oldPendingAdmin = s.pendingAdmin;
// Store admin with value pendingAdmin
s.admin = s.pendingAdmin;
// Clear the pending value
s.pendingAdmin = address(0);
emit NewAdmin(oldAdmin, s.admin);
emit NewPendingAdmin(oldPendingAdmin, s.pendingAdmin);
return true;
}
/**
* @notice Get current admin for prism proxy
* @return admin address
*/
function proxyAdmin() public view returns (address) {
ProxyStorage storage s = proxyStorage();
return s.admin;
}
/**
* @notice Get pending admin for prism proxy
* @return admin address
*/
function pendingProxyAdmin() public view returns (address) {
ProxyStorage storage s = proxyStorage();
return s.pendingAdmin;
}
/**
* @notice Address of implementation contract
* @return implementation address
*/
function proxyImplementation() public view returns (address) {
ProxyStorage storage s = proxyStorage();
return s.implementation;
}
/**
* @notice Address of pending implementation contract
* @return pending implementation address
*/
function pendingProxyImplementation() public view returns (address) {
ProxyStorage storage s = proxyStorage();
return s.pendingImplementation;
}
/**
* @notice Current implementation version for proxy
* @return version number
*/
function proxyImplementationVersion() public view returns (uint8) {
ProxyStorage storage s = proxyStorage();
return s.version;
}
/**
* @notice Delegates execution to an implementation contract.
* @dev Returns to the external caller whatever the implementation returns or forwards reverts
*/
function _forwardToImplementation() internal {
ProxyStorage storage s = proxyStorage();
// delegate all other functions to current implementation
(bool success, ) = s.implementation.delegatecall(msg.data);
assembly {
let free_mem_ptr := mload(0x40)
returndatacopy(free_mem_ptr, 0, returndatasize())
switch success
case 0 { revert(free_mem_ptr, returndatasize()) }
default { return(free_mem_ptr, returndatasize()) }
}
}
}
// 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);
}
}
|
Get total amount of tokens staked in contract by `staker` staker The user with staked tokens stakedToken The staked token return total amount staked/
|
function getAmountStaked(address staker, address stakedToken) external view override returns (uint256) {
return getStake(staker, stakedToken).amount;
}
| 14,952,940 |
./full_match/3/0x66719Dd809567233A52d3113D3B0A9a72dDeCE1b/sources/contracts/3_Ballot.sol
|
Dividend-Paying Token Optional Interface Roger Wu (https://github.com/roger-wu) OPTIONAL functions for a dividend-paying token contract.
|
interface DividendPayingTokenOptionalInterface {
function withdrawableDividendOf(address _owner) external view returns (uint256);
function withdrawnDividendOf(address _owner) external view returns (uint256);
function accumulativeDividendOf(address _owner) external view returns (uint256);
}
| 8,234,423 |
/*
Copyright 2019 RigoBlock.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.0;
/// @title ABI Encoder - return an array of encoded parameters.
/// @author Gabriele Rigo - <[email protected]>
contract AbiEncoder {
struct HandlerMockOrder {
uint256 orderAmount;
}
struct ZeroExOrder {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Amount of ZRX paid to feeRecipient by maker when order is filled. If set to 0, no transfer of ZRX from maker to feeRecipient will be attempted.
uint256 takerFee; // Amount of ZRX paid to feeRecipient by taker when order is filled. If set to 0, no transfer of ZRX from taker to feeRecipient will be attempted.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The last byte references the id of this proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The last byte references the id of this proxy.
bytes signature;
}
struct TotleOrder {
address exchangeHandler;
bytes genericPayload;
}
struct TotleTrade {
bool isSell;
address tokenAddress;
uint256 tokenAmount;
bool optionalTrade;
uint256 minimumExchangeRate;
uint256 minimumAcceptableTokenAmount;
TotleOrder[] orders;
}
/*
/// @dev Gets the Abi encoded bytes array of an integer.
/// @param orderAmount integer of amount.
/// @return Byte array of the ABI encoded struct.
function abiEncodeHandlerMockOrder(uint256 orderAmount)
external
pure
returns (bytes memory encodedOrder)
{
HandlerMockOrder memory order;
order.orderAmount = orderAmount;
encodedOrder = abi.encode(order);
return encodedOrder;
}
*/
/*
// @notice: following structs not supported yet
// @notice: pragma ABIEncoderV2 prompts stack-too-deep error
function abiEncodePackedHandlerMockOrder(uint256 orderAmount)
external
pure
returns (bytes memory encodedOrder)
{
HandlerMockOrder memory order;
order.orderAmount = orderAmount;
encodedOrder = abi.encodePacked(order);
return encodedOrder;
}
*/
function abiEncodeZeroExOrder(
address makerAddress,
address takerAddress,
address feeRecipientAddress,
address senderAddress,
uint256 makerAssetAmount,
uint256 takerAssetAmount,
uint256 makerFee,
uint256 takerFee,
uint256 expirationTimeSeconds,
// uint256 salt,
// bytes makerAssetData,
bytes calldata takerAssetData,
bytes calldata signature)
external
pure
returns (bytes memory encodedOrder)
{
return encodedOrder = abi.encode(
makerAddress,
takerAddress,
feeRecipientAddress,
senderAddress,
makerAssetAmount,
takerAssetAmount,
makerFee,
takerFee,
expirationTimeSeconds,
//salt,
//makerAssetData,
takerAssetData,
signature
);
}
/*
function abiEncodePackedZeroExOrder(
address makerAddress,
address takerAddress,
address feeRecipientAddress,
address senderAddress,
uint256 makerAssetAmount,
uint256 takerAssetAmount,
uint256 makerFee,
uint256 takerFee,
uint256 expirationTimeSeconds,
uint256 salt,
bytes memory makerAssetData,
bytes memory takerAssetData)
public
pure
returns (bytes memory encodedOrder)
{
ZeroExOrder memory order;
order.makerAddress = makerAddress;
order.takerAddress = takerAddress;
order.feeRecipientAddress = feeRecipientAddress;
order.senderAddress = senderAddress;
order.makerAssetAmount = makerAssetAmount;
order.takerAssetAmount = takerAssetAmount;
order.makerFee = makerFee;
order.takerFee = takerFee;
order.expirationTimeSeconds = expirationTimeSeconds;
order.salt = salt;
order.makerAssetData = makerAssetData;
order.takerAssetData = takerAssetData;
encodedOrder = abi.encodePacked(
"ZeroExOrder(",
"address makerAddress,",
"address takerAddress,",
"address feeRecipientAddress,",
"address senderAddress,",
"uint256 makerAssetAmount,",
"uint256 takerAssetAmount,",
"uint256 makerFee,",
"uint256 takerFee,",
"uint256 expirationTimeSeconds,",
"uint256 salt,",
"bytes makerAssetData,",
"bytes takerAssetData",
")"
);
return encodedOrder;
}
function abiEncodeTotleOrder(
address exchangeHandler,
bytes memory genericPayload)
public
pure
returns (bytes memory encodedOrder)
{
TotleOrder memory order;
order.exchangeHandler = exchangeHandler;
order.genericPayload = genericPayload;
encodedOrder = abi.encodePacked(
"TotleOrder(",
"address exchangeHandler,",
"bytes genericPayload,",
")"
);
}
function abiEncodePackedTotleOrder(
address exchangeHandler,
bytes memory genericPayload)
public
pure
returns (bytes memory encodedOrder)
{
TotleOrder memory order;
order.exchangeHandler = exchangeHandler;
order.genericPayload = genericPayload;
encodedOrder = abi.encodePacked(
"TotleOrder(",
"address exchangeHandler,",
"bytes genericPayload,",
")"
);
return encodedOrder;
}
// @notice the following two functions require ABIencoderV2, which is not optimized
// @notice switch to ABIencoderV2 results in stack-too-deep error
function abiEncodeTotleTrade(
bool isSell,
address tokenAddress,
uint256 tokenAmount,
bool optionalTrade,
uint256 minimumExchangeRate,
uint256 minimumAcceptableTokenAmount,
TotleOrder[] memory orders)
public
pure
returns (bytes memory encodedOrder)
{
TotleTrade memory order;
order.isSell = isSell;
order.tokenAddress = tokenAddress;
order.tokenAmount = tokenAmount;
order.optionalTrade = optionalTrade;
order.minimumExchangeRate = minimumExchangeRate;
order.minimumAcceptableTokenAmount = minimumAcceptableTokenAmount;
order.orders = orders;
encodedOrder = abi.encodePacked(
"TotleTrade(",
"bool isSell,",
"address tokenAddress,",
"uint256 tokenAmount,",
"bool optionalTrade,",
"uint256 minimumExchangeRate,",
"uint256 minimumAcceptableTokenAmount,",
"TotleOrder[] orders,",
")"
);
return encodedOrder;
}
function abiEncodePackedTotleTrade(
bool isSell,
address tokenAddress,
uint256 tokenAmount,
bool optionalTrade,
uint256 minimumExchangeRate,
uint256 minimumAcceptableTokenAmount,
TotleOrder[] memory orders)
public
pure
returns (bytes memory encodedOrder)
{
TotleTrade memory order;
order.isSell = isSell;
order.tokenAddress = tokenAddress;
order.tokenAmount = tokenAmount;
order.optionalTrade = optionalTrade;
order.minimumExchangeRate = minimumExchangeRate;
order.minimumAcceptableTokenAmount = minimumAcceptableTokenAmount;
order.orders = orders;
encodedOrder = abi.encodePacked(
"TotleTrade(",
"bool isSell,",
"address tokenAddress,",
"uint256 tokenAmount,",
"bool optionalTrade,",
"uint256 minimumExchangeRate,",
"uint256 minimumAcceptableTokenAmount,",
"TotleOrder[] orders,",
")"
);
return encodedOrder;
}
*/
}
|
Gets the Abi encoded bytes array of an integer. orderAmount integer of amount. return Byte array of the ABI encoded struct.
|
function abiEncodeHandlerMockOrder(uint256 orderAmount)
external
pure
returns (bytes memory encodedOrder)
{
HandlerMockOrder memory order;
order.orderAmount = orderAmount;
encodedOrder = abi.encode(order);
return encodedOrder;
}
| 15,867,858 |
pragma solidity ^0.4.23;
contract Ownable {
address public owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() 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 {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
contract Mortal is Ownable{
uint public stopTS;
uint public minimumWait = 1 hours;
bool public killed;
/**
* keep people from joining games or initiating new ones
* */
function stopPlaying() public onlyOwner{
stopTS = now;
}
/**
* kills the contract if enough time has passed. time to pass = twice the waiting time for withdrawal of funds of a running game.
* */
function kill() public onlyOwner{
require(stopTS > 0 && stopTS + 2 * minimumWait <= now, "before killing, playing needs to be stopped and sufficient time has to pass");
selfdestruct(owner);
}
/**
* like killing, because playing will no longer be possible and funds are withdrawn, but keeps the data available on the blockchain
* (especially scores)
* */
function permaStop() public onlyOwner{
require(stopTS > 0 && stopTS + 2 * minimumWait <= now, "before killing, playing needs to be stopped and sufficient time has to pass");
killed = true;
owner.transfer(address(this).balance);
}
/**
* resume playing. stops the killing preparation.
* */
function resumePlaying() public onlyOwner{
require(!killed, "killed contract cannot be reactivated");
stopTS = 0;
}
/**
* don't allow certain functions if playing has been stopped
* */
modifier active(){
require(stopTS == 0, "playing has been stopped by the owner");
_;
}
}
contract Administrable is Mortal{
/** the different pots */
uint public charityPot;
uint public highscorePot;
uint public affiliatePot;
uint public surprisePot;
uint public developerPot;
/** the Percentage of the game stake which go into a pot with one decimal (25 => 2.5%) */
uint public charityPercent = 25;
uint public highscorePercent = 50;
uint public affiliatePercent = 50;
uint public surprisePercent = 25;
uint public developerPercent = 50;
uint public winnerPercent = 800;
/** the current highscore holder **/
address public highscoreHolder;
address public signer;
/** balance of affiliate partners */
mapping (address => uint) public affiliateBalance;
/** tells if a hash has already been used for withdrawal **/
mapping (bytes32 => bool) public used;
event Withdrawal(uint8 pot, address receiver, uint value);
modifier validAddress(address receiver){
require(receiver != 0x0, "invalid receiver");
_;
}
/**
* set the minimum waiting time for withdrawal of funds of a started but not-finished game
* */
function setMinimumWait(uint newMin) public onlyOwner{
minimumWait = newMin;
}
/**
* withdraw from the developer pot
* */
function withdrawDeveloperPot(address receiver) public onlyOwner validAddress(receiver){
uint value = developerPot;
developerPot = 0;
receiver.transfer(value);
emit Withdrawal(0, receiver, value);
}
/**
* withdraw from the charity pot
* */
function donate(address charity) public onlyOwner validAddress(charity){
uint value = charityPot;
charityPot = 0;
charity.transfer(value);
emit Withdrawal(1, charity, value);
}
/**
* withdraw from the highscorePot
* */
function withdrawHighscorePot(address receiver) public validAddress(receiver){
require(msg.sender == highscoreHolder);
uint value = highscorePot;
highscorePot = 0;
receiver.transfer(value);
emit Withdrawal(2, receiver, value);
}
/**
* withdraw from the affiliate pot
* */
function withdrawAffiliateBalance(address receiver) public validAddress(receiver){
uint value = affiliateBalance[msg.sender];
require(value > 0);
affiliateBalance[msg.sender] = 0;
receiver.transfer(value);
emit Withdrawal(3, receiver, value);
}
/**
* withdraw from the surprise pot
* */
function withdrawSurprisePot(address receiver) public onlyOwner validAddress(receiver){
uint value = surprisePot;
surprisePot = 0;
receiver.transfer(value);
emit Withdrawal(4, receiver, value);
}
/**
* allows an user to withdraw from the surprise pot with a valid signature
* */
function withdrawSurprisePotUser(uint value, uint expiry, uint8 v, bytes32 r, bytes32 s) public{
require(expiry >= now, "signature expired");
bytes32 hash = keccak256(abi.encodePacked(msg.sender, value, expiry));
require(!used[hash], "same signature was used before");
require(ecrecover(hash, v, r, s) == signer, "invalid signer");
require(value <= surprisePot, "not enough in the pot");
surprisePot -= value;
used[hash] = true;
msg.sender.transfer(value);
emit Withdrawal(4, msg.sender, value);
}
/**
* sets the signing address
* */
function setSigner(address signingAddress) public onlyOwner{
signer = signingAddress;
}
/**
* sets the pot Percentages
* */
function setPercentages(uint affiliate, uint charity, uint dev, uint highscore, uint surprise) public onlyOwner{
uint sum = affiliate + charity + highscore + surprise + dev;
require(sum < 500, "winner should not lose money");
charityPercent = charity;
affiliatePercent = affiliate;
highscorePercent = highscore;
surprisePercent = surprise;
developerPercent = dev;
winnerPercent = 1000 - sum;
}
}
contract Etherman is Administrable{
struct game{
uint32 timestamp;
uint128 stake;
address player1;
address player2;
}
struct player{
uint8 team;
uint64 score;
address referrer;
}
mapping (bytes32 => game) public games;
mapping (address => player) public players;
event NewGame(bytes32 gameId, address player1, uint stake);
event GameStarted(bytes32 gameId, address player1, address player2, uint stake);
event GameDestroyed(bytes32 gameId);
event GameEnd(bytes32 gameId, address winner, uint value);
event NewHighscore(address holder, uint score, uint lastPot);
modifier onlyHuman(){
require(msg.sender == tx.origin, "contract calling");
_;
}
constructor(address signingAddress) public{
setSigner(signingAddress);
}
/**
* sets the referrer for the lifetime affiliate program and initiates a new game
* */
function initGameReferred(address referrer, uint8 team) public payable active onlyHuman validAddress(referrer){
//new player which does not have a referrer set yet
if(players[msg.sender].referrer == 0x0 && players[msg.sender].score == 0)
players[msg.sender] = player(team, 0, referrer);
initGame();
}
/**
* sets the team and initiates a game
* */
function initGameTeam(uint8 team) public payable active onlyHuman{
if(players[msg.sender].score == 0)
players[msg.sender].team = team;
initGame();
}
/**
* initiates a new game
* */
function initGame() public payable active onlyHuman{
require(msg.value <= 10 ether, "stake needs to be lower than or equal to 10 ether");
require(msg.value > 1 finney, "stake needs to be at least 1 finney");
bytes32 gameId = keccak256(abi.encodePacked(msg.sender, block.number));
games[gameId] = game(uint32(now), uint128(msg.value), msg.sender, 0x0);
emit NewGame(gameId, msg.sender, msg.value);
}
/**
* sets the referrer for the lifetime affiliate program and joins a game
* */
function joinGameReferred(bytes32 gameId, address referrer, uint8 team) public payable active onlyHuman validAddress(referrer){
//new player which does not have a referrer set yet
if(players[msg.sender].referrer == 0x0 && players[msg.sender].score == 0)
players[msg.sender] = player(team, 0, referrer);
joinGame(gameId);
}
/**
* sets the team and joins a game
* */
function joinGameTeam(bytes32 gameId, uint8 team) public payable active onlyHuman{
if(players[msg.sender].score == 0)
players[msg.sender].team = team;
joinGame(gameId);
}
/**
* join a game
* */
function joinGame(bytes32 gameId) public payable active onlyHuman{
game storage cGame = games[gameId];
require(cGame.player1!=0x0, "game id unknown");
require(cGame.player1 != msg.sender, "cannot play with one self");
require(msg.value >= cGame.stake, "value does not suffice to join the game");
cGame.player2 = msg.sender;
cGame.timestamp = uint32(now);
emit GameStarted(gameId, cGame.player1, msg.sender, cGame.stake);
if(msg.value > cGame.stake) developerPot += msg.value - cGame.stake;
}
/**
* withdraw from the game stake in case no second player joined or the game was not ended within the
* minimum waiting time
* */
function withdraw(bytes32 gameId) public onlyHuman{
game storage cGame = games[gameId];
uint128 value = cGame.stake;
if(msg.sender == cGame.player1){
if(cGame.player2 == 0x0){
delete games[gameId];
msg.sender.transfer(value);
}
else if(cGame.timestamp + minimumWait <= now){
address player2 = cGame.player2;
delete games[gameId];
msg.sender.transfer(value);
player2.transfer(value);
}
else{
revert("minimum waiting time has not yet passed");
}
}
else if(msg.sender == cGame.player2){
if(cGame.timestamp + minimumWait <= now){
address player1 = cGame.player1;
delete games[gameId];
msg.sender.transfer(value);
player1.transfer(value);
}
else{
revert("minimum waiting time has not yet passed");
}
}
else{
revert("sender is not a player in this game");
}
emit GameDestroyed(gameId);
}
/**
* The winner can claim his winnings, only with a signature from the contract owner.
* the pot is distributed amongst the winner, the developers, the affiliate partner, a charity and the surprise pot
* */
function claimWin(bytes32 gameId, uint8 v, bytes32 r, bytes32 s) public onlyHuman{
game storage cGame = games[gameId];
require(cGame.player2!=0x0, "game has not started yet");
require(msg.sender == cGame.player1 || msg.sender == cGame.player2, "sender is not a player in this game");
require(ecrecover(keccak256(abi.encodePacked(gameId, msg.sender)), v, r, s) == signer, "invalid signature");
uint256 value = 2*cGame.stake;
uint256 win = winnerPercent * value / 1000;
addScore(msg.sender, cGame.stake);
delete games[gameId];
charityPot += value * charityPercent / 1000;
//players of the leading team do not pay tributes
if(players[highscoreHolder].team == players[msg.sender].team){
win += value * highscorePercent / 1000;
}
else{
highscorePot += value * highscorePercent / 1000;
}
surprisePot += value * surprisePercent / 1000;
if(players[msg.sender].referrer == 0x0){
developerPot += value * (developerPercent + affiliatePercent) / 1000;
}
else{
developerPot += value * developerPercent / 1000;
affiliateBalance[players[msg.sender].referrer] += value * affiliatePercent / 1000;
}
msg.sender.transfer(win);//no overflow possible because stake is <= max uint128, but now we have 256 bit
emit GameEnd(gameId, msg.sender, win);
}
function addScore(address receiver, uint stake) private{
player storage rec = players[receiver];
player storage hsh = players[highscoreHolder];
if(rec.team == hsh.team){
if(stake < 0.05 ether) rec.score += 1;
else if(stake < 0.5 ether) rec.score += 5;
else rec.score += 10;
}
else{//extra points if not belonging to the highscore team
if(stake < 0.05 ether) rec.score += 2;
else if(stake < 0.5 ether) rec.score += 7;
else rec.score += 13;
}
if(rec.score > hsh.score){
uint pot = highscorePot;
if(pot > 0){
highscorePot = 0;
highscoreHolder.transfer(pot);
}
highscoreHolder = receiver;
emit NewHighscore(receiver, rec.score, pot);
}
}
/**
* any directly sent ETH are considered a donation for development
* */
function() public payable{
developerPot+=msg.value;
}
function doNothing(){
}
}
|
like killing, because playing will no longer be possible and funds are withdrawn, but keeps the data available on the blockchain (especially scores) /
|
function permaStop() public onlyOwner{
require(stopTS > 0 && stopTS + 2 * minimumWait <= now, "before killing, playing needs to be stopped and sufficient time has to pass");
killed = true;
owner.transfer(address(this).balance);
}
| 2,576,958 |
./full_match/3/0xaE6B632dDbAe12F2edfb846bd7622ABD698e6a9D/sources/contracts/Relayer.sol
|
IRelayer.bindingWorker/
|
function bindingWorker(uint256 _chainId, bytes32 _worker)
external
override
onlyRelayer
{
require(
bindRelayer[_worker][_chainId] == address(0),
"Relayer: worker already binded"
);
_setBindAddress(msg.sender, _worker, _chainId);
emit WorkerSet(msg.sender, _chainId, _worker);
}
| 14,135,355 |
//pragma solidity 0.4.1;
import {RequestFactoryInterface} from "contracts/RequestFactoryInterface.sol";
import {TransactionRequest} from "contracts/TransactionRequest.sol";
import {RequestLib} from "contracts/RequestLib.sol";
import {SafeSendLib} from "contracts/SafeSendLib.sol";
import {IterTools} from "contracts/IterTools.sol";
import {RequestTrackerInterface} from "contracts/RequestTrackerInterface.sol";
contract RequestFactory is RequestFactoryInterface {
using IterTools for bool[7];
using SafeSendLib for address;
RequestTrackerInterface public requestTracker;
function RequestFactory(address _trackerAddress) {
if (_trackerAddress == 0x0) throw;
requestTracker = RequestTrackerInterface(_trackerAddress);
}
/*
* The lowest level interface for creating a transaction request.
*
* addressArgs[1] - meta.owner
* addressArgs[1] - paymentData.donationBenefactor
* addressArgs[2] - txnData.toAddress
* uintArgs[0] - paymentData.donation
* uintArgs[1] - paymentData.payment
* uintArgs[2] - schedule.claimWindowSize
* uintArgs[3] - schedule.freezePeriod
* uintArgs[4] - schedule.reservedWindowSize
* uintArgs[5] - schedule.temporalUnit
* uintArgs[6] - schedule.windowSize
* uintArgs[7] - schedule.windowStart
* uintArgs[8] - txnData.callGas
* uintArgs[9] - txnData.callValue
* uintArgs[10] - txnData.requiredStackDepth
*/
function createRequest(address[3] addressArgs,
uint[11] uintArgs,
bytes callData) returns (address) {
var request = (new TransactionRequest).value(msg.value)(
[
msg.sender,
addressArgs[0], // meta.owner
addressArgs[1], // paymentData.donationBenefactor
addressArgs[2] // txnData.toAddress
],
uintArgs,
callData
);
// Track the address locally
requests[address(request)] = true;
// Log the creation.
RequestCreated(address(request));
// Add the request to the RequestTracker
requestTracker.addRequest(address(request), uintArgs[7]);
return request;
}
/*
* ValidationError
*/
enum Errors {
InsufficientEndowment,
ReservedWindowBiggerThanExecutionWindow,
InvalidTemporalUnit,
ExecutionWindowTooSoon,
InvalidRequiredStackDepth,
CallGasTooHigh,
EmptyToAddress
}
event ValidationError(uint8 error);
/*
* Validate the constructor arguments for either `createRequest` or
* `createValidatedRequest`
*/
function validateRequestParams(address[3] addressArgs,
uint[11] uintArgs,
bytes callData,
uint endowment) returns (bool[7]) {
return RequestLib.validate(
[
msg.sender, // meta.createdBy
addressArgs[0], // meta.owner
addressArgs[1], // paymentData.donationBenefactor
addressArgs[2] // txnData.toAddress
],
uintArgs,
callData,
endowment
);
}
/*
* The same as createRequest except that it requires validation prior to
* creation.
*
* Parameters are the same as `createRequest`
*/
function createValidatedRequest(address[3] addressArgs,
uint[11] uintArgs,
bytes callData) returns (address) {
var is_valid = validateRequestParams(addressArgs,
uintArgs,
callData,
msg.value);
if (!is_valid.all()) {
if (!is_valid[0]) ValidationError(uint8(Errors.InsufficientEndowment));
if (!is_valid[1]) ValidationError(uint8(Errors.ReservedWindowBiggerThanExecutionWindow));
if (!is_valid[2]) ValidationError(uint8(Errors.InvalidTemporalUnit));
if (!is_valid[3]) ValidationError(uint8(Errors.ExecutionWindowTooSoon));
if (!is_valid[4]) ValidationError(uint8(Errors.InvalidRequiredStackDepth));
if (!is_valid[5]) ValidationError(uint8(Errors.CallGasTooHigh));
if (!is_valid[6]) ValidationError(uint8(Errors.EmptyToAddress));
// Try to return the ether sent with the message. If this failed
// then throw to force it to be returned.
if (msg.sender.sendOrThrow(msg.value)) {
return 0x0;
}
throw;
}
return createRequest(addressArgs, uintArgs, callData);
}
mapping (address => bool) requests;
function isKnownRequest(address _address) returns (bool) {
// TODO: decide whether this should be a local mapping or from tracker.
return requests[_address];
}
}
contract TestnetRequestFactory is RequestFactory(0x8e67d439713b2022cac2ff4ebca21e173ccba4a0) {
}
|
TODO: decide whether this should be a local mapping or from tracker.
|
function isKnownRequest(address _address) returns (bool) {
return requests[_address];
}
| 13,102,866 |
pragma solidity ^0.4.15;
import './zeppelin/ownership/Ownable.sol';
contract StarMarket is Ownable {
// You can use this hash to verify the csv file containing all the stars
string public csvHash = "039fdcdcfc31968c6938863ac1d293854ba810bbfa0bcd72b1f4cc2d544f3d08";
address owner;
string public standard = 'Stars';
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
uint256 public claimFee;
uint8 public transactionFeePercentage;
uint public nextStarIndexToAssign = 0; // TODO: unused, remove?
bool public allStarsAssigned = false;
bool public canClaimStars = false;
uint public starsRemainingToAssign = 0;
//mapping (address => uint) public addressToStarIndex;
mapping (uint => address) public starIndexToAddress;
/* This creates an array with all balances */
mapping (address => uint256) public balanceOf;
struct Offer {
bool isForSale;
uint starIndex;
address seller;
uint minValue; // in ether
address onlySellTo; // specify to sell only to a specific person
}
struct Bid {
bool hasBid;
uint starIndex;
address bidder;
uint value;
}
// A record of stars that are offered for sale at a specific minimum value, and perhaps to a specific person
mapping (uint => Offer) public starsOfferedForSale;
// A record of the highest star bid
mapping (uint => Bid) public starBids;
mapping (address => uint) public pendingWithdrawals;
event Assign(address indexed to, uint256 starIndex);
event Transfer(address indexed from, address indexed to, uint256 value);
event StarTransfer(address indexed from, address indexed to, uint256 starIndex);
event StarOffered(uint indexed starIndex, uint minValue, address indexed toAddress);
event StarBidEntered(uint indexed starIndex, uint value, address indexed fromAddress);
event StarBidWithdrawn(uint indexed starIndex, uint value, address indexed fromAddress);
event StarBought(uint indexed starIndex, uint value, address indexed fromAddress, address indexed toAddress, uint256 transactionFee);
event StarNoLongerForSale(uint indexed starIndex);
event ClaimFeeUpdated(uint256 indexed newClaimFee);
event TransactionFeePercentageUpdated(uint8 indexed newTransactionFeePercentage);
/* Initializes contract with initial supply tokens to the creator of the contract */
function StarMarket() payable {
// balanceOf[msg.sender] = initialSupply; // Give the creator all initial tokens
owner = msg.sender;
totalSupply = 119615; // Update total supply
starsRemainingToAssign = totalSupply;
name = "STARS"; // Set the name for display purposes
symbol = "★"; // Set the symbol for display purposes
decimals = 0; // Amount of decimals for display purposes
claimFee = 15000000000000000; // Price of claiming a star
transactionFeePercentage = 5; // Whole number percentage (0-100)
}
function setInitialOwner(address to, uint starIndex, uint initialOffer) onlyOwner {
if (allStarsAssigned && !canClaimStars) revert();
if (starIndex >= totalSupply) revert();
if (starIndexToAddress[starIndex] != to) {
if (starIndexToAddress[starIndex] != 0x0) {
balanceOf[starIndexToAddress[starIndex]]--;
} else {
starsRemainingToAssign--;
}
starIndexToAddress[starIndex] = to;
balanceOf[to]++;
if (initialOffer > 0) {
offerStarForSale(starIndex, initialOffer);
}
Assign(to, starIndex);
}
}
function setInitialOwners(address[] addresses, uint[] indices, uint[] initialOffers) onlyOwner {
uint n = addresses.length;
for (uint i = 0; i < n; i++) {
setInitialOwner(addresses[i], indices[i], initialOffers[i]);
}
}
function allInitialOwnersAssigned() onlyOwner {
allStarsAssigned = true;
canClaimStars = true;
}
function updateCSV(string newHash, uint256 newTotalSupply) onlyOwner {
if (newTotalSupply < totalSupply) revert(); // We should only be able to add stars to the db
csvHash = newHash;
if (totalSupply != newTotalSupply) {
starsRemainingToAssign = newTotalSupply - totalSupply;
canClaimStars = true;
totalSupply = newTotalSupply;
}
}
function updateClaimFee(uint256 newClaimFee) onlyOwner {
claimFee = newClaimFee;
ClaimFeeUpdated(newClaimFee);
}
function updateTransactionFeePercentage(uint8 newTransactionFeePercentage) onlyOwner {
if (newTransactionFeePercentage > 5) revert(); // Prevent the fee from ever being more than 5%
if (newTransactionFeePercentage < 0) revert();
transactionFeePercentage = newTransactionFeePercentage;
TransactionFeePercentageUpdated(newTransactionFeePercentage);
}
function getStar(uint starIndex) payable {
if (!allStarsAssigned && !canClaimStars) revert();
if (starsRemainingToAssign == 0) revert();
if (starIndexToAddress[starIndex] != 0x0) revert();
if (starIndex >= totalSupply) revert();
if (msg.value < claimFee) revert();
pendingWithdrawals[owner] += msg.value;
starIndexToAddress[starIndex] = msg.sender;
balanceOf[msg.sender]++;
starsRemainingToAssign--;
if (starsRemainingToAssign == 0) {
canClaimStars = false;
}
Assign(msg.sender, starIndex);
}
// Transfer ownership of a star to another user without requiring payment
function transferStar(address to, uint starIndex) {
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
if (starIndex >= totalSupply) revert();
if (starsOfferedForSale[starIndex].isForSale) {
starNoLongerForSale(starIndex);
}
starIndexToAddress[starIndex] = to;
balanceOf[msg.sender]--;
balanceOf[to]++;
Transfer(msg.sender, to, 1);
StarTransfer(msg.sender, to, starIndex);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid storage bid = starBids[starIndex];
if (bid.bidder == to) {
// Kill bid and refund value
pendingWithdrawals[to] += bid.value;
starBids[starIndex] = Bid(false, starIndex, 0x0, 0);
}
}
function starNoLongerForSale(uint starIndex) {
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
if (starIndex >= totalSupply) revert();
starsOfferedForSale[starIndex] = Offer(false, starIndex, msg.sender, 0, 0x0);
StarNoLongerForSale(starIndex);
}
function offerStarForSale(uint starIndex, uint minSalePriceInWei) {
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
if (starIndex >= totalSupply) revert();
starsOfferedForSale[starIndex] = Offer(true, starIndex, msg.sender, minSalePriceInWei, 0x0);
StarOffered(starIndex, minSalePriceInWei, 0x0);
}
function offerStarForSaleToAddress(uint starIndex, uint minSalePriceInWei, address toAddress) {
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
if (starIndex >= totalSupply) revert();
starsOfferedForSale[starIndex] = Offer(true, starIndex, msg.sender, minSalePriceInWei, toAddress);
StarOffered(starIndex, minSalePriceInWei, toAddress);
}
function buyStar(uint starIndex) payable {
if (!allStarsAssigned) revert();
Offer storage offer = starsOfferedForSale[starIndex];
if (starIndex >= totalSupply) revert();
if (!offer.isForSale) revert(); // star not actually for sale
if (offer.onlySellTo != 0x0 && offer.onlySellTo != msg.sender) revert(); // star not supposed to be sold to this user
if (msg.value < offer.minValue) revert(); // Didn't send enough ETH
if (offer.seller != starIndexToAddress[starIndex]) revert(); // Seller no longer owner of star
address seller = offer.seller;
starIndexToAddress[starIndex] = msg.sender;
balanceOf[seller]--;
balanceOf[msg.sender]++;
Transfer(seller, msg.sender, 1);
starNoLongerForSale(starIndex);
uint256 transactionFee = msg.value * (transactionFeePercentage / 100);
uint256 toSeller = msg.value - transactionFee;
pendingWithdrawals[owner] += transactionFee;
pendingWithdrawals[seller] += toSeller;
StarBought(starIndex, msg.value, seller, msg.sender, transactionFee);
// Check for the case where there is a bid from the new owner and refund it.
// Any other bid can stay in place.
Bid storage bid = starBids[starIndex];
if (bid.bidder == msg.sender) {
// Kill bid and refund value
pendingWithdrawals[msg.sender] += bid.value;
starBids[starIndex] = Bid(false, starIndex, 0x0, 0);
}
}
function withdraw() {
if (!allStarsAssigned) revert();
uint amount = pendingWithdrawals[msg.sender];
// Remember to zero the pending refund before
// sending to prevent re-entrancy attacks
pendingWithdrawals[msg.sender] = 0;
msg.sender.transfer(amount);
}
function enterBidForStar(uint starIndex) payable {
if (starIndex >= totalSupply) revert();
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] == 0x0) revert();
if (starIndexToAddress[starIndex] == msg.sender) revert();
if (msg.value == 0) revert();
Bid storage existing = starBids[starIndex];
if (msg.value <= existing.value) revert();
if (existing.value > 0) {
// Refund the failing bid
pendingWithdrawals[existing.bidder] += existing.value;
}
starBids[starIndex] = Bid(true, starIndex, msg.sender, msg.value);
StarBidEntered(starIndex, msg.value, msg.sender);
}
function acceptBidForStar(uint starIndex, uint minPrice) {
if (starIndex >= totalSupply) revert();
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
address seller = msg.sender;
Bid storage bid = starBids[starIndex];
if (bid.value == 0) revert();
if (bid.value < minPrice) revert();
starIndexToAddress[starIndex] = bid.bidder;
balanceOf[seller]--;
balanceOf[bid.bidder]++;
Transfer(seller, bid.bidder, 1);
starsOfferedForSale[starIndex] = Offer(false, starIndex, bid.bidder, 0, 0x0);
uint256 transactionFee = bid.value * (transactionFeePercentage / 100);
uint256 toSeller = bid.value - transactionFee;
starBids[starIndex] = Bid(false, starIndex, 0x0, 0);
pendingWithdrawals[owner] += transactionFee;
pendingWithdrawals[seller] += toSeller;
StarBought(starIndex, bid.value, seller, bid.bidder, transactionFee);
}
function withdrawBidForStar(uint starIndex) {
if (starIndex >= totalSupply) revert();
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] == 0x0) revert();
if (starIndexToAddress[starIndex] == msg.sender) revert();
Bid storage bid = starBids[starIndex];
if (bid.bidder != msg.sender) revert();
StarBidWithdrawn(starIndex, bid.value, msg.sender);
uint amount = bid.value;
starBids[starIndex] = Bid(false, starIndex, 0x0, 0);
// Refund the bid money
msg.sender.transfer(amount);
}
}
|
Transfer ownership of a star to another user without requiring payment Kill bid and refund value
|
function transferStar(address to, uint starIndex) {
if (!allStarsAssigned) revert();
if (starIndexToAddress[starIndex] != msg.sender) revert();
if (starIndex >= totalSupply) revert();
if (starsOfferedForSale[starIndex].isForSale) {
starNoLongerForSale(starIndex);
}
starIndexToAddress[starIndex] = to;
balanceOf[msg.sender]--;
balanceOf[to]++;
Transfer(msg.sender, to, 1);
StarTransfer(msg.sender, to, starIndex);
if (bid.bidder == to) {
pendingWithdrawals[to] += bid.value;
starBids[starIndex] = Bid(false, starIndex, 0x0, 0);
}
}
| 13,114,085 |
./full_match/80001/0x18cE94D4b70dd064532127275dBf02A7Bf9f5B8C/sources/contracts/Tasks/TasksUtils.sol
|
From: https:github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/proxy/Clones.sol @solidity memory-safe-assembly Cleans the upper 96 bits of the `implementation` word, then packs the first 3 bytes of the `implementation` address with the bytecode before the address. Packs the remaining 17 bytes of `implementation` with the bytecode after the address.
|
function clone(address implementation) internal returns (address instance) {
assembly {
mstore(
0x00,
or(
shr(0xe8, shl(0x60, implementation)),
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000
)
)
mstore(
0x20,
or(shl(0x78, implementation), 0x5af43d82803e903d91602b57fd5bf3)
)
instance := create(0, 0x09, 0x37)
}
if (instance == address(0)) {
revert ERC1167FailedCreateClone();
}
}
| 844,135 |
pragma solidity ^0.5.0;
/**------------------------------------
LAVA Token (0xBTC Token Proxy with Lava Enabled)
0xBTC proxy token contract. ApproveAndCall() 0xBTC to this contract to receive LAVA tokens. Alternatively, Approve() 0xBTC to this contract and then call the mutateTokens() method. Do not directly transfer 0xBTC to this contract using Transfer() or TransferFrom().
LAVA tokens can be spent not just by your account, but by any account as long as they have a lava packet signature, signed by your private key, which validates that specific transaction.
A relayer reward can be specified in a signed packet. This means that LAVA can be sent by paying an incentive fee of LAVA to relayers for the gas, not ETH.
LAVA is 1:1 pegged to 0xBTC.
This contract implements EIP712 for Signing Typed Data:
https://github.com/MetaMask/eth-sig-util
------------------------------------*/
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract 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 memory 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
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 {
return ecrecover(hash, v, r, s);
}
}
}
contract RelayAuthorityInterface {
function getRelayAuthority() public returns (address);
}
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public;
}
contract LavaToken is ECRecovery{
using SafeMath for uint;
address constant public masterToken = 0xB6eD7644C69416d67B522e20bC294A9a9B405B31;
string public name = "Lava";
string public symbol = "LAVA";
uint8 public decimals = 8;
uint private _totalSupply;
event Approval(address indexed src, address indexed ext, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
event Deposit(address indexed dst, uint amt);
event Withdrawal(address indexed src, uint amt);
mapping (address => uint) public balances;
mapping (address => mapping (address => uint)) public allowance;
mapping (bytes32 => uint256) public burnedSignatures;
struct LavaPacket {
string methodName; //approve, transfer, or a custom data byte32 for ApproveAndCall()
address relayAuthority; //either a contract or an account
address from; //the packet origin and signer
address to; //the recipient of tokens
address wallet; //this contract address
uint256 tokens; //the amount of tokens to give to the recipient
uint256 relayerRewardTokens; //the amount of tokens to give to msg.sender
uint256 expires; //the eth block number this packet expires at
uint256 nonce; //a random number to ensure that packet hashes are always unique (optional)
}
bytes32 constant LAVAPACKET_TYPEHASH = keccak256(
"LavaPacket(string methodName,address relayAuthority,address from,address to,address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce)"
);
function getLavaPacketTypehash() public pure returns (bytes32) {
return LAVAPACKET_TYPEHASH;
}
function getLavaPacketHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
return keccak256(abi.encode(
LAVAPACKET_TYPEHASH,
keccak256(bytes(methodName)),
relayAuthority,
from,
to,
wallet,
tokens,
relayerRewardTokens,
expires,
nonce
));
}
constructor() public {
}
/**
* Do not allow ETH to enter
*/
function() external payable
{
revert();
}
/**
* @dev Deposit original tokens, receive proxy tokens 1:1
* This method requires token approval.
*
* @param amount of tokens to deposit
*/
function mutateTokens(address from, uint amount) public returns (bool)
{
require( amount >= 0 );
require( ERC20Interface( masterToken ).transferFrom( from, address(this), amount) );
balances[from] = balances[from].add(amount);
_totalSupply = _totalSupply.add(amount);
emit Transfer(address(0), from, amount);
return true;
}
/**
* @dev Withdraw original tokens, burn proxy tokens 1:1
*
*
*
* @param amount of tokens to withdraw
*/
function unmutateTokens( uint amount) public returns (bool)
{
address from = msg.sender;
require( amount >= 0 );
balances[from] = balances[from].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(from, address(0), amount);
require( ERC20Interface( masterToken ).transfer( from, amount) );
return true;
}
//standard ERC20 method
function totalSupply() public view returns (uint) {
return _totalSupply;
}
//standard ERC20 method
function balanceOf(address tokenOwner) public view returns (uint balance) {
return balances[tokenOwner];
}
//standard ERC20 method
function getAllowance(address owner, address spender) public view returns (uint)
{
return allowance[owner][spender];
}
//standard ERC20 method
function approve(address spender, uint tokens) public returns (bool success) {
allowance[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
//standard ERC20 method
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer(msg.sender, to, tokens);
return true;
}
//standard ERC20 method
function transferFrom( address from, address to, uint tokens) public returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowance[from][to] = allowance[from][to].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
//internal method for transferring tokens to the relayer reward as incentive for submitting the packet
function _giveRelayerReward( address from, address to, uint tokens) internal returns (bool success){
balances[from] = balances[from].sub(tokens);
balances[to] = balances[to].add(tokens);
emit Transfer( from, to, tokens);
return true;
}
/*
Read-only method that returns the EIP712 message structure to be signed for a lava packet.
*/
function getLavaTypedDataHash(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce) public pure returns (bytes32) {
// Note: we need to use `encodePacked` here instead of `encode`.
bytes32 digest = keccak256(abi.encodePacked(
"\x19\x01",
// DOMAIN_SEPARATOR,
getLavaPacketHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce)
));
return digest;
}
/*
The internal method for processing the internal data structure of an offchain lava packet with signature.
*/
function _tokenApprovalWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes32 sigHash, bytes memory signature) internal returns (bool success)
{
/*
Always allow relaying a packet if the specified relayAuthority is 0.
If the authority address is not a contract, allow it to relay
If the authority address is a contract, allow its defined 'getAuthority()' delegate to relay
*/
require( relayAuthority == address(0x0)
|| (!addressContainsContract(relayAuthority) && msg.sender == relayAuthority)
|| (addressContainsContract(relayAuthority) && msg.sender == RelayAuthorityInterface(relayAuthority).getRelayAuthority()) );
address recoveredSignatureSigner = recover(sigHash,signature);
//make sure the signer is the depositor of the tokens
require(from == recoveredSignatureSigner);
//make sure this is the correct 'wallet' for this packet
require(address(this) == wallet);
//make sure the signature has not expired
require(block.number < expires);
uint previousBurnedSignatureValue = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x1; //spent
require(previousBurnedSignatureValue == 0x0);
//relayer reward tokens, has nothing to do with allowance
require(_giveRelayerReward(from, msg.sender, relayerRewardTokens));
//approve transfer of tokens
allowance[from][to] = tokens;
emit Approval(from, to, tokens);
return true;
}
function approveTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('approve',bytes(methodName)));
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
return true;
}
function transferTokensWithSignature(string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
require(bytesEqual('transfer',bytes(methodName)));
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
//it can be requested that fewer tokens be sent that were approved -- the whole approval will be invalidated though
require(transferFrom( from, to, tokens));
return true;
}
/*
Approve LAVA tokens for a smart contract and call the contracts receiveApproval method in a single packet transaction.
Uses the methodName as the 'bytes' for the fallback function to the remote contract
*/
function approveAndCallWithSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature ) public returns (bool success) {
require(!bytesEqual('approve',bytes(methodName)) && !bytesEqual('transfer',bytes(methodName)));
//check to make sure that signature == ecrecover signature
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
require(_tokenApprovalWithSignature(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce,sigHash,signature));
_sendApproveAndCall(from,to,tokens,bytes(methodName));
return true;
}
function _sendApproveAndCall(address from, address to, uint tokens, bytes memory methodName) internal
{
ApproveAndCallFallBack(to).receiveApproval(from, tokens, address(this), bytes(methodName));
}
/*
Burn the signature of an off-chain transaction packet so that it cannot be used on-chain.
Only the creator of the packet can call this method as msg.sender.
*/
function burnSignature( string memory methodName, address relayAuthority,address from,address to, address wallet,uint256 tokens,uint256 relayerRewardTokens,uint256 expires,uint256 nonce, bytes memory signature) public returns (bool success)
{
bytes32 sigHash = getLavaTypedDataHash(methodName,relayAuthority,from,to,wallet,tokens,relayerRewardTokens,expires,nonce);
address recoveredSignatureSigner = recover(sigHash,signature);
//make sure the invalidator is the signer
require(recoveredSignatureSigner == from);
//only the original packet owner can burn signature, not a relay
require(from == msg.sender);
//make sure this signature has never been used
uint burnedSignature = burnedSignatures[sigHash];
burnedSignatures[sigHash] = 0x2; //invalidated
require(burnedSignature == 0x0);
return true;
}
/*
Check the burn status of the SHA3 hash of a packet signature.
Signatures are burned whenever they are used for a transaction or whenever the burnSignature() method is called.
*/
function signatureHashBurnStatus(bytes32 digest) public view returns (uint)
{
return (burnedSignatures[digest]);
}
/*
Receive approval from ApproveAndCall() to mutate tokens.
This method allows 0xBTC to be mutated into LAVA using a single method call.
*/
function receiveApproval(address from, uint256 tokens, address token, bytes memory data) public returns (bool success) {
require(token == masterToken);
require(mutateTokens(from, tokens));
return true;
}
function addressContainsContract(address _to) view internal returns (bool)
{
uint codeLength;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
return (codeLength>0);
}
function bytesEqual(bytes memory b1,bytes memory b2) pure internal returns (bool)
{
if(b1.length != b2.length) return false;
for (uint i=0; i<b1.length; i++) {
if(b1[i] != b2[i]) return false;
}
return true;
}
}
|
Retrieve the size of the code on target address, this needs assembly .
|
function addressContainsContract(address _to) view internal returns (bool)
{
uint codeLength;
assembly {
codeLength := extcodesize(_to)
}
return (codeLength>0);
}
| 1,830,933 |
pragma solidity ^0.4.25;
import "./Traceability.sol";
contract TraceabilityFactory{
struct GoodsTrace{
Traceability trace;
bool valid;
}
mapping(bytes32=>GoodsTrace) private _goodsCategory;
event newTraceEvent(bytes32 goodsGroup);
//Create traceability commodity category
function createTraceability(bytes32 goodsGroup)public returns(Traceability) {
require(!_goodsCategory[goodsGroup].valid,"The trademark already exists" );
Traceability category = new Traceability(goodsGroup);
_goodsCategory[goodsGroup].valid = true;
_goodsCategory[goodsGroup].trace = category;
emit newTraceEvent(goodsGroup);
return category;
}
function getTraceability(bytes32 goodsGroup)private view returns(Traceability) {
require(_goodsCategory[goodsGroup].valid,"The trademark has not exists" );
return _goodsCategory[goodsGroup].trace;
}
//Create traceability products
function createTraceGoods(bytes32 goodsGroup, uint64 goodsId)public returns(Goods) {
Traceability category = getTraceability(goodsGroup);
return category.createGoods(goodsId);
}
//Change product status
function changeTraceGoods(bytes32 goodsGroup, uint64 goodsId, int16 goodsStatus, string memory remark)public{
Traceability category = getTraceability(goodsGroup);
category.changeGoodsStatus(goodsId, goodsStatus, remark);
}
//Query the current status of goods
function getStatus(bytes32 goodsGroup, uint64 goodsId)public view returns(int16){
Traceability category = getTraceability(goodsGroup);
return category.getStatus(goodsId);
}
//The whole process of querying goods
function getTraceInfo(bytes32 goodsGroup, uint64 goodsId)public view returns(Goods){
Traceability category = getTraceability(goodsGroup);
return category.getGoods(goodsId);
}
}
|
Create traceability commodity category
|
function createTraceability(bytes32 goodsGroup)public returns(Traceability) {
require(!_goodsCategory[goodsGroup].valid,"The trademark already exists" );
Traceability category = new Traceability(goodsGroup);
_goodsCategory[goodsGroup].valid = true;
_goodsCategory[goodsGroup].trace = category;
emit newTraceEvent(goodsGroup);
return category;
}
| 1,799,871 |
pragma solidity ^0.4.24;
/*
******************** https://doubledivs.cash/exchange/ *********************
*
* _______ ______ __ __ .______ __ _______
* | \ / __ \ | | | | | _ \ | | | ____|
* | .--. | | | | | | | | | |_) | | | | |__
* | | | | | | | | | | | | _ < | | | __|
* | '--' | `--' | | `--' | | |_) | | `----.| |____
* |_______/ \______/ \______/ |______/ |_______||_______|
* _______ __ ____ ____ _______.
* | \ | | \ \ / / / |
* | .--. || | \ \/ / | (----`
* | | | || | \ / \ \
* | '--' || | \ / .----) |
* |_______/ |__| \__/ |_______/
* __________ ___ ______ __ __ ___ .__ __. _______ _______
* | ____\ \ / / / || | | | / \ | \ | | / _____|| ____|
* | |__ \ V / | ,----'| |__| | / ^ \ | \| | | | __ | |__
* | __| > < | | | __ | / /_\ \ | . ` | | | |_ | | __|
* | |____ / . \ | `----.| | | | / _____ \ | |\ | | |__| | | |____
* |_______/__/ \__\ \______||__| |__| /__/ \__\ |__| \__| \______| |_______|
*
* DOUBLEDIVS 50% DIVIDENDS. FOREVER.
*
* https://doubledivs.cash/
* https://doubledivs.cash/exchange/
*
******************** https://doubledivs.cash/exchange/ *********************
*
*
* [x] 25% Exchange fee (Split to Token Divs + Double Divs + Referral)
* [x] 18% Dividends to all DDIVS holders
* [x] 5% Dividends to Double Divs
* [x] 0% Account transfer fees
* [x] 2% To Dev Fund for future development costs
* [x] Double Divs Dividend Account: 0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433
* [x] Multi-tier Masternode system for exchange buys and sells (3 levels)
* [x] Refferal approximate % breakdown (4% for 1st, 2.4% for 2nd, 1.6% 3rd)
* [x] Double Divs (DDIVS) Token can be used for future games
*
* Official Website: https://doubledivs.cash/
* Official Exchange: https://doubledivs.cash/exchange
* Official Discord: https://discord.gg/YRTWtJ6
* Official Twitter: https://twitter.com/DoubleDivs
* Official Telegram: https://t.me/DoubleDivs
*/
/**
* Definition of contract accepting Double Divs (DDIVS) tokens
* Games or any other innovative platforms can reuse this contract to support Double Divs (DDIVS) tokens
*/
contract AcceptsDDIVS {
DDIVS public tokenContract;
constructor(address _tokenContract) public {
tokenContract = DDIVS(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
}
contract DDIVS {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
uint ACTIVATION_TIME = 1538028000;
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
if (now >= ACTIVATION_TIME) {
onlyAmbassadors = false;
}
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "DDIVS";
string public symbol = "DDIVS";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 18; // 18% dividend fee for double divs tokens on each buy and sell
uint8 constant internal fundFee_ = 7; // 7% investment fund fee to buy double divs on each buy and sell
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// Address to send the 1% Fee
address public giveEthFundAddress = 0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433;
bool public finalizedEthFundAddress = false;
uint256 public totalEthFundRecieved; // total ETH charity recieved from this contract
uint256 public totalEthFundCollected; // total ETH charity collected in this contract
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 25e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 0.75 ether;
uint256 constant internal ambassadorQuota_ = 1.5 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
// Special Double Divs Platform control from scam game contracts on Double Divs platform
mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Double Divs tokens
mapping(address => address) public stickyRef;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
constructor()
public
{
// add administrators here
administrators[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true;
// add the ambassadors here - Tokens will be distributed to these addresses from main premine
ambassadors_[0x41FE3738B503cBaFD01C1Fd8DD66b7fE6Ec11b01] = true;
// add the ambassadors here - Tokens will be distributed to these addresses from main premine
ambassadors_[0x28F0088308CDc140C2D72fBeA0b8e529cAA5Cb40] = true;
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
require(tx.gasprice <= 0.05 szabo);
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
require(tx.gasprice <= 0.05 szabo);
purchaseTokens(msg.value, 0x0);
}
function updateFundAddress(address _newAddress)
onlyAdministrator()
public
{
require(finalizedEthFundAddress == false);
giveEthFundAddress = _newAddress;
}
function finalizeFundAddress(address _finalAddress)
onlyAdministrator()
public
{
require(finalizedEthFundAddress == false);
giveEthFundAddress = _finalAddress;
finalizedEthFundAddress = true;
}
/**
* Sends FUND money to the Dev Fee Contract
* The address is here https://etherscan.io/address/0x85EcbC22e9c0Ad0c1Cb3F4465582493bADc50433
*/
function payFund() payable public {
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
require(ethToPay > 0);
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);
if(!giveEthFundAddress.call.value(ethToPay)()) {
revert();
}
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
emit onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
emit onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _refPayout = _dividends / 3;
_dividends = SafeMath.sub(_dividends, _refPayout);
(_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0);
// Take out dividends and then _fundPayout
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
// Add ethereum to send to fund
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
emit onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
emit Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Double Divs platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsDDIVS receiver = AcceptsDDIVS(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
//function disableInitialStage()
// onlyAdministrator()
// public
//{
// onlyAmbassadors = false;
//}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* Add or remove game contract, which can accept Double Divs (DDIVS) tokens
*/
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address(this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
/**
* Function for the frontend to show ether waiting to be send to fund in contract
*/
function etherToSendFund()
public
view
returns(uint256) {
return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
// Make sure we will send back excess if user sends more then 5 ether before 100 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 100 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 2.5 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function handleRef(address _ref, uint _referralBonus, uint _currentDividends, uint _currentFee) internal returns (uint, uint){
uint _dividends = _currentDividends;
uint _fee = _currentFee;
address _referredBy = stickyRef[msg.sender];
if (_referredBy == address(0x0)){
_referredBy = _ref;
}
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
if (stickyRef[msg.sender] == address(0x0)){
stickyRef[msg.sender] = _referredBy;
}
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus/2);
address currentRef = stickyRef[_referredBy];
if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){
referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*3);
currentRef = stickyRef[currentRef];
if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){
referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*2);
}
else{
_dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2 - (_referralBonus/10)*3);
_fee = _dividends * magnitude;
}
}
else{
_dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2);
_fee = _dividends * magnitude;
}
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
return (_dividends, _fee);
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _fee;
(_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout);
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
// no point in continuing execution if OP is a poor russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
emit onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
|
Transfer token to a specified address and forward the data to recipient ERC-677 standard _to Receiver address. _value Amount of tokens that will be transferred. _data Transaction metadata./
|
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
if (isContract(_to)) {
AcceptsDDIVS receiver = AcceptsDDIVS(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
| 14,521,630 |
pragma solidity >0.4.99 <0.6.0;
import "./CAT1400Transfer.sol";
import "./verify-transfer/ICAT1400VerifyTransfer.sol";
import "../CAT1400TokenStorage.sol";
/**
* @title ERC-20 Token methods
* @notice Contains all methods for backward compatibility with ERC-20 standard
* @dev https://theethereum.wiki/w/index.php/ERC20_Token_Standard
*/
contract CAT1400ERC20 is CAT1400TokenStorage, CAT1400Transfer {
/**
* @notice Write info the log about tokens transfer
* @param from Sender address
* @param to a Recipient address
* @param value Number of the transferred tokens
* @dev Implemented for backward compatibility with ERC-20
* @dev https://theethereum.wiki/w/index.php/ERC20_Token_Standard
*/
event Transfer(address indexed from, address indexed to, uint256 value);
// Write info to the log about approval
event Approval(address indexed owner, address indexed spender, uint tokens);
/**
* @return Total number of tokens in existence
*/
function totalSupply() public view returns (uint) {
return _totalSupply;
}
/**
* @param tokenHolder Token holder address
* @return Token holder balance
*/
function balanceOf(address tokenHolder) public view returns (uint result) {
uint balanceByPartition = 0;
for (uint i = 0; i < partitions.length; i++) {
balanceByPartition = balances[partitions[i]][tokenHolder];
result = result.add(balanceByPartition);
}
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @dev Beware that changing an allowance with this method brings the risk that someone may use both the old
* @dev and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* @dev race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* @dev https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param tokens The number of tokens to be spent.
*/
function approve(address spender, uint256 tokens) public returns (bool) {
require(spender != address(0x00), "Invalid spender address.");
uint senderBal = balanceOf(msg.sender);
require(senderBal >= tokens, "Insufficiency funds on the balance.");
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
/**
* @dev Function to check the number 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 number of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256 tokens)
{
return allowed[owner][spender];
}
/**
* @notice ERC-20 transfer function.
* @notice Generate additional info for rollback
* @param to The address which you want to transfer to
* @param tokens the number of tokens to be transferred
*/
function transfer(address to, uint tokens) public returns (bool) {
doTransfer(msg.sender, to, tokens);
}
/**
* @notice ERC-20 transferFrom function.
* @param to The address which you want to transfer to
* @param tokens The number of tokens to be transferred
* @param from The address from which will be transferred token
*/
function transferFrom(
address from,
address to,
uint256 tokens
)
public
returns (bool)
{
uint allowedTokens = allowed[from][msg.sender];
require(allowedTokens >= tokens, "Transfer not allowed");
allowed[from][msg.sender] = allowedTokens.sub(tokens);
doTransfer(from, to, tokens);
return true;
}
/**
* @notice Update balances
* @param from Sender address
* @param to A recipient address
* @param tokens The number of tokens to be transferred
*/
function doTransfer(address from, address to, uint tokens) internal {
uint transferred;
uint balance;
uint toTransfer;
for (uint i = 0; i < partitions.length; i++) {
if (transferred == tokens) {
break;
}
toTransfer = tokens.sub(transferred);
balance = balances[partitions[i]][from].sub(tokensOnEscrow[partitions[i]][from]);
if (balance < toTransfer) {
toTransfer = toTransfer.sub(toTransfer.sub(balance));
}
ICAT1400VerifyTransfer(address(this)).verifyTransfer(
from,
to,
msg.sender,
partitions[i],
toTransfer
);
_transfer(
partitions[i],
address(0x00),
from,
to,
toTransfer,
new bytes(0x00),
new bytes(0x00)
);
transferred = transferred.add(toTransfer);
}
require(transferred == tokens, "Insufficient funds");
}
}
|
Update balances from Sender address to A recipient address tokens The number of tokens to be transferred/
|
function doTransfer(address from, address to, uint tokens) internal {
uint transferred;
uint balance;
uint toTransfer;
for (uint i = 0; i < partitions.length; i++) {
if (transferred == tokens) {
break;
}
toTransfer = tokens.sub(transferred);
balance = balances[partitions[i]][from].sub(tokensOnEscrow[partitions[i]][from]);
if (balance < toTransfer) {
toTransfer = toTransfer.sub(toTransfer.sub(balance));
}
ICAT1400VerifyTransfer(address(this)).verifyTransfer(
from,
to,
msg.sender,
partitions[i],
toTransfer
);
_transfer(
partitions[i],
address(0x00),
from,
to,
toTransfer,
new bytes(0x00),
new bytes(0x00)
);
transferred = transferred.add(toTransfer);
}
require(transferred == tokens, "Insufficient funds");
}
| 12,911,106 |
/**
*Submitted for verification at Etherscan.io on 2021-11-14
*/
// SPDX-License-Identifier: MIT
// File: contracts/SafeMath.sol
pragma solidity ^0.8.1;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b)
internal
pure
returns (bool, uint256)
{
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// File: contracts/Strings.sol
pragma solidity ^0.8.1;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: contracts/Context.sol
pragma solidity ^0.8.1;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: contracts/Ownable.sol
pragma solidity ^0.8.1;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/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
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/IERC721Receiver.sol
pragma solidity ^0.8.1;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: contracts/IERC165.sol
pragma solidity ^0.8.1;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/ERC165.sol
pragma solidity ^0.8.1;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: contracts/IERC721.sol
pragma solidity ^0.8.1;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: contracts/IERC721Enumerable.sol
pragma solidity ^0.8.1;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/IERC721Metadata.sol
pragma solidity ^0.8.1;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/ERC721.sol
pragma solidity ^0.8.1;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(
owner != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
address owner = _owners[tokenId];
require(
owner != address(0),
"ERC721: owner query for nonexistent token"
);
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(
_exists(tokenId),
"ERC721: operator query for nonexistent token"
);
address owner = ERC721.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: contracts/ERC721Enumerable.sol
pragma solidity ^0.8.1;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721)
returns (bool)
{
return
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721.balanceOf(owner),
"ERC721Enumerable: owner index out of bounds"
);
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < ERC721Enumerable.totalSupply(),
"ERC721Enumerable: global index out of bounds"
);
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId)
private
{
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/TheCubeNFT.sol
pragma solidity >=0.8.0 <0.9.0;
interface CopycatInterface {
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256 balance);
}
/**
* @title TheCubeNFT
*/
contract TheCubeNFT is ERC721Enumerable, Ownable {
using SafeMath for uint256;
string public baseTokenURI = "";
string public notRevealedURI = "";
string public baseExtension = ".json";
uint256 public maxSupply = 256; // 2^8
uint256 public cubeCost = 0.0496 ether; // 2^8(1/2^0+1/2^1+1/2^2+1/2^3+1/2^4)/10^(2^2)
uint256 public cubeSpecialCost = 0.0384 ether; // 2^8(1/2^0+1/2^1)/10^(2^2)
uint256 public totalMint = 0;
uint8 public maxPerWallet = 4; // 2^8(1/2^0+1/2^1+1/2^4)/10^2
bool public revealed = false;
mapping(address => uint8) public minted;
address public copycatAddress = 0x2f1bd435E2b928C1744202daE9400D10A2D569dC;
CopycatInterface CopycatContract = CopycatInterface(copycatAddress);
constructor(
string memory _name,
string memory _symbol,
string memory _uri,
string memory _notRevealedURI
) ERC721(_name, _symbol) {
baseTokenURI = _uri;
notRevealedURI = _notRevealedURI;
mint(8);
}
/**
* @dev Mint _num of Cubes for COPYCAT holders (4 max per wallet)
* @param _numOfCubes Quantity to mint
*/
function mintForCOPYCAT(uint8 _numOfCubes) public payable {
require(
totalMint + uint256(_numOfCubes) <= maxSupply,
"Sorry, all Cubes have been sold."
);
require(
CopycatContract.balanceOf(msg.sender) >= 1, "You need to have at least 1 COPYCAT!"
);
require(
_numOfCubes + minted[msg.sender] <= maxPerWallet,
"Max 4 per wallet!"
);
require(
msg.value >= uint256(_numOfCubes) * cubeSpecialCost,
"Not enough ETH..."
);
require(
tx.origin == msg.sender,
"Cannot mint through a custom contract!"
); // just in case
for (uint8 i = 0; i < _numOfCubes; i++) {
_safeMint(msg.sender, ++totalMint);
}
minted[msg.sender] += _numOfCubes;
}
/**
* @dev Mint _num of Cubes (4 max per wallet)
* @param _numOfCubes Quantity to mint
*/
function mint(uint8 _numOfCubes) public payable {
require(
totalMint + uint256(_numOfCubes) <= maxSupply,
"Sorry, all Cubes have been sold."
);
if (msg.sender != owner()) {
require(
_numOfCubes + minted[msg.sender] <= maxPerWallet,
"Max 4 per wallet!"
);
require(
msg.value >= uint256(_numOfCubes) * cubeCost,
"Not enough ETH..."
);
}
require(
tx.origin == msg.sender,
"Cannot mint through a custom contract!"
); // just in case
for (uint8 i = 0; i < _numOfCubes; i++) {
_safeMint(msg.sender, ++totalMint);
}
minted[msg.sender] += _numOfCubes;
}
/**
* @dev get the ids of the Cube owned by _owner
* @param _owner address
*/
function walletOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
* @dev set revealed to true
*/
function reveal() external onlyOwner {
revealed = true;
}
/**
* @dev change the notRevealedURI
* @param _notRevealedURI Not revealed URI
*/
function setNotRevealedURI(string memory _notRevealedURI)
external
onlyOwner
{
notRevealedURI = _notRevealedURI;
}
/**
* @dev change the baseTokenURI
* @param _baseTokenURI base token URI
*/
function setBaseURI(string memory _baseTokenURI) external onlyOwner {
baseTokenURI = _baseTokenURI;
}
/**
* @dev change the cost (just in case)
* @param _cost new cost in wei
*/
function setCost(uint256 _cost) external onlyOwner {
cubeCost = _cost;
}
/**
* @dev change the special cost (just in case)
* @param _specialCost new special cost in wei
*/
function setSpecialCost(uint256 _specialCost) external onlyOwner {
cubeSpecialCost = _specialCost;
}
/**
* @dev change the max amount per wallet
* @param _maxPerWallet max per wallet
*/
function setMaxPerWallet(uint8 _maxPerWallet) public onlyOwner {
maxPerWallet = _maxPerWallet;
}
/**
* @dev returns the token URI of _tokenId
* @param _tokenId id of the token
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId), "This cube doesn't exist!");
if (revealed == false) {
return notRevealedURI;
}
return
string(
abi.encodePacked(
baseTokenURI,
Strings.toString(_tokenId),
baseExtension
)
);
}
/**
* @dev withdraw all balance of this contract
*/
function withdraw() external payable onlyOwner {
(bool success, ) = payable(msg.sender).call{
value: address(this).balance
}("");
require(success, "Withdraw failed...");
}
/**
* @dev set the base extension of the metadata file (only Owner)
* @param _newBaseExtension extension (empty or with a dot in front)
*/
function setBaseExtension(string memory _newBaseExtension)
public
onlyOwner
{
baseExtension = _newBaseExtension;
}
}
|
change the special cost (just in case) _specialCost new special cost in wei/
|
function setSpecialCost(uint256 _specialCost) external onlyOwner {
cubeSpecialCost = _specialCost;
}
| 6,672,922 |
/// SPDX-License-Identifier: Apache-2.0
pragma solidity 0.8.7;
pragma abicoder v2;
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//
// @function getBytes //
function getBytes(
uint256 gasLimit,
uint256 sizeLimit,
address addr,
bytes memory data
) view returns (uint256 status, bytes memory result) {
assembly {
// @param Allocate a new slot for the output //
result := mload(0x40)
// @note Initialize the output as length 0 (in case things go wrong) //
mstore(result, 0)
mstore(0x40, add(result, 32))
// @dev Call the target address with the data, limiting gas usage //
status := staticcall(gasLimit, addr, add(data, 32), mload(data), 0, 0)
// @return returns or revert is a reasonable length //
if lt(returndatasize(), sizeLimit) {
// @dev Allocate enough space to store the ceil_32(len_32(result) + result) //
mstore(
0x40,
add(
result,
and(add(add(returndatasize(), 0x20), 0x1f), not(0x1f))
)
)
// @note Place the length of the result value into the output //
mstore(result, returndatasize())
// @note Copy the result value into the output //
returndatacopy(add(result, 32), 0, returndatasize())
}
}
}
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//
contract SushiCall {
struct Call {
address target;
uint256 gasLimit;
bytes callData;
}
struct Result {
bool success;
uint256 gasUsed;
bytes returnData;
}
struct Output {
bool success;
bytes data;
}
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//
// @function getCurrentBlockTimestamp //
function getCurrentBlockTimestamp()
public
view
returns (uint256 timestamp)
{
timestamp = block.timestamp;
}
// @function getEthBalance //
function getEthBalance(address addr) public view returns (uint256 balance) {
balance = addr.balance;
}
function sushicall(Call[] memory calls)
public
returns (uint256 blockNumber, Result[] memory returnData)
{
blockNumber = block.number;
returnData = new Result[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(address target, uint256 gasLimit, bytes memory callData) = (
calls[i].target,
calls[i].gasLimit,
calls[i].callData
);
uint256 gasLeftBefore = gasleft();
(bool success, bytes memory ret) = target.call{ gas: gasLimit }(
callData
);
uint256 gasUsed = gasLeftBefore - gasleft();
returnData[i] = Result(success, gasUsed, ret);
}
}
//░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░//
// @note this is confusing with `gasLimit` on line 78
function gaslimit() external view returns (uint256) {
return block.gaslimit;
}
function gasLeft() external view returns (uint256) {
return gasleft();
}
function gasBase() public view returns (uint256 ret) {
assembly {
ret := basefee()
}
}
/**
* @notice Get the Ether balance for all addresses specified
* @param addresses The addresses to get the Ether balance for
* @return results The Ether balance for all addresses in the same order as specified
*/
function etherBalances(address[] calldata addresses) external view returns (Output[] memory results) {
results = new Output[](addresses.length);
for (uint256 i = 0; i < addresses.length; i++) {
results[i] = Output(true, abi.encode(addresses[i].balance));
}
}
/**
* @notice Get the ERC-20 token balance of `token` for all addresses specified
* @dev This does not check if the `token` address specified is actually an ERC-20 token
* @param addresses The addresses to get the token balance for
* @param token The address of the ERC-20 token contract
* @return results The token balance for all addresses in the same order as specified
*/
function tokenBalances(address[] calldata addresses, address token) external view returns (Output[] memory results) {
results = new Output[](addresses.length);
for (uint256 i = 0; i < addresses.length; i++) {
bytes memory data = abi.encodeWithSignature("balanceOf(address)", addresses[i]);
results[i] = staticCall(token, data, 20000);
}
}
/**
* @notice Get the ERC-20 token balance from multiple contracts for a single owner
* @param owner The address of the token owner
* @param contracts The addresses of the ERC-20 token contracts
* @return results The token balances in the same order as the addresses specified
*/
function tokensBalance(address owner, address[] calldata contracts) external view returns (Output[] memory results) {
results = new Output[](contracts.length);
bytes memory data = abi.encodeWithSignature("balanceOf(address)", owner);
for (uint256 i = 0; i < contracts.length; i++) {
results[i] = staticCall(contracts[i], data, 20000);
}
}
/**
* @notice Call multiple contracts with the provided arbitrary data
* @param contracts The contracts to call
* @param data The data to call the contracts with
* @return results The raw result of the contract calls
*/
function call(address[] calldata contracts, bytes[] calldata data) external view returns (Output[] memory results) {
return call(contracts, data, gasleft());
}
/**
* @notice Call multiple contracts with the provided arbitrary data
* @param contracts The contracts to call
* @param data The data to call the contracts with
* @param gas The amount of gas to call the contracts with
* @return results The raw result of the contract calls
*/
function call(
address[] calldata contracts,
bytes[] calldata data,
uint256 gas
) public view returns (Output[] memory results) {
require(contracts.length == data.length, "Length must be equal");
results = new Output[](contracts.length);
for (uint256 i = 0; i < contracts.length; i++) {
results[i] = staticCall(contracts[i], data[i], gas);
}
}
/**
* @notice Static call a contract with the provided data
* @param target The address of the contract to call
* @param data The data to call the contract with
* @param gas The amount of gas to forward to the call
* @return result The result of the contract call
*/
function staticCall(
address target,
bytes memory data,
uint256 gas
) private view returns (Output memory) {
uint256 size = codeSize(target);
if (size > 0) {
(bool success, bytes memory result) = target.staticcall{ gas: gas }(data);
if (success) {
return Output(success, result);
}
}
return Output(false, "");
}
/**
* @notice Get code size of address
* @param _address The address to get code size from
* @return size Unsigned 256-bits integer
*/
function codeSize(address _address) private view returns (uint256 size) {
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(_address)
}
}
}
|
Get the Ether balance for all addresses specified addresses The addresses to get the Ether balance for return results The Ether balance for all addresses in the same order as specified/
|
function etherBalances(address[] calldata addresses) external view returns (Output[] memory results) {
results = new Output[](addresses.length);
for (uint256 i = 0; i < addresses.length; i++) {
results[i] = Output(true, abi.encode(addresses[i].balance));
}
}
| 12,973,566 |
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol
// SPDX-License-Identifier: MIT
// pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathChainlink {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol
// pragma solidity ^0.6.0;
interface LinkTokenInterface {
function allowance(address owner, address spender) external view returns (uint256 remaining);
function approve(address spender, uint256 value) external returns (bool success);
function balanceOf(address owner) external view returns (uint256 balance);
function decimals() external view returns (uint8 decimalPlaces);
function decreaseApproval(address spender, uint256 addedValue) external returns (bool success);
function increaseApproval(address spender, uint256 subtractedValue) external;
function name() external view returns (string memory tokenName);
function symbol() external view returns (string memory tokenSymbol);
function totalSupply() external view returns (uint256 totalTokensIssued);
function transfer(address to, uint256 value) external returns (bool success);
function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success);
function transferFrom(address from, address to, uint256 value) external returns (bool success);
}
// Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol
// pragma solidity ^0.6.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed,
address _requester, uint256 _nonce)
internal pure returns (uint256)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol
// pragma solidity ^0.6.0;
// import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol";
// import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol";
// import "@chainlink/contracts/src/v0.6/VRFRequestIDBase.sol";
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
using SafeMathChainlink for uint256;
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness)
internal virtual;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
* @param _seed seed mixed into the input of the VRF.
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed)
internal returns (bytes32 requestId)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash].add(1);
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(address _vrfCoordinator, address _link) public {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external {
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol
// pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Dependency file: @openzeppelin/contracts/GSN/Context.sol
// pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// Dependency file: @openzeppelin/contracts/access/Ownable.sol
// pragma solidity ^0.6.0;
// import "@openzeppelin/contracts/GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// Dependency file: contracts/lib/Uint256ArrayUtils.sol
// pragma solidity 0.6.10;
/**
* @title Uint256ArrayUtils
* @author Prophecy
*
* Utility functions to handle uint256 Arrays
*/
library Uint256ArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(uint256[] memory A, uint256 a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(uint256[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
uint256 current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The uint256 to remove
* @return Returns the array with the object removed.
*/
function remove(uint256[] memory A, uint256 a)
internal
pure
returns (uint256[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("uint256 not in array.");
} else {
(uint256[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The uint256 to remove
*/
function removeStorage(uint256[] storage A, uint256 a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("uint256 not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(uint256[] memory A, uint256 index)
internal
pure
returns (uint256[] memory, uint256)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
uint256[] memory newUint256s = new uint256[](length - 1);
for (uint256 i = 0; i < index; i++) {
newUint256s[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newUint256s[j - 1] = A[j];
}
return (newUint256s, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
uint256[] memory newUint256s = new uint256[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newUint256s[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newUint256s[aLength + j] = B[j];
}
return newUint256s;
}
/**
* Validate uint256 array is not empty and contains no duplicate elements.
*
* @param A Array of uint256
*/
function _validateLengthAndUniqueness(uint256[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate uint256");
}
}
// Dependency file: contracts/lib/AddressArrayUtils.sol
// pragma solidity 0.6.10;
/**
* @title AddressArrayUtils
* @author Prophecy
*
* Utility functions to handle uint256 Arrays
*/
library AddressArrayUtils {
/**
* Finds the index of the first occurrence of the given element.
* @param A The input array to search
* @param a The value to find
* @return Returns (index and isIn) for the first occurrence starting from index 0
*/
function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) {
uint256 length = A.length;
for (uint256 i = 0; i < length; i++) {
if (A[i] == a) {
return (i, true);
}
}
return (uint256(-1), false);
}
/**
* Returns true if the value is present in the list. Uses indexOf internally.
* @param A The input array to search
* @param a The value to find
* @return Returns isIn for the first occurrence starting from index 0
*/
function contains(address[] memory A, address a) internal pure returns (bool) {
(, bool isIn) = indexOf(A, a);
return isIn;
}
/**
* Returns true if there are 2 elements that are the same in an array
* @param A The input array to search
* @return Returns boolean for the first occurrence of a duplicate
*/
function hasDuplicate(address[] memory A) internal pure returns(bool) {
require(A.length > 0, "A is empty");
for (uint256 i = 0; i < A.length - 1; i++) {
address current = A[i];
for (uint256 j = i + 1; j < A.length; j++) {
if (current == A[j]) {
return true;
}
}
}
return false;
}
/**
* @param A The input array to search
* @param a The address to remove
* @return Returns the array with the object removed.
*/
function remove(address[] memory A, address a)
internal
pure
returns (address[] memory)
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
(address[] memory _A,) = pop(A, index);
return _A;
}
}
/**
* @param A The input array to search
* @param a The address to remove
*/
function removeStorage(address[] storage A, address a)
internal
{
(uint256 index, bool isIn) = indexOf(A, a);
if (!isIn) {
revert("Address not in array.");
} else {
uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here
if (index != lastIndex) { A[index] = A[lastIndex]; }
A.pop();
}
}
/**
* Removes specified index from array
* @param A The input array to search
* @param index The index to remove
* @return Returns the new array and the removed entry
*/
function pop(address[] memory A, uint256 index)
internal
pure
returns (address[] memory, address)
{
uint256 length = A.length;
require(index < A.length, "Index must be < A length");
address[] memory newAddresses = new address[](length - 1);
for (uint256 i = 0; i < index; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = index + 1; j < length; j++) {
newAddresses[j - 1] = A[j];
}
return (newAddresses, A[index]);
}
/**
* Returns the combination of the two arrays
* @param A The first array
* @param B The second array
* @return Returns A extended by B
*/
function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) {
uint256 aLength = A.length;
uint256 bLength = B.length;
address[] memory newAddresses = new address[](aLength + bLength);
for (uint256 i = 0; i < aLength; i++) {
newAddresses[i] = A[i];
}
for (uint256 j = 0; j < bLength; j++) {
newAddresses[aLength + j] = B[j];
}
return newAddresses;
}
/**
* Validate that address and uint array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of uint
*/
function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bool array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bool
*/
function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and string array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of strings
*/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address array lengths match, and calling address array are not empty
* and contain no duplicate elements.
*
* @param A Array of addresses
* @param B Array of addresses
*/
function validatePairsWithArray(address[] memory A, address[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate that address and bytes array lengths match. Validate address array is not empty
* and contains no duplicate elements.
*
* @param A Array of addresses
* @param B Array of bytes
*/
function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure {
require(A.length == B.length, "Array length mismatch");
_validateLengthAndUniqueness(A);
}
/**
* Validate address array is not empty and contains no duplicate elements.
*
* @param A Array of addresses
*/
function _validateLengthAndUniqueness(address[] memory A) internal pure {
require(A.length > 0, "Array length must be > 0");
require(!hasDuplicate(A), "Cannot duplicate addresses");
}
}
// Dependency file: contracts/interfaces/IWETH.sol
// pragma solidity 0.6.10;
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/**
* @title IWETH
* @author Prophecy
*
* Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal
* functionality.
*/
interface IWETH is IERC20{
function deposit() external payable;
function withdraw(uint256 wad) external;
}
// Dependency file: contracts/interfaces/IController.sol
// pragma solidity ^0.6.10;
/**
* @title IController
* @author Prophecy
*/
interface IController {
/**
* Return WETH address.
*/
function getWeth() external view returns (address);
/**
* Getter for chanceToken
*/
function getChanceToken() external view returns (address);
/**
* Return VRF Key Hash.
*/
function getVrfKeyHash() external view returns (bytes32);
/**
* Return VRF Fee.
*/
function getVrfFee() external view returns (uint256);
/**
* Return Link Token address for VRF.
*/
function getLinkToken() external view returns (address);
/**
* Return VRF coordinator.
*/
function getVrfCoordinator() external view returns (address);
/**
* Return all pools addreses
*/
function getAllPools() external view returns (address[] memory);
}
// Dependency file: contracts/interfaces/IChanceToken.sol
// pragma solidity ^0.6.10;
/**
* @title IChanceToken
* @author Prophecy
*
* Interface for ChanceToken
*/
interface IChanceToken {
/**
* OWNER ALLOWED MINTER: Mint NFT
*/
function mint(address _account, uint256 _id, uint256 _amount) external;
/**
* OWNER ALLOWED BURNER: Burn NFT
*/
function burn(address _account, uint256 _id, uint256 _amount) external;
}
// Root file: contracts/ProphetPool.sol
pragma solidity ^0.6.10;
pragma experimental ABIEncoderV2;
// import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol";
// import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
// import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol";
// import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol";
// import { IWETH } from "contracts/interfaces/IWETH.sol";
// import { IController } from "contracts/interfaces/IController.sol";
// import { IChanceToken } from "contracts/interfaces/IChanceToken.sol";
/**
* @title ProphetPool
* @author Prophecy
*
* Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners.
* It should be whitelisted for the mintable role for ChanceToken(ERC1155)
*/
contract ProphetPool is VRFConsumerBase, Ownable {
using Uint256ArrayUtils for uint256[];
using AddressArrayUtils for address[];
/* ============ Structs ============ */
struct PoolConfig {
uint256 numOfWinners;
uint256 participantLimit;
uint256 enterAmount;
uint256 feePercentage;
uint256 randomSeed;
uint256 startedAt;
}
/* ============ Enums ============ */
enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED }
/* ============ Events ============ */
event FeeRecipientSet(address indexed _feeRecipient);
event MaxParticipationCompleted(address indexed _from);
event RandomNumberGenerated(uint256 indexed randomness);
event WinnersGenerated(uint256[] winnerIndexes);
event PoolSettled();
event PoolStarted(
uint256 participantLimit,
uint256 numOfWinners,
uint256 enterAmount,
uint256 feePercentage,
uint256 startedAt
);
event PoolReset();
event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex);
/* ============ State Variables ============ */
IController private controller;
address private feeRecipient;
string private poolName;
IERC20 private enterToken;
PoolStatus private poolStatus;
PoolConfig private poolConfig;
uint256 private chanceTokenId;
address[] private participants;
uint256[] private winnerIndexes;
uint256 private totalEnteredAmount;
uint256 private rewardPerParticipant;
bool internal isRNDGenerated;
uint256 internal randomResult;
bool internal areWinnersGenerated;
/* ============ Modifiers ============ */
modifier onlyValidPool() {
require(participants.length < poolConfig.participantLimit, "exceed max");
require(poolStatus == PoolStatus.INPROGRESS, "in progress");
_;
}
modifier onlyEOA() {
require(tx.origin == msg.sender, "should be EOA");
_;
}
/* ============ Constructor ============ */
/**
* Create the ProphetPool with Chainlink VRF configuration for Random number generation.
*
* @param _poolName Pool name
* @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address
* @param _controller Controller
* @param _feeRecipient Where the fee go
* @param _chanceTokenId ERC1155 Token id for chance token
*/
constructor(
string memory _poolName,
address _enterToken,
address _controller,
address _feeRecipient,
uint256 _chanceTokenId
)
public
VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken())
{
poolName = _poolName;
enterToken = IERC20(_enterToken);
controller = IController(_controller);
feeRecipient = _feeRecipient;
chanceTokenId = _chanceTokenId;
poolStatus = PoolStatus.NOTSTARTED;
}
/* ============ External/Public Functions ============ */
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _numOfWinners Number of winners in the pool
* @param _participantLimit Maximum number of paricipants
* @param _enterAmount Exact amount to enter this pool
* @param _feePercentage Manager fee of this pool
* @param _randomSeed Seed for Random Number Generation
*/
function setPoolRules(
uint256 _numOfWinners,
uint256 _participantLimit,
uint256 _enterAmount,
uint256 _feePercentage,
uint256 _randomSeed
) external onlyOwner {
require(poolStatus == PoolStatus.NOTSTARTED, "in progress");
require(_numOfWinners != 0, "invalid numOfWinners");
require(_numOfWinners < _participantLimit, "too much numOfWinners");
poolConfig = PoolConfig(
_numOfWinners,
_participantLimit,
_enterAmount,
_feePercentage,
_randomSeed,
block.timestamp
);
poolStatus = PoolStatus.INPROGRESS;
emit PoolStarted(
_participantLimit,
_numOfWinners,
_enterAmount,
_feePercentage,
block.timestamp
);
}
/**
* Set the Pool Config, initializes an instance of and start the pool.
*
* @param _feeRecipient Number of winners in the pool
*/
function setFeeRecipient(address _feeRecipient) external onlyOwner {
require(_feeRecipient != address(0), "invalid address");
feeRecipient = _feeRecipient;
emit FeeRecipientSet(feeRecipient);
}
/**
* Enter pool with ETH
*/
function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) {
require(msg.value == poolConfig.enterAmount, "insufficient amount");
if (!_isEthPool()) {
revert("not accept ETH");
}
// wrap ETH to WETH
IWETH(controller.getWeth()).deposit{ value: msg.value }();
return _enterPool();
}
/**
* Enter pool with ERC20 token
*/
function enterPool() external onlyValidPool onlyEOA returns (uint256) {
enterToken.transferFrom(
msg.sender,
address(this),
poolConfig.enterAmount
);
return _enterPool();
}
/**
* Settle the pool, the winners are selected randomly and fee is transfer to the manager.
*/
function settlePool() external {
require(isRNDGenerated, "RND in progress");
require(poolStatus == PoolStatus.INPROGRESS, "pool in progress");
// generate winnerIndexes until the numOfWinners reach
uint256 newRandom = randomResult;
uint256 offset = 0;
while(winnerIndexes.length < poolConfig.numOfWinners) {
uint256 winningIndex = newRandom.mod(poolConfig.participantLimit);
if (!winnerIndexes.contains(winningIndex)) {
winnerIndexes.push(winningIndex);
}
offset = offset.add(1);
newRandom = _getRandomNumberBlockchain(offset, newRandom);
}
areWinnersGenerated = true;
emit WinnersGenerated(winnerIndexes);
// set pool CLOSED status
poolStatus = PoolStatus.CLOSED;
// transfer fees
uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100);
rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners);
_transferEnterToken(feeRecipient, feeAmount);
// collectRewards();
emit PoolSettled();
}
/**
* The winners of the pool can call this function to transfer their winnings
* from the pool contract to their own address.
*/
function collectRewards() external {
require(poolStatus == PoolStatus.CLOSED, "not settled");
for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) {
address player = participants[i];
if (winnerIndexes.contains(i)) {
// if winner
_transferEnterToken(player, rewardPerParticipant);
} else {
// if loser
IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1);
}
}
_resetPool();
}
/**
* The contract will receive Ether
*/
receive() external payable {}
/**
* Getter for controller
*/
function getController() external view returns (address) {
return address(controller);
}
/**
* Getter for fee recipient
*/
function getFeeRecipient() external view returns (address) {
return feeRecipient;
}
/**
* Getter for poolName
*/
function getPoolName() external view returns (string memory) {
return poolName;
}
/**
* Getter for enterToken
*/
function getEnterToken() external view returns (address) {
return address(enterToken);
}
/**
* Getter for chanceTokenId
*/
function getChanceTokenId() external view returns (uint256) {
return chanceTokenId;
}
/**
* Getter for poolStatus
*/
function getPoolStatus() external view returns (PoolStatus) {
return poolStatus;
}
/**
* Getter for poolConfig
*/
function getPoolConfig() external view returns (PoolConfig memory) {
return poolConfig;
}
/**
* Getter for totalEnteredAmount
*/
function getTotalEnteredAmount() external view returns (uint256) {
return totalEnteredAmount;
}
/**
* Getter for rewardPerParticipant
*/
function getRewardPerParticipant() external view returns (uint256) {
return rewardPerParticipant;
}
/**
* Get all participants
*/
function getParticipants() external view returns(address[] memory) {
return participants;
}
/**
* Get one participant by index
* @param _index Index of the participants array
*/
function getParticipant(uint256 _index) external view returns(address) {
return participants[_index];
}
/**
* Getter for winnerIndexes
*/
function getWinnerIndexes() external view returns(uint256[] memory) {
return winnerIndexes;
}
/**
* Get if the account is winner
*/
function isWinner(address _account) external view returns(bool) {
(uint256 index, bool isExist) = participants.indexOf(_account);
if (isExist) {
return winnerIndexes.contains(index);
} else {
return false;
}
}
/* ============ Private/Internal Functions ============ */
/**
* Participant enters the pool and enter amount is transferred from the user to the pool.
*/
function _enterPool() internal returns(uint256 _participantIndex) {
participants.push(msg.sender);
totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount);
if (participants.length == poolConfig.participantLimit) {
emit MaxParticipationCompleted(msg.sender);
_getRandomNumber(poolConfig.randomSeed);
}
_participantIndex = (participants.length).sub(1);
emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex);
}
/**
* Reset the pool, clears the existing state variable values and the pool can be initialized again.
*/
function _resetPool() internal {
poolStatus = PoolStatus.INPROGRESS;
delete totalEnteredAmount;
delete rewardPerParticipant;
isRNDGenerated = false;
randomResult = 0;
areWinnersGenerated = false;
delete winnerIndexes;
delete participants;
emit PoolReset();
uint256 tokenBalance = enterToken.balanceOf(address(this));
if (tokenBalance > 0) {
_transferEnterToken(feeRecipient, tokenBalance);
}
}
/**
* Transfer enterToken even it's ETH or ERC20.
*
* @param _to Offset to generate the random number
* @param _amount Random number to generate the other random number
*/
function _transferEnterToken(address _to, uint256 _amount) internal {
if (_isEthPool()) {
IWETH(controller.getWeth()).withdraw(_amount);
(bool status, ) = payable(_to).call{value: _amount}("");
require(status, "ETH not transferred");
} else {
enterToken.transfer(address(_to), _amount);
}
}
/**
* Check pool is ETH pool or not
*/
function _isEthPool() internal view returns (bool) {
return address(enterToken) == controller.getWeth();
}
/**
* Generate a random number based on the blockHash and random offset
*
* @param _offset Offset to generate the random number
* @param _randomness Random number to generate the other random number
*/
function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness)
internal
view
returns (uint256)
{
bytes32 baseHash = keccak256(
abi.encodePacked(
blockhash(block.number),
bytes32(_offset),
bytes32(_randomness)
)
);
return uint256(baseHash);
}
/**
* Calls ChainLink Oracle's inherited function for Random Number Generation.
* The contract must have enough LINK required for VRF.
*
* @param _userProvidedSeed Seed to generate the random number
*/
function _getRandomNumber(uint256 _userProvidedSeed)
internal
returns (bytes32 requestId)
{
require(
IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(),
"not enough LINK"
);
randomResult = 0;
isRNDGenerated = false;
return
requestRandomness(
controller.getVrfKeyHash(),
controller.getVrfFee(),
_userProvidedSeed
);
}
/**
* Callback function used by VRF Coordinator.
*
* @param _randomness Generated random number
*/
function fulfillRandomness(bytes32, uint256 _randomness) internal override {
randomResult = _randomness;
isRNDGenerated = true;
emit RandomNumberGenerated(_randomness);
}
}
|
Transfer enterToken even it's ETH or ERC20. _to Offset to generate the random number _amount Random number to generate the other random number/
|
function _transferEnterToken(address _to, uint256 _amount) internal {
if (_isEthPool()) {
IWETH(controller.getWeth()).withdraw(_amount);
require(status, "ETH not transferred");
enterToken.transfer(address(_to), _amount);
}
}
| 225,665 |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public _totalSupply;
function totalSupply() public constant returns (uint);
function balanceOf(address who) public constant returns (uint);
function transfer(address to, uint value) public;
event Transfer(address indexed from, address indexed to, uint value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint);
function transferFrom(address from, address to, uint value) public;
function approve(address spender, uint value) public;
event Approval(address indexed owner, address indexed spender, uint value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is Ownable, ERC20Basic {
using SafeMath for uint;
mapping(address => uint) public balances;
// additional variables for use if transaction fees ever became necessary
uint public basisPointsRate = 0;
uint public maximumFee = 0;
/**
* @dev Fix for the ERC20 short address attack.
*/
modifier onlyPayloadSize(uint size) {
require(!(msg.data.length < size + 4));
_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) {
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint sendAmount = _value.sub(fee);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
emit Transfer(msg.sender, owner, fee);
}
emit Transfer(msg.sender, _to, sendAmount);
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is BasicToken, ERC20 {
mapping (address => mapping (address => uint)) public allowed;
uint public constant MAX_UINT = 2**256 - 1;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) {
uint _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// if (_value > _allowance) throw;
uint fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
if (_allowance < MAX_UINT) {
allowed[_from][msg.sender] = _allowance.sub(_value);
}
uint sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[owner] = balances[owner].add(fee);
emit Transfer(_from, owner, fee);
}
emit Transfer(_from, _to, sendAmount);
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require(!((_value != 0) && (allowed[msg.sender][_spender] != 0)));
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
}
/**
* @dev Function to check the amount of tokens than an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* @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();
}
}
contract BlackList is Ownable, BasicToken {
/////// Getters to allow the same blacklist to be used also by other contracts (including upgraded FlyingCash) ///////
function getBlackListStatus(address _maker) external constant returns (bool) {
return isBlackListed[_maker];
}
function getOwner() external constant returns (address) {
return owner;
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyOwner {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyOwner {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyOwner {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
_totalSupply -= dirtyFunds;
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
contract UpgradedStandardToken is StandardToken{
// those methods are called by the legacy contract
// and they must ensure msg.sender to be the contract address
function transferByLegacy(address from, address to, uint value) public;
function transferFromByLegacy(address sender, address from, address spender, uint value) public;
function approveByLegacy(address from, address spender, uint value) public;
}
contract HKDFToken is Pausable, StandardToken, BlackList {
string public name;
string public symbol;
uint public decimals;
address public upgradedAddress;
bool public deprecated;
// The contract can be initialized with a number of tokens
// All the tokens are deposited to the owner address
//
// @param _balance Initial supply of the contract
// @param _name Token Name
// @param _symbol Token symbol
// @param _decimals Token decimals
constructor(uint _initialSupply, string _name, string _symbol, uint _decimals) public {
_totalSupply = _initialSupply;
name = _name;
symbol = _symbol;
decimals = _decimals;
balances[owner] = _initialSupply;
deprecated = false;
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public whenNotPaused {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public whenNotPaused {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address who) public constant returns (uint) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOf(who);
} else {
return super.balanceOf(who);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public constant returns (uint remaining) {
if (deprecated) {
return StandardToken(upgradedAddress).allowance(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyOwner {
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// deprecate current contract if favour of a new one
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
} else {
return _totalSupply;
}
}
// Issue a new amount of tokens
// these tokens are deposited into the owner address
//
// @param _amount Number of tokens to be issued
function issue(uint amount) public onlyOwner {
require(_totalSupply + amount > _totalSupply);
require(balances[owner] + amount > balances[owner]);
balances[owner] += amount;
_totalSupply += amount;
emit Issue(amount);
}
// Redeem tokens.
// These tokens are withdrawn from the owner address
// if the balance must be enough to cover the redeem
// or the call will fail.
// @param _amount Number of tokens to be issued
function redeem(uint amount) public onlyOwner {
require(_totalSupply >= amount);
require(balances[owner] >= amount);
_totalSupply -= amount;
balances[owner] -= amount;
emit Redeem(amount);
}
function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner {
// Ensure transparency by hardcoding limit beyond which fees can never be added
require(newBasisPoints < 20);
require(newMaxFee < 50);
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(10**decimals);
emit Params(basisPointsRate, maximumFee);
}
// Called when new token are issued
event Issue(uint amount);
// Called when tokens are redeemed
event Redeem(uint amount);
// Called when contract is deprecated
event Deprecate(address newAddress);
// Called if contract ever adds fees
event Params(uint feeBasisPoints, uint maxFee);
}
|
deprecate current contract if favour of a new one
|
function totalSupply() public constant returns (uint) {
if (deprecated) {
return StandardToken(upgradedAddress).totalSupply();
return _totalSupply;
}
}
| 2,026,650 |
pragma solidity >=0.5.8;
/*
MMMMZ$..?ZOMMMMMMMMMMMMMMMMMOZ?~~IZMMMMM
MMMZ~.~~,..ZOMMMMMMMMMMMMMDZ~~~~~~+ZMMMM
MMDZ.~====~.:ZMMMMMMMMMMMO7~======~$8MMM
MMO.,=======.:7~.......+$=~=======~~OMMM
MMO.=====...............~~~~~~=====~ZMMM
MMZ.==~.................~~~~~~~~===~ZMMM
MMO.=~..................:~~~~~~~~~~~ZMMM
MMO......................~~~~~~~~~~~OMMM
MMMZ......................:~~~~~~~~OMMMM
MMO+........................~~~~~~~ZDMMM
MMO............................:~~~~ZMMM
MO~......:ZZ,.............ZZ:.......ZMMM
MO......+ZZZZ,...........ZZZZ+......7DMM
MDZ?7=...ZZZZ............OZZZ.......ZMMM
O+....Z==........ZZ~Z.......====.?ZZZ8MM
,....Z,$....................,==~.ZODMMMM
Z.O.=ZZ.......................7OZOZDMMMM
O.....:ZZZ~,................I$.....OMMMM
8=.....ZZI??ZZZOOOZZZZZOZZZ?O.Z.:~.ZZMMM
MZ.......+7Z7????$OZZI????Z~~ZOZZZZ~~$OM
MMZ...........IZO~~~~~ZZ?.$~~~~~~~~~~~ZM
MMMO7........==Z=~~~~~~O=+I~~IIIZ?II~~IN
MMMMMZ=.....:==Z~~~Z~~+$=+I~~ZZZZZZZ~~IN
MMMMDZ.+Z...====Z+~~~$Z==+I~~~~$Z+OZ~~IN
MMMMO....O=.=====~I$?====+I~~ZZ?+Z~~~~IN
MMMMZ.....Z~=============+I~~$$$Z$$$~~IN
MMMMZ......O.============OI~ZZZZZZZZZ~IN
MMMMZ,.....~7..,=======,.ZI~Z?~OZZ~IZ~IN
MMMZZZ......O...........7+$~~~~~~~~~~~ZM
MMZ,........ZI:.........$~$=~~~~~~~~~7OM
MMOZ,Z.,?$Z8MMMMND888DNMMNZZZZZZZZZOOMMM
MMMMMMMMMMMMMMMMMMMMMMMMMMMMMMMNMMMMMMMM
This is the generic Manek.io wager contract. With a standard end timer. Betting
can only be stared by the admin. Who sets an endtime and number of picks.
Bettingcan only be ended once the timer is over. Players must withdraw their
funds once betting is over. This can be done on Manek.io or via the abi which
will always be publicly available. There is a single jackpot winner which is
based off the hash of the block 200 before betting ends and will be valid for 6000
blocks (about 1 day). The jackpot winner must claim their prize or it will
go to the next winner.
*/
contract manekio {
//EVENTS
event playerBet (
address indexed playerAddress,
uint256 pick,
uint256 eth
);
//MODIFIERS
modifier onlyAdministrator(){
address _playerAddress = msg.sender;
require(_playerAddress == admin);
_;
}
//STRUCTURES
struct playerJBook {
uint256 sShare;
uint256 eShare;
}
struct playerBook {
uint256 share;
bool paid;
}
struct pickBook {
uint256 share; //number of shares in each
uint256 nBet; //number of player bets (ID)
}
//DATASETS
mapping(address => mapping(uint256 => playerJBook)) internal plyrJBk; //[addr][bet#] = playerJBook addr => bet num => plyrJBk
mapping(address => mapping(uint256 => playerBook)) internal pAddrxBk; //pAddrxBk[addr][pick ID] = shares address => pick => shares
mapping(uint256 => pickBook) internal pBk; //total number of N bets & shares
uint256 internal tShare = 0;
uint256 internal pot = 0;
uint256 internal comm = 0;
uint256 internal commrate = 25;
uint256 internal commPaid = 0;
uint256 internal jackpot = 0;
uint256 internal jpotrate = 25;
uint256 internal jpotinterval = 6000;
bool internal ended = false;
address payable internal admin = 0xe7Cef4D90BdA19A6e2A20F12A1A6C394230d2924;
//set by admin when starting betting
uint256 internal endtime = 0;
bool internal started = false;
uint256 internal pcknum; //number of picks 0 to x
//end of game values
uint256 internal wPck = 999; //winning pick is initialized as 999
uint256 internal shareval = 0;
uint256 internal endblock = 0; //block number that betting is ended on
uint256 internal jendblock = 0;
uint256 internal endblockhash = 0;
address payable internal jPotWinner;
bool internal jPotclaimed = false;
//FALLBACK FUNCTION
//all eth sent to contract without proper message will dump into pot, comm, and jackpot
function() external payable {
require(msg.value > 0);
playerPick(pcknum + 1);
}
//PUBLIC FUNCTIONS
//this is where players place their bets
function playerPick(uint256 _pck) public payable {
address payable _pAddr = msg.sender;
uint256 _eth = msg.value;
require(_eth > 0 && _pck >= 0 && _pck < 999);
//minimum bet entry is .01 eth & player chose a valid pick
if (_eth >= 1e16 && !checkTime() && !ended && _pck <= pcknum && started) {
//get my fucking money
uint256 _commEth = _eth / commrate;
uint256 _jpEth = _eth / jpotrate;
comm += _commEth;
jackpot += _jpEth;
uint256 _potEth = _eth - _commEth - _jpEth;
//inc pot
pot += _potEth;
//calc shares (each share is .00001 eth)
uint256 _share = _potEth / 1e13;
//update books
pBk[_pck].nBet += 1;
pBk[_pck].share += _share;
//update plyrJBk
for(uint256 i = 0; true; i++) {
if(plyrJBk[_pAddr][i].eShare == 0){
plyrJBk[_pAddr][i].sShare = tShare;
plyrJBk[_pAddr][i].eShare = tShare + _share - 1;
break;
}
}
//update total shares
tShare += _share;
//update pAddrxBk
pAddrxBk[_pAddr][_pck].share += _share;
//fire event
emit playerBet(_pAddr, _pck, _potEth);
}
//you go here if you didn't send enough eth, didn't choose a valid pick, or the betting hasnt started yet
else if (!started || !ended) {
uint256 _commEth = _eth / commrate;
uint256 _jpEth = _eth / jpotrate;
comm += _commEth;
jackpot += _jpEth;
uint256 _potEth = _eth - _commEth - _jpEth;
pot += _potEth;
}
//if you really goof. send too little eth or betting is over it goes to admin
else {
comm += _eth;
}
}
function claimJackpot() public {
address payable _pAddr = msg.sender;
uint256 _jackpot = jackpot;
require(ended == true && checkJPotWinner(_pAddr) && !jPotclaimed);
_pAddr.transfer(_jackpot);
jPotclaimed = true;
jPotWinner = _pAddr;
}
function payMeBitch(uint256 _pck) public {
address payable _pAddr = msg.sender;
require(_pck >= 0 && _pck < 998);
require(ended == true && pAddrxBk[_pAddr][_pck].paid == false && pAddrxBk[_pAddr][_pck].share > 0 && wPck == _pck);
_pAddr.transfer(pAddrxBk[_pAddr][_pck].share * shareval);
pAddrxBk[_pAddr][_pck].paid = true;
}
//VIEW FUNCTIONS
function checkJPotWinner(address payable _pAddr) public view returns(bool){
uint256 _endblockhash = endblockhash;
uint256 _tShare = tShare;
uint256 _nend = nextJPot();
uint256 _wnum;
require(plyrJBk[_pAddr][0].eShare != 0);
if (jPotclaimed == true) {
return(false);
}
_endblockhash = uint256(keccak256(abi.encodePacked(_endblockhash + _nend)));
_wnum = (_endblockhash % _tShare);
for(uint256 i = 0; true; i++) {
if(plyrJBk[_pAddr][i].eShare == 0){
break;
}
else {
if (plyrJBk[_pAddr][i].sShare <= _wnum && plyrJBk[_pAddr][i].eShare >= _wnum ){
return(true);
}
}
}
return(false);
}
function nextJPot() public view returns(uint256) {
uint256 _cblock = block.number;
uint256 _jendblock = jendblock;
uint256 _tmp = (_cblock - _jendblock);
uint256 _nend = _jendblock + jpotinterval;
uint256 _c = 0;
if (jPotclaimed == true) {
return(0);
}
while(_tmp > ((_c + 1) * jpotinterval)) {
_c += 1;
}
_nend += jpotinterval * _c;
return(_nend);
}
//to view postitions on bet for specific address
function addressPicks(address _pAddr, uint256 _pck) public view returns(uint256) {
return(pAddrxBk[_pAddr][_pck].share);
}
//checks if an address has been paid
function addressPaid(address _pAddr, uint256 _pck) public view returns(bool) {
return(pAddrxBk[_pAddr][_pck].paid);
}
//get shares in pot for specified pick
function pickPot(uint256 _pck) public view returns(uint256) {
return(pBk[_pck].share);
}
//get number of bets for speficied pick
function pickPlyr(uint256 _pck) public view returns(uint256) {
return(pBk[_pck].nBet);
}
//gets the total pot
function getPot() public view returns(uint256) {
return(pot);
}
//gets the total jackpot
function getJPot() public view returns(uint256) {
return(jackpot);
}
//gets winning pick set by admin. Will return 999 prior to
function getWPck() public view returns(uint256) {
return(wPck);
}
function viewJPotclaimed() public view returns(bool) {
return(jPotclaimed);
}
function viewJPotWinner() public view returns(address) {
return(jPotWinner);
}
//grab the time betting is over
function getEndtime() public view returns(uint256) {
return(endtime);
}
//how much do they owe me?
function getComm() public view returns(uint256) {
return(comm);
}
function hasStarted() public view returns(bool) {
return(started);
}
function isOver() public view returns(bool) {
return(ended);
}
function pickRatio(uint256 _pck) public view returns(uint256) {
return(pot / pBk[_pck].share);
}
function checkTime() public view returns(bool) {
uint256 _now = now;
if (_now < endtime) {
return(false);
}
else {
return(true);
}
}
function testView(address _pAddr, uint256 _n) public view returns(uint256 sShare, uint256 eShare) {
return(plyrJBk[_pAddr][_n].sShare, plyrJBk[_pAddr][_n].eShare);
}
//ADMIN ONLY FUNCTIONS
function startYourEngines(uint256 _pcknum, uint256 _endtime) onlyAdministrator() public returns(bool){
require(!started);
pcknum = _pcknum;
endtime = _endtime;
started = true;
return(true);
}
function adminWinner(uint256 _wPck) onlyAdministrator() public {
require(_wPck <= pcknum && checkTime() && ended == false);
ended = true;
wPck = _wPck;
shareval = pot / pBk[_wPck].share;
endblock = block.number;
uint256 _jendblock = block.number;
jendblock = _jendblock;
endblockhash = uint256(keccak256(abi.encodePacked(blockhash(_jendblock - 200))));
}
function fuckYouPayMe() onlyAdministrator() public {
uint256 _commDue = comm - commPaid;
if (_commDue > 0) {
admin.transfer(_commDue);
commPaid += _commDue;
}
}
}
|
gets the total jackpot
|
function getJPot() public view returns(uint256) {
return(jackpot);
}
| 14,085,765 |
pragma solidity 0.4.16;
/**
* TODOs
* * 0x000 account gets nominated for voting constantly
* * Can not make a nomination with 1st label created for some reason (mb solidity has problems with 0 index elements???)
* * Voting throws errors constantly (maybe linked to next point)
* * How assigned voters supposed to know which nominations they can vote for? securely and privately
* * To get randomization element from offchain
* * Save lists of passed nominations label: [users] offchain
*/
contract owned {
address public owner;
function owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract Congress is owned {
string constant public VERSION = "0.0.3";
// Contract Variables and events
uint public minimumQuorum;
uint public debatingPeriodInMinutes;
int public majorityMargin;
Nomination[] public nominations;
uint public numNominations;
mapping (address => uint) memberId;
mapping (uint => address) memberIndex;
Member[] public members;
Label[] public labels;
mapping (string => uint) labelId;
event NominationAdded(uint nominationID, address recipient, string description);
event Voted(uint nominationID, bool position, address voter, string justification);
event NominationTallied(uint nominationID, int result, uint quorum, bool active);
event LabelAdded(string label, string description);
event MembershipChanged(address member, bool isMember);
event ChangeOfRules(uint newMinimumQuorum, uint newDebatingPeriodInMinutes, int newMajorityMargin);
// debugging [
event VoterAssigned(uint nominationID, address assignedVoter);
// debugging ]
struct Nomination {
address nominee;
string label;
string evidence;
uint votingDeadline;
bool executed;
bool nominationPassed;
uint numberOfVotes;
int currentResult;
bytes32 nominationHash;
Vote[] votes;
mapping (address => bool) voted;
address[] assignedVoters;
mapping (address => uint) assignedVotersMappig;
}
/*
struct AssignedVoters {
bytes32 nominationHash;
address voter;
}
*/
struct Label {
string name;
string description;
}
struct Member {
address member;
string name;
uint memberSince;
}
struct Vote {
bool inSupport;
address voter;
string justification;
}
// Modifier that allows only shareholders to vote
modifier onlyMembers {
require(memberId[msg.sender] != 0);
_;
}
/**
* Constructor function
*/
function Congress (
uint minimumQuorumForProposals,
uint minutesForDebate,
int marginOfVotesForMajority
) payable public {
changeVotingRules(minimumQuorumForProposals, minutesForDebate, marginOfVotesForMajority);
// It’s necessary to add an empty first member
addMember(0, "");
// and let's add the founder, to save a step later
addMember(owner, 'founder');
}
/**
* Add label
*
* @param label Label name
* @param labelDescription Label description
*/
function addLabel(string label, string labelDescription) onlyOwner public {
uint id = labelId[label];
if (id == 0) {
labelId[label] = labels.length;
id = labels.length++;
}
labels[id] = Label({name: label, description: labelDescription});
LabelAdded(label, labelDescription);
}
/**
* Add member
*
* Make `targetMember` a member named `memberName`
*
* @param targetMember ethereum address to be added
* @param memberName public name for that member
*/
function addMember(address targetMember, string memberName) onlyOwner public {
uint id = memberId[targetMember];
if (id == 0) {
memberId[targetMember] = members.length;
id = members.length++;
}
members[id] = Member({member: targetMember, memberSince: now, name: memberName});
MembershipChanged(targetMember, true);
}
/**
* Remove member
*
* @notice Remove membership from `targetMember`
*
* @param targetMember ethereum address to be removed
*/
function removeMember(address targetMember) onlyOwner public {
require(memberId[targetMember] != 0);
for (uint i = memberId[targetMember]; i<members.length-1; i++){
members[i] = members[i+1];
}
delete members[members.length-1];
members.length--;
}
/**
* Change voting rules
*
* Make so that proposals need tobe discussed for at least `minutesForDebate/60` hours,
* have at least `minimumQuorumForProposals` votes, and have 50% + `marginOfVotesForMajority` votes to be executed
*
* @param minimumQuorumForProposals how many members must vote on a proposal for it to be executed
* @param minutesForDebate the minimum amount of delay between when a proposal is made and when it can be executed
* @param marginOfVotesForMajority the proposal needs to have 50% plus this number
*/
function changeVotingRules(
uint minimumQuorumForProposals,
uint minutesForDebate,
int marginOfVotesForMajority
) onlyOwner public {
minimumQuorum = minimumQuorumForProposals;
debatingPeriodInMinutes = minutesForDebate;
majorityMargin = marginOfVotesForMajority;
ChangeOfRules(minimumQuorum, debatingPeriodInMinutes, majorityMargin);
}
/**
* Add Nomination
*
* Propose to send `weiAmount / 1e18` ether to `beneficiary` for `jobDescription`. `transactionBytecode ? Contains : Does not contain` code.
*
* @param nominee The one being labeled
* @param evidence Provide some evidence supporting the nomination
* @param transactionBytecode Bytecode of transaction
*/
function newNomination(
address nominee,
string label,
string evidence,
bytes transactionBytecode
)
// anyone can nominate anyone
public returns (uint nominationID)
{
require(labelId[label]!=0); // Only authorized labels allowed, cancel
require(bytes(evidence).length!=0); // Does not allow empty evidence, cancel
nominationID = nominations.length++;
Nomination storage n = nominations[nominationID];
n.nominee = nominee;
n.label = label;
n.evidence = evidence;
n.nominationHash = keccak256(nominee, transactionBytecode);
n.votingDeadline = now + debatingPeriodInMinutes * 1 minutes;
n.executed = false;
n.nominationPassed = false;
n.numberOfVotes = 0;
NominationAdded(nominationID, nominee, evidence);
numNominations = nominationID+1;
// 10 randomly selected people should vote on nomination
var usersToSelect = max(1, i-members.length/10);
for (uint i=members.length; i>0; i = i - usersToSelect) {
n.assignedVoters.push(memberIndex[i]);
n.assignedVotersMappig[memberIndex[i]] = 1;
VoterAssigned(nominationID, memberIndex[i]);
}
return nominationID;
}
function max(uint a, uint b) private returns (uint) {
return a > b ? a : b;
}
/**
* Check if a nomination code matches
*
* @param nominationNumber ID number of the nomination to query
* @param nominee The one being labeled
* @param transactionBytecode bytecode of transaction
*/
function checkNominationCode(
uint nominationNumber,
address nominee,
bytes transactionBytecode
)
constant public returns (bool codeChecksOut)
{
Nomination storage n = nominations[nominationNumber];
return n.nominationHash == keccak256(nominee, transactionBytecode);
}
/**
* Log a vote for a nomination
*
* Vote `supportsNomination? in support of : against` nomination #`nominationNumber`
*
* @param nominationNumber Number of nomination
* @param supportsNomination Either in favor or against it
* @param justificationText optional: justification text
*/
function vote(
uint nominationNumber,
bool supportsNomination,
string justificationText
)
onlyMembers public returns (uint voteID)
{
Nomination storage n = nominations[nominationNumber]; // Get the proposal
require(!n.voted[msg.sender]); // If has already voted, cancel
require(n.assignedVotersMappig[msg.sender]!=0); // Only randomly assigned voters can vote, cancel
n.voted[msg.sender] = true; // Set this voter as having voted
n.numberOfVotes++; // Increase the number of votes
if (supportsNomination) { // If they support the proposal
n.currentResult++; // Increase score
} else { // If they don't
n.currentResult--; // Decrease the score
}
// Create a log of this event
Voted(nominationNumber, supportsNomination, msg.sender, justificationText);
return n.numberOfVotes;
}
/**
* Finish vote
*
* Count the votes proposal #`nominationNumber` and execute it if approved
*
* @param nominationNumber Nomination number
* @param transactionBytecode optional: if the transaction contained a bytecode, you need to send it
*/
function executeProposal(uint nominationNumber, bytes transactionBytecode) public {
Nomination storage n = nominations[nominationNumber];
require(now > n.votingDeadline // If it is past the voting deadline
&& n.nominationHash == keccak256(n.nominee, transactionBytecode) // and the supplied code matches the proposal
&& n.numberOfVotes >= minimumQuorum); // and a minimum quorum has been reached...
// ...then execute result
if (n.currentResult > majorityMargin) {
// Proposal passed; execute the transaction
n.executed = true; // Avoid recursive calling
// TODO push to hextable
n.nominationPassed = true;
} else {
// Nomination failed
n.nominationPassed = false;
}
// Fire Events
NominationTallied(nominationNumber, n.currentResult, n.numberOfVotes, n.nominationPassed);
}
}
|
Constructor function/ It’s necessary to add an empty first member and let's add the founder, to save a step later
|
function Congress (
uint minimumQuorumForProposals,
uint minutesForDebate,
int marginOfVotesForMajority
) payable public {
changeVotingRules(minimumQuorumForProposals, minutesForDebate, marginOfVotesForMajority);
addMember(0, "");
addMember(owner, 'founder');
}
| 5,458,650 |
./full_match/1/0x54d194FaAe439fc3f8024801B0b9EBc91Ebd39f5/sources/lib/base-contracts/src/revenue-share/BalanceTracker.sol
|
/// Checks the balance of the target address and refills it back up to the target balance if needed. _systemAddress The system address being funded. _targetBalance The target balance for the system address being funded./
|
function refillBalanceIfNeeded(address _systemAddress, uint256 _targetBalance) internal {
uint256 systemAddressBalance = _systemAddress.balance;
if (systemAddressBalance >= _targetBalance) {
emit ProcessedFunds(_systemAddress, false, 0, 0);
return;
}
uint256 valueNeeded = _targetBalance - systemAddressBalance;
uint256 balanceTrackerBalance = address(this).balance;
uint256 valueToSend = valueNeeded > balanceTrackerBalance ? balanceTrackerBalance : valueNeeded;
bool success = SafeCall.send(_systemAddress, gasleft(), valueToSend);
emit ProcessedFunds(_systemAddress, success, valueNeeded, valueToSend);
}
| 2,977,963 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/Extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
contract SimU is ERC721Enumerable, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIdTracker;
address private _proxyRegistryAddress;
string private _sharedBaseURI;
bool private _licenseChecksumLocked;
bool private _metadataURILocked;
bool private _delegateMinterRequired;
// Allows more options on how metadata URI can be stored. Overrides default
// baseURI based approach.
mapping(uint256 => string) private _tokenMetadataURI;
mapping(address => bool) private _delegates;
string public metadataChecksum;
string public license;
uint256 public mintReserve;
constructor(string memory name_, string memory symbol_)
ERC721(name_, symbol_)
{
_sharedBaseURI = "https://www.simulateduniversenft.com/api/metadata/";
metadataChecksum = "e0821490b282d7d1666b96f60b6fcbb31942f238c7098d4490e7c9fb111e0c9788d29ad84912f702aea48f6d928e557a1ecbf9ddfdf5c5f9ffd65ea58fb3b042";
license = "As long as you hold the NFT, you are granted MIT license to the universe' metadata in its entirety.";
_licenseChecksumLocked = false;
_metadataURILocked = false;
// Start with 1.
_tokenIdTracker.increment();
_delegateMinterRequired = true;
mintReserve = 1000;
}
/**
* @dev Premenately locks license and checksum updates.
*/
function lockLicenseAndChecksum() external onlyOwner {
_licenseChecksumLocked = true;
emit LicenseAndChecksumLocked();
}
/**
* @dev Permenantely locks metadataURI.
*/
function lockMetadataURI() external onlyOwner {
_metadataURILocked = true;
emit MetadataURILocked();
}
/**
* @dev Whether delegate role is required to mint.
*/
function updateDelegateMinterRequired(bool required) external onlyOwner {
_delegateMinterRequired = required;
}
/**
* @dev Update the reserve allocation.
*/
function updateMintReserve(uint256 reserve) external onlyOwner {
mintReserve = reserve;
}
/**
* @dev Override baseURI based metadata URI.
*/
function updateMetadataURI(uint256 tokenId, string memory metadataURI)
external
{
require(_delegates[_msgSender()] == true, "Not authorized");
require(_metadataURILocked == false, "Operation locked");
_tokenMetadataURI[tokenId] = metadataURI;
}
/**
* @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 updateBaseURI(string memory baseURI) external onlyOwner {
require(_metadataURILocked == false, "Operation locked");
_sharedBaseURI = baseURI;
}
/**
* @dev Allows license polishing until functionaly is locked up.
*/
function updateLicense(string memory theLicense) external onlyOwner {
require(_licenseChecksumLocked == false, "Operation locked");
license = theLicense;
}
/**
* @dev Allows bug fixing until the functionality is locked up.
*/
function updateMetadataSha512(string memory checksum) external onlyOwner {
require(_licenseChecksumLocked == false, "Operation locked");
metadataChecksum = checksum;
}
/**
* @dev Add a delegate.
*/
function addDelegate(address delegate) external onlyOwner {
require(delegate != address(0), "0 address not allowed");
_delegates[delegate] = true;
}
/**
* @dev Remove a delegate.
*/
function removeDelegate(address delegate) external onlyOwner {
delete _delegates[delegate];
}
/**
* @dev Update proxy registry address.
*/
function updateProxyRegisteryAddress(address anAddress) external onlyOwner {
_proxyRegistryAddress = anAddress;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "Nonexistent token");
if (bytes(_tokenMetadataURI[tokenId]).length > 0) {
return _tokenMetadataURI[tokenId];
}
return
bytes(_sharedBaseURI).length > 0
? string(abi.encodePacked(_sharedBaseURI, tokenId.toString()))
: "";
}
function mint(address toAddress) external {
if (_delegateMinterRequired) {
require(_delegates[_msgSender()] == true, "Not authorized");
}
require(totalSupply() < 10000 - mintReserve, "Mint cap reached");
_mint(toAddress, _tokenIdTracker.current());
_tokenIdTracker.increment();
}
/**
* @dev Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
if (_proxyRegistryAddress != address(0)) {
ProxyRegistry proxyRegistry = ProxyRegistry(_proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
}
return super.isApprovedForAll(owner, operator);
}
event LicenseAndChecksumLocked();
event MetadataURILocked();
}
// 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 "./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 "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
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
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;
/**
* @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;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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);
}
|
Allows bug fixing until the functionality is locked up./
|
function updateMetadataSha512(string memory checksum) external onlyOwner {
require(_licenseChecksumLocked == false, "Operation locked");
metadataChecksum = checksum;
}
| 352,828 |
/**
*Submitted for verification at Etherscan.io on 2021-08-02
*/
/// AutoRewardDripper.sol
// Copyright (C) 2021 Reflexer Labs, INC
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
pragma solidity 0.6.7;
abstract contract TokenLike {
function balanceOf(address) virtual public view returns (uint256);
function transfer(address, uint256) virtual external returns (bool);
}
contract AutoRewardDripper {
// --- Auth ---
mapping (address => uint) public authorizedAccounts;
/**
* @notice Add auth to an account
* @param account Account to add auth to
*/
function addAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 1;
emit AddAuthorization(account);
}
/**
* @notice Remove auth from an account
* @param account Account to remove auth from
*/
function removeAuthorization(address account) virtual external isAuthorized {
authorizedAccounts[account] = 0;
emit RemoveAuthorization(account);
}
/**
* @notice Checks whether msg.sender can call an authed function
**/
modifier isAuthorized {
require(authorizedAccounts[msg.sender] == 1, "AutoRewardDripper/account-not-authorized");
_;
}
// --- Variables ---
// Last block when a reward was given
uint256 public lastRewardBlock;
// Amount of tokens distributed per block
uint256 public rewardPerBlock;
// The timeline (in number of blocks) used to calculate rewardPerBlock
uint256 public rewardTimeline;
// Last time when the reward was calculated
uint256 public lastRewardCalculation;
// Delay between reward calculations
uint256 public rewardCalculationDelay;
// The address that can request rewards
address public requestor;
// The reward token being distributed
TokenLike public rewardToken;
uint256 public constant MAX_REWARD_TIMELINE = 2250000;
// --- Events ---
event AddAuthorization(address account);
event RemoveAuthorization(address account);
event ModifyParameters(bytes32 indexed parameter, uint256 data);
event ModifyParameters(bytes32 indexed parameter, address data);
event DripReward(address requestor, uint256 amountToTransfer);
event TransferTokenOut(address dst, uint256 amount);
event RecomputePerBlockReward(uint256 rewardPerBlock);
constructor(
address requestor_,
address rewardToken_,
uint256 rewardTimeline_,
uint256 rewardCalculationDelay_
) public {
require(requestor_ != address(0), "AutoRewardDripper/null-requoestor");
require(rewardToken_ != address(0), "AutoRewardDripper/null-reward-token");
require(rewardTimeline_ > 0, "AutoRewardDripper/null-reward-time");
require(rewardTimeline_ <= MAX_REWARD_TIMELINE, "AutoRewardDripper/high-reward-timeline");
require(rewardCalculationDelay_ > 0, "AutoRewardDripper/null-reward-calc-delay");
authorizedAccounts[msg.sender] = 1;
rewardTimeline = rewardTimeline_;
requestor = requestor_;
rewardCalculationDelay = rewardCalculationDelay_;
rewardToken = TokenLike(rewardToken_);
lastRewardBlock = block.number;
emit AddAuthorization(msg.sender);
emit ModifyParameters("rewardTimeline", rewardTimeline);
emit ModifyParameters("rewardCalculationDelay", rewardCalculationDelay);
emit ModifyParameters("requestor", requestor);
emit ModifyParameters("lastRewardBlock", lastRewardBlock);
}
// --- Boolean ---
function either(bool x, bool y) internal pure returns (bool z) {
assembly{ z := or(x, y)}
}
// --- Math ---
function subtract(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x - y) <= x, "AutoRewardDripper/sub-underflow");
}
function multiply(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "AutoRewardDripper/mul-overflow");
}
// --- Administration ---
/*
* @notify Modify an uint256 parameter
* @param parameter The name of the parameter to modify
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, uint256 data) external isAuthorized {
if (parameter == "lastRewardBlock") {
require(data >= block.number, "AutoRewardDripper/invalid-last-reward-block");
lastRewardBlock = data;
} else if (parameter == "rewardPerBlock") {
require(data > 0, "AutoRewardDripper/invalid-reward-per-block");
rewardPerBlock = data;
} else if (parameter == "rewardCalculationDelay") {
require(data > 0, "AutoRewardDripper/invalid-reward-calculation-delay");
rewardCalculationDelay = data;
} else if (parameter == "rewardTimeline") {
require(data > 0 && data <= MAX_REWARD_TIMELINE, "AutoRewardDripper/invalid-reward-timeline");
rewardTimeline = data;
}
else revert("AutoRewardDripper/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
/*
* @notify Modify an address parameter
* @param parameter The name of the parameter to modify
* @param data New value for the parameter
*/
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "AutoRewardDripper/null-data");
if (parameter == "requestor") {
requestor = data;
}
else revert("AutoRewardDripper/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
// --- Core Logic ---
/*
* @notice Transfer tokens to a custom address
* @param dst The destination address for the tokens
* @param amount The amount of tokens transferred
*/
function transferTokenOut(address dst, uint256 amount) external isAuthorized {
require(dst != address(0), "AutoRewardDripper/null-dst");
require(amount > 0, "AutoRewardDripper/null-amount");
require(rewardToken.transfer(dst, amount), "AutoRewardDripper/failed-transfer");
emit TransferTokenOut(dst, amount);
}
/*
* @notify Send rewards to the requestor
*/
function dripReward() external {
dripReward(msg.sender);
}
/*
* @notify Recompute rewardPerBlock
*/
function recomputePerBlockReward() public {
uint256 remainingBalance = rewardToken.balanceOf(address(this));
if (either(remainingBalance == 0, subtract(now, lastRewardCalculation) < rewardCalculationDelay)) return;
lastRewardCalculation = now;
rewardPerBlock = (rewardTimeline >= remainingBalance) ? remainingBalance : remainingBalance / rewardTimeline;
emit RecomputePerBlockReward(rewardPerBlock);
}
/*
* @notify Send rewards to an address defined by the requestor
*/
function dripReward(address to) public {
if (lastRewardBlock >= block.number) return;
require(msg.sender == requestor, "AutoRewardDripper/invalid-caller");
uint256 remainingBalance = rewardToken.balanceOf(address(this));
uint256 amountToTransfer = multiply(subtract(block.number, lastRewardBlock), rewardPerBlock);
amountToTransfer = (amountToTransfer > remainingBalance) ? remainingBalance : amountToTransfer;
lastRewardBlock = block.number;
recomputePerBlockReward();
if (amountToTransfer == 0) return;
require(rewardToken.transfer(to, amountToTransfer), "AutoRewardDripper/failed-transfer");
emit DripReward(to, amountToTransfer);
}
}
|
@notify Modify an address parameter parameter The name of the parameter to modify data New value for the parameter/
|
function modifyParameters(bytes32 parameter, address data) external isAuthorized {
require(data != address(0), "AutoRewardDripper/null-data");
if (parameter == "requestor") {
requestor = data;
}
else revert("AutoRewardDripper/modify-unrecognized-param");
emit ModifyParameters(parameter, data);
}
| 7,686,734 |
./full_match/3/0xEaAc1538556896da8f627C56196f4965cadA45C5/sources/contracts/StakingTokenByPeriod.sol
|
A method to send tokens from the retailer to the customer. retailer The retailer address. customer The customer address. tokens The amount of tokens to send./
|
function sendTokensFromRetailerToCustomer(address retailer, address customer, uint256 tokens) public {
increaseAllowance(retailer, tokens * 10 ** uint256(decimals()));
ERC20.transferFrom(retailer, customer, tokens * 10 ** uint256(decimals()));
updateRewardableBalancePerAddress(customer);
updateRewardableBalancePerAddress(retailer);
}
| 8,274,460 |
// File: contracts/lib/interface/ICelerWallet.sol
pragma solidity ^0.5.1;
/**
* @title CelerWallet interface
*/
interface ICelerWallet {
function create(address[] calldata _owners, address _operator, bytes32 _nonce) external returns(bytes32);
function depositETH(bytes32 _walletId) external payable;
function depositERC20(bytes32 _walletId, address _tokenAddress, uint _amount) external;
function withdraw(bytes32 _walletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferToWallet(bytes32 _fromWalletId, bytes32 _toWalletId, address _tokenAddress, address _receiver, uint _amount) external;
function transferOperatorship(bytes32 _walletId, address _newOperator) external;
function proposeNewOperator(bytes32 _walletId, address _newOperator) external;
function drainToken(address _tokenAddress, address _receiver, uint _amount) external;
function getWalletOwners(bytes32 _walletId) external view returns(address[] memory);
function getOperator(bytes32 _walletId) external view returns(address);
function getBalance(bytes32 _walletId, address _tokenAddress) external view returns(uint);
function getProposedNewOperator(bytes32 _walletId) external view returns(address);
function getProposalVote(bytes32 _walletId, address _owner) external view returns(bool);
event CreateWallet(bytes32 indexed walletId, address[] indexed owners, address indexed operator);
event DepositToWallet(bytes32 indexed walletId, address indexed tokenAddress, uint amount);
event WithdrawFromWallet(bytes32 indexed walletId, address indexed tokenAddress, address indexed receiver, uint amount);
event TransferToWallet(bytes32 indexed fromWalletId, bytes32 indexed toWalletId, address indexed tokenAddress, address receiver, uint amount);
event ChangeOperator(bytes32 indexed walletId, address indexed oldOperator, address indexed newOperator);
event ProposeNewOperator(bytes32 indexed walletId, address indexed newOperator, address indexed proposer);
event DrainToken(address indexed tokenAddress, address indexed receiver, uint amount);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @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 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(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'
require((value == 0) || (token.allowance(msg.sender, spender) == 0));
require(token.approve(spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance));
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an account access to this role
*/
function add(Role storage role, address account) internal {
require(account != address(0));
require(!has(role, account));
role.bearer[account] = true;
}
/**
* @dev remove an account's access to this role
*/
function remove(Role storage role, address account) internal {
require(account != address(0));
require(has(role, account));
role.bearer[account] = false;
}
/**
* @dev check if an account has this role
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0));
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender));
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is PauserRole {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor () internal {
_paused = false;
}
/**
* @return true if the contract is paused, 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);
_;
}
/**
* @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() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: contracts/CelerWallet.sol
pragma solidity ^0.5.1;
/**
* @title CelerWallet contract
* @notice A multi-owner, multi-token, operator-centric wallet designed for CelerChannel.
* This wallet can run independetly and doesn't rely on trust of any external contracts
* even CelerLedger to maximize its security.
*/
contract CelerWallet is ICelerWallet, Pausable {
using SafeMath for uint;
using SafeERC20 for IERC20;
enum MathOperation { Add, Sub }
struct Wallet {
// corresponding to peers in CelerLedger
address[] owners;
// corresponding to CelerLedger
address operator;
// adderss(0) for ETH
mapping(address => uint) balances;
address proposedNewOperator;
mapping(address => bool) proposalVotes;
}
uint public walletNum;
mapping(bytes32 => Wallet) private wallets;
/**
* @dev Throws if called by any account other than the wallet's operator
* @param _walletId id of the wallet to be operated
*/
modifier onlyOperator(bytes32 _walletId) {
require(msg.sender == wallets[_walletId].operator, "msg.sender is not operator");
_;
}
/**
* @dev Throws if given address is not an owner of the wallet
* @param _walletId id of the wallet to be operated
* @param _addr address to be checked
*/
modifier onlyWalletOwner(bytes32 _walletId, address _addr) {
require(_isWalletOwner(_walletId, _addr), "Given address is not wallet owner");
_;
}
/**
* @notice Create a new wallet
* @param _owners owners of the wallet
* @param _operator initial operator of the wallet
* @param _nonce nonce given by caller to generate the wallet id
* @return id of created wallet
*/
function create(
address[] memory _owners,
address _operator,
bytes32 _nonce
)
public
whenNotPaused
returns(bytes32)
{
require(_operator != address(0), "New operator is address(0)");
bytes32 walletId = keccak256(abi.encodePacked(address(this), msg.sender, _nonce));
Wallet storage w = wallets[walletId];
// wallet must be uninitialized
require(w.operator == address(0), "Occupied wallet id");
w.owners = _owners;
w.operator = _operator;
walletNum++;
emit CreateWallet(walletId, _owners, _operator);
return walletId;
}
/**
* @notice Deposit ETH to a wallet
* @param _walletId id of the wallet to deposit into
*/
function depositETH(bytes32 _walletId) public payable whenNotPaused {
uint amount = msg.value;
_updateBalance(_walletId, address(0), amount, MathOperation.Add);
emit DepositToWallet(_walletId, address(0), amount);
}
/**
* @notice Deposit ERC20 tokens to a wallet
* @param _walletId id of the wallet to deposit into
* @param _tokenAddress address of token to deposit
* @param _amount deposit token amount
*/
function depositERC20(
bytes32 _walletId,
address _tokenAddress,
uint _amount
)
public
whenNotPaused
{
_updateBalance(_walletId, _tokenAddress, _amount, MathOperation.Add);
emit DepositToWallet(_walletId, _tokenAddress, _amount);
IERC20(_tokenAddress).safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @notice Withdraw funds to an address
* @dev Since this withdraw() function uses direct transfer to send ETH, if CelerLedger
* allows non externally-owned account (EOA) to be a peer of the channel namely an owner
* of the wallet, CelerLedger should implement a withdraw pattern for ETH to avoid
* maliciously fund locking. Withdraw pattern reference:
* https://solidity.readthedocs.io/en/v0.5.9/common-patterns.html#withdrawal-from-contracts
* @param _walletId id of the wallet to withdraw from
* @param _tokenAddress address of token to withdraw
* @param _receiver token receiver
* @param _amount withdrawal token amount
*/
function withdraw(
bytes32 _walletId,
address _tokenAddress,
address _receiver,
uint _amount
)
public
whenNotPaused
onlyOperator(_walletId)
onlyWalletOwner(_walletId, _receiver)
{
_updateBalance(_walletId, _tokenAddress, _amount, MathOperation.Sub);
emit WithdrawFromWallet(_walletId, _tokenAddress, _receiver, _amount);
_withdrawToken(_tokenAddress, _receiver, _amount);
}
/**
* @notice Transfer funds from one wallet to another wallet with a same owner (as the receiver)
* @dev from wallet and to wallet must have one common owner as the receiver or beneficiary
* of this transfer
* @param _fromWalletId id of wallet to transfer funds from
* @param _toWalletId id of wallet to transfer funds to
* @param _tokenAddress address of token to transfer
* @param _receiver beneficiary who transfers her funds from one wallet to another wallet
* @param _amount transferred token amount
*/
function transferToWallet(
bytes32 _fromWalletId,
bytes32 _toWalletId,
address _tokenAddress,
address _receiver,
uint _amount
)
public
whenNotPaused
onlyOperator(_fromWalletId)
onlyWalletOwner(_fromWalletId, _receiver)
onlyWalletOwner(_toWalletId, _receiver)
{
_updateBalance(_fromWalletId, _tokenAddress, _amount, MathOperation.Sub);
_updateBalance(_toWalletId, _tokenAddress, _amount, MathOperation.Add);
emit TransferToWallet(_fromWalletId, _toWalletId, _tokenAddress, _receiver, _amount);
}
/**
* @notice Current operator transfers the operatorship of a wallet to the new operator
* @param _walletId id of wallet to transfer the operatorship
* @param _newOperator the new operator
*/
function transferOperatorship(
bytes32 _walletId,
address _newOperator
)
public
whenNotPaused
onlyOperator(_walletId)
{
_changeOperator(_walletId, _newOperator);
}
/**
* @notice Wallet owners propose and assign a new operator of their wallet
* @dev it will assign a new operator if all owners propose the same new operator.
* This does not require unpaused.
* @param _walletId id of wallet which owners propose new operator of
* @param _newOperator the new operator proposal
*/
function proposeNewOperator(
bytes32 _walletId,
address _newOperator
)
public
onlyWalletOwner(_walletId, msg.sender)
{
require(_newOperator != address(0), "New operator is address(0)");
Wallet storage w = wallets[_walletId];
if (_newOperator != w.proposedNewOperator) {
_clearVotes(w);
w.proposedNewOperator = _newOperator;
}
w.proposalVotes[msg.sender] = true;
emit ProposeNewOperator(_walletId, _newOperator, msg.sender);
if (_checkAllVotes(w)) {
_changeOperator(_walletId, _newOperator);
_clearVotes(w);
}
}
/**
* @notice Pauser drains one type of tokens when paused
* @dev This is for emergency situations.
* @param _tokenAddress address of token to drain
* @param _receiver token receiver
* @param _amount drained token amount
*/
function drainToken(
address _tokenAddress,
address _receiver,
uint _amount
)
public
whenPaused
onlyPauser
{
emit DrainToken(_tokenAddress, _receiver, _amount);
_withdrawToken(_tokenAddress, _receiver, _amount);
}
/**
* @notice Get owners of a given wallet
* @param _walletId id of the queried wallet
* @return wallet's owners
*/
function getWalletOwners(bytes32 _walletId) external view returns(address[] memory) {
return wallets[_walletId].owners;
}
/**
* @notice Get operator of a given wallet
* @param _walletId id of the queried wallet
* @return wallet's operator
*/
function getOperator(bytes32 _walletId) public view returns(address) {
return wallets[_walletId].operator;
}
/**
* @notice Get balance of a given token in a given wallet
* @param _walletId id of the queried wallet
* @param _tokenAddress address of the queried token
* @return amount of the given token in the wallet
*/
function getBalance(bytes32 _walletId, address _tokenAddress) public view returns(uint) {
return wallets[_walletId].balances[_tokenAddress];
}
/**
* @notice Get proposedNewOperator of a given wallet
* @param _walletId id of the queried wallet
* @return wallet's proposedNewOperator
*/
function getProposedNewOperator(bytes32 _walletId) external view returns(address) {
return wallets[_walletId].proposedNewOperator;
}
/**
* @notice Get the vote of an owner for the proposedNewOperator of a wallet
* @param _walletId id of the queried wallet
* @param _owner owner to be checked
* @return the owner's vote for the proposedNewOperator
*/
function getProposalVote(
bytes32 _walletId,
address _owner
)
external
view
onlyWalletOwner(_walletId, _owner)
returns(bool)
{
return wallets[_walletId].proposalVotes[_owner];
}
/**
* @notice Internal function to withdraw out one type of token
* @param _tokenAddress address of token to withdraw
* @param _receiver token receiver
* @param _amount withdrawal token amount
*/
function _withdrawToken(address _tokenAddress, address _receiver, uint _amount) internal {
if (_tokenAddress == address(0)) {
// convert from address to address payable
// TODO: latest version of openzeppelin Address.sol provide this api toPayable()
address payable receiver = address(uint160(_receiver));
receiver.transfer(_amount);
} else {
IERC20(_tokenAddress).safeTransfer(_receiver, _amount);
}
}
/**
* @notice Update balance record
* @param _walletId id of wallet to update
* @param _tokenAddress address of token to update
* @param _amount update amount
* @param _op update operation
*/
function _updateBalance(
bytes32 _walletId,
address _tokenAddress,
uint _amount,
MathOperation _op
)
internal
{
Wallet storage w = wallets[_walletId];
if (_op == MathOperation.Add) {
w.balances[_tokenAddress] = w.balances[_tokenAddress].add(_amount);
} else if (_op == MathOperation.Sub) {
w.balances[_tokenAddress] = w.balances[_tokenAddress].sub(_amount);
} else {
assert(false);
}
}
/**
* @notice Clear all votes of new operator proposals of the wallet
* @param _w the wallet
*/
function _clearVotes(Wallet storage _w) internal {
for (uint i = 0; i < _w.owners.length; i++) {
_w.proposalVotes[_w.owners[i]] = false;
}
}
/**
* @notice Internal function of changing the operator of a wallet
* @param _walletId id of wallet to change its operator
* @param _newOperator the new operator
*/
function _changeOperator(bytes32 _walletId, address _newOperator) internal {
require(_newOperator != address(0), "New operator is address(0)");
Wallet storage w = wallets[_walletId];
address oldOperator = w.operator;
w.operator = _newOperator;
emit ChangeOperator(_walletId, oldOperator, _newOperator);
}
/**
* @notice Check if all owners have voted for the same new operator
* @param _w the wallet
* @return true if all owners have voted for a same operator; otherwise false
*/
function _checkAllVotes(Wallet storage _w) internal view returns(bool) {
for (uint i = 0; i < _w.owners.length; i++) {
if (_w.proposalVotes[_w.owners[i]] == false) {
return false;
}
}
return true;
}
/**
* @notice Check if an address is an owner of a wallet
* @param _walletId id of wallet to check
* @param _addr address to check
* @return true if this address is an owner of the wallet; otherwise false
*/
function _isWalletOwner(bytes32 _walletId, address _addr) internal view returns(bool) {
Wallet storage w = wallets[_walletId];
for (uint i = 0; i < w.owners.length; i++) {
if (_addr == w.owners[i]) {
return true;
}
}
return false;
}
}
|
Check if an address is an owner of a wallet _walletId id of wallet to check _addr address to check return true if this address is an owner of the wallet; otherwise false/
|
function _isWalletOwner(bytes32 _walletId, address _addr) internal view returns(bool) {
Wallet storage w = wallets[_walletId];
for (uint i = 0; i < w.owners.length; i++) {
if (_addr == w.owners[i]) {
return true;
}
}
return false;
}
| 12,188,514 |
./partial_match/1/0x7Cc46CF6392ed9DB45351A3F82EB2Cc3b83Da761/sources/erc721a/contracts/ERC721A.sol
|
Equivalent to `_burn(tokenId, false)`./
|
function _burn(uint256 tokenId) internal virtual {
_burn(tokenId, true);
}
| 3,572,195 |
./full_match/11155111/0x7228dcd460E7aA341aD3959cC5f6385c6b77a7ff/sources/contracts/f1rtunaMarketplace.sol
|
Internal function we'll use to shift money around
|
function payTo(address to, uint256 amount) internal {
require(success);
}
| 3,786,969 |
pragma solidity ^0.4.24;
import "./tokens/SafeERC20.sol";
import "./math/SafeMath.sol";
contract HodlContract {
uint multiplier = 10 ** 18;
using SafeERC20 for IERC20;
using SafeMath for uint256;
// ERC20 basic token contract being held
IERC20 private _token;
// beneficiary of tokens after they are released
address private _beneficiary;
// timestamp when token release is enabled
uint256 private _releaseTime;
constructor(
IERC20 token,
address beneficiary,
uint256 releaseTime
)
public
{
// solium-disable-next-line security/no-block-members
require(releaseTime > block.timestamp);
_token = token;
_beneficiary = beneficiary;
_releaseTime = releaseTime;
}
/**
* @return the token being held.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns(address) {
return _beneficiary;
}
/**
* @return the time when the tokens are released.
*/
function releaseTime() public view returns(uint256) {
return _releaseTime;
}
function allInfo() public view returns(address, address, uint256, uint256) {
return (_token, _beneficiary, _releaseTime, _token.balanceOf(address(this)).div(multiplier));
}
/**
* @notice Transfers tokens held by
* timelock to beneficiary.
* User gains reward in Wei.
* Reward is for keeping tokens in contract
* beyond the expiry time.
*/
function postRelease() public {
//only the beneficiary can unlock
require(tx.origin == _beneficiary);
//don't call this without reason, or no gas refunded.
assert(block.timestamp >= _releaseTime);
uint256 timeGainedinSeconds = block.timestamp - _releaseTime;
// 1 wei per 1 second per 1 token held
uint256 weiGained = _token.balanceOf(address(this)).div(multiplier) * timeGainedinSeconds * 1;
//send wei gained else throw if error
require(_beneficiary.call.gas(210000).value(weiGained)());
transfer();
}
/**
* called when user wants to get their tokens back,
* before the release time (_releaseTime)
* User pays a fine in wei for early
* release of the tokens.
*/
function preRelease() public payable {
//request should come from beneficiary
require(tx.origin == _beneficiary);
//don't call this without reason, or no gas refunded.
assert(block.timestamp <= _releaseTime);
uint256 timeEarly = _releaseTime - block.timestamp;
// 1 wei per 1 second per 1 token held
uint256 weiToBeFined = _token.balanceOf(address(this)).div(multiplier) * timeEarly * 1;
require(msg.value >= weiToBeFined);
transfer();
}
/*
* Private function for transferring all
* ERC20 tokens associated with this contract,
* from the contract to the _beneficiary.
*/
function transfer() private {
uint256 amount = _token.balanceOf(address(this));
require(amount > 0); //<--becoming false
_token.safeTransfer(_beneficiary, amount);
}
//function to collect all incoming wei
function() public payable {
}
}
|
return the time when the tokens are released./
|
function releaseTime() public view returns(uint256) {
return _releaseTime;
}
| 12,657,095 |
/*
Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity >=0.7.0;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "./interfaces/IUTokensV2.sol";
import "./interfaces/IHolderV2.sol";
import "./interfaces/ISTokensV2.sol";
import "./interfaces/IStakeLP.sol";
import "./libraries/TransferHelper.sol";
import "./libraries/FullMath.sol";
import "./interfaces/IWhitelistedPTokenEmission.sol";
import "./interfaces/IWhitelistedRewardEmission.sol";
contract StakeLP is
IStakeLP,
PausableUpgradeable,
AccessControlUpgradeable,
ReentrancyGuardUpgradeable
{
using SafeMathUpgradeable for uint256;
using FullMath for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// constant pertaining to access roles
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// valueDivisor to store fractional values for various reward attributes like _rewardTokenEmission
uint256 public _valueDivisor;
// variable pertaining to contract upgrades versioning
uint256 public _version;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// VARIABLES PERTAINING TO CALCULATION OF LPTIMESHARE
// balance of user, for an LP Token
mapping(address => mapping(address => uint256)) public _lpBalance;
// supply of LP tokens reserve, for an LP Token
mapping(address => uint256) public _lpSupply;
// last updated total LPTimeShare, for an LP Token
mapping(address => uint256) public _lastLPTimeShare;
// last recorded timestamp when user's LPTimeShare was updated, for a user, for an LP Token
mapping(address => mapping(address => uint256))
public _lastLiquidityTimestamp;
// -------------------------------------------------------------------------
// -------------------------------------------------------------------------
// required to store the whitelisting holder logic data for PToken rewards, initiated from WhitelistedEmission contract
address public _whitelistedPTokenEmissionContract;
// required to store the whitelisting holder logic data for other rewards, initiated from WhitelistedEmission contract
address public _whitelistedRewardEmissionContract;
/**
* @dev Constructor for initializing the stakeLP contract.
* @param pauserAddress - address of the pauser admin.
* @param whitelistedPTokenEmissionContract - address of whitelistedPTokenEmission Contract.
* @param whitelistedRewardEmissionContract - address of whitelistedPTokenEmission Contract.
* @param valueDivisor - valueDivisor set to 10^9.
*/
function initialize(
address pauserAddress,
address whitelistedPTokenEmissionContract,
address whitelistedRewardEmissionContract,
uint256 valueDivisor
) public virtual initializer {
__AccessControl_init();
__Pausable_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, pauserAddress);
_whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract;
_whitelistedRewardEmissionContract = whitelistedRewardEmissionContract;
_valueDivisor = valueDivisor;
}
/*
* @dev calculate liquidity and reward tokens and disburse to user
* @param holderAddress: holder contract address
* @param accountAddress: user address
*/
function calculatePendingRewards(
address holderAddress,
address accountAddress
)
public
view
virtual
override
returns (
uint256[] memory rewardAmounts,
address[] memory rewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress,
uint256 updatedSupplyLPTimeshare,
uint256 newSupplyLPTimeShare
)
{
uint256 _userLPTimeShare;
uint256 _totalSupplyLPTimeShare;
uint256[] memory holderRewards;
// CALCULTE LP TOKEN RATIOS OF USER AND SUPPLY
// CALCULATE PTOKENS REWARD EMISSION - CALCULATE (NOT TRIGGER) HOLDER REWARDS
// CALCULATE PTOKENS REWARD SHARE OF USER - CALCULATE (NOT TRIGGER) REWARD CALC OF PTOKENS
// CALCULATE OTHER REWARDS EMISSION - CALCULATE (NOT TRIGGER) OTHER PENDING REWARDS
// CALCULATE OTHER REWARDS SHARE OF USER - CALCULATE (NOT TRIGGER) REWARD CALC OF OTHER TOKENS
(
holderRewards,
sTokenAddresses,
,
lpTokenAddress
) = IWhitelistedPTokenEmission(_whitelistedPTokenEmissionContract)
.calculateAllPendingHolderRewards(holderAddress);
if (
holderAddress == address(0) ||
lpTokenAddress == address(0) ||
accountAddress == address(0)
) {
return (
rewardAmounts,
rewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
);
}
// calculate the new LPTimeShare of the user's LP Token
_userLPTimeShare = (
(_lpBalance[lpTokenAddress][accountAddress]).mul(
block.timestamp.sub(
_lastLiquidityTimestamp[lpTokenAddress][accountAddress]
)
)
);
// calculate the new LPTimeShare of the sum of supply of all LP Tokens
newSupplyLPTimeShare = (
(_lpSupply[lpTokenAddress]).mul(
block.timestamp.sub(
IWhitelistedRewardEmission(
_whitelistedRewardEmissionContract
).getLastLPTimeShareTimestamp(lpTokenAddress)
)
)
);
// calculate the totalSupplyLPTimeShare by adding new LPTimeShare to the existing share
_totalSupplyLPTimeShare = _lastLPTimeShare[lpTokenAddress].add(
newSupplyLPTimeShare
);
// calculate the remaining LPTimeShare of the total supply after the tokens for the user has been dispatched
updatedSupplyLPTimeshare = _totalSupplyLPTimeShare.sub(
_userLPTimeShare
);
// calculate the amounts and token contracts of other reward tokens
(
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
) = IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.calculateOtherPendingRewards(
holderAddress,
lpTokenAddress,
accountAddress,
_userLPTimeShare,
newSupplyLPTimeShare
);
(rewardAmounts, rewardTokens) = _getRewardData(
holderAddress,
sTokenAddresses,
holderRewards,
_userLPTimeShare,
_totalSupplyLPTimeShare,
otherRewardAmounts,
otherRewardTokens
);
}
/*
* @dev get liquidity and reward tokens and disburse to user
* @param holderAddress: holder contract address
* @param sTokenAddresses: sToken contract address in array
* @param holderRewards: holder contract address in array
* @param userLPTimeShare: user LP timeshare
* @param totalSupplyLPTimeShare: total supply LP timeshare
* @param otherRewardAmounts: reward amount in array
* @param otherRewardTokens: reward tokens in array
*/
function _getRewardData(
address holderAddress,
address[] memory sTokenAddresses,
uint256[] memory holderRewards,
uint256 userLPTimeShare,
uint256 totalSupplyLPTimeShare,
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
)
internal
view
returns (uint256[] memory rewardAmounts, address[] memory rewardTokens)
{
uint256 i;
uint256 rewardPool;
// initialize rewardAmounts and rewardTokens as per the sum of the size of pSTAKE and other rewards
rewardAmounts = new uint256[](
(otherRewardAmounts.length).add(sTokenAddresses.length)
);
rewardTokens = new address[](
(otherRewardTokens.length).add(sTokenAddresses.length)
);
// CALCULATE REWARD FOR EACH UTOKEN ADDRESS
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
rewardTokens[i] = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
// uTokenAddress = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
if (totalSupplyLPTimeShare > 0) {
// calculated the updated rewardPool
rewardPool = IUTokensV2(rewardTokens[i]).balanceOf(
holderAddress
);
rewardPool = rewardPool.add(holderRewards[i]);
// calculate the reward portion of the user
rewardAmounts[i] = rewardPool.mulDiv(
userLPTimeShare,
totalSupplyLPTimeShare
);
}
}
for (i = 0; i < otherRewardAmounts.length; i = i.add(1)) {
rewardTokens[i.add(sTokenAddresses.length)] = otherRewardTokens[i];
rewardAmounts[i.add(sTokenAddresses.length)] = otherRewardAmounts[
i
];
}
}
/*
* @dev calculate reward tokens and disburse to user
* @param holderAddress: holder contract address
* @param accountAddress: user address
*/
function _calculateRewards(address holderAddress, address accountAddress)
internal
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
uint256 updatedSupplyLPTimeshare;
uint256 newSupplyLPTimeShare;
uint256 i;
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
) = calculatePendingRewards(holderAddress, accountAddress);
// update last timestamps and LPTimeShares as per Checks-Effects-Interactions pattern
_lastLiquidityTimestamp[lpTokenAddress][accountAddress] = block
.timestamp;
_lastLPTimeShare[lpTokenAddress] = updatedSupplyLPTimeshare;
// update the cummulative new supply LP Timeshare value
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastCummulativeSupplyLPTimeShare(
lpTokenAddress,
newSupplyLPTimeShare
);
// update the _lastLPTimeShareTimestampArray
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastLPTimeShareTimestamp(lpTokenAddress, block.timestamp);
// DISBURSE THE MULTIPLE UTOKEN REWARDS TO USER (transfer)
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
if (RewardAmounts[i] > 0)
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
// DISBURSE THE OTHER REWARD TOKENS TO USER (transfer)
for (
i = sTokenAddresses.length;
i < RewardTokens.length;
i = i.add(1)
) {
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setRewardPoolUserTimestamp(
holderAddress,
RewardTokens[i],
accountAddress,
block.timestamp
);
// dispatch the rewards for that specific token
if (RewardAmounts[i] > 0) {
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
}
emit CalculateRewardsStakeLP(
holderAddress,
lpTokenAddress,
accountAddress,
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
/*
* @dev calculate liquidity and reward tokens and disburse to user
* @param holderAddress: holder contract address
*/
function calculateSyncedRewards(address holderAddress)
public
virtual
override
whenNotPaused
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
// check for validity of arguments
require(holderAddress != address(0), "LP1");
// initiate calculateHolderRewards for all StokenAddress-whitelistedAddress pair that
// comes under the holder contract
IWhitelistedPTokenEmission(_whitelistedPTokenEmissionContract)
.calculateAllHolderRewards(holderAddress);
// now initiate the calculate Rewards to distribute to the user
// calculate liquidity and reward tokens and disburse to user
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress
) = _calculateRewards(holderAddress, _msgSender());
require(lpTokenAddress != address(0), "LP2");
emit TriggeredCalculateSyncedRewards(
holderAddress,
_msgSender(),
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
/*
* @dev adding the liquidity
* @param holderAddress: holder contract address
* @param amount: token amount
*
* Emits a {AddLiquidity} event with 'lpToken, amount, rewards and liquidity'
*
*/
function addLiquidity(address holderAddress, uint256 amount)
public
virtual
override
whenNotPaused
returns (bool success)
{
// directly call calculate Synced Rewards since all the require conditions are checked there
(, , , address lpTokenAddress) = calculateSyncedRewards(holderAddress);
address messageSender = _msgSender();
// update the user balance
_lpBalance[lpTokenAddress][messageSender] = _lpBalance[lpTokenAddress][
messageSender
].add(amount);
// update the supply of lp tokens for reward and liquidity calculation
_lpSupply[lpTokenAddress] = _lpSupply[lpTokenAddress].add(amount);
// finally transfer the new LP Tokens to the StakeLP contract as per Checks-Effects-Interactions pattern
TransferHelper.safeTransferFrom(
lpTokenAddress,
messageSender,
address(this),
amount
);
// emit an event
emit AddLiquidity(
holderAddress,
messageSender,
amount,
block.timestamp
);
success = true;
return success;
}
/*
* @dev removing the liquidity
* @param holderAddress: holder contract address
* @param amount: token amount
*
* Emits a {RemoveLiquidity} event with 'lpToken, amount, rewards and liquidity'
*
*/
function removeLiquidity(address holderAddress, uint256 amount)
public
virtual
override
whenNotPaused
nonReentrant
returns (bool success)
{
// directly call calculateSyncedRewards since all the require conditions are checked there
(, , , address lpTokenAddress) = calculateSyncedRewards(holderAddress);
address messageSender = _msgSender();
// check if suffecient balance is there
require(_lpBalance[lpTokenAddress][messageSender] >= amount, "LP3");
// update the user balance
_lpBalance[lpTokenAddress][messageSender] = _lpBalance[lpTokenAddress][
messageSender
].sub(amount);
// update the supply of lp tokens for reward and liquidity calculation
_lpSupply[lpTokenAddress] = _lpSupply[lpTokenAddress].sub(amount);
// finally transfer the LP Tokens to the user as per Checks-Effects-Interactions pattern
TransferHelper.safeTransfer(lpTokenAddress, messageSender, amount);
emit RemoveLiquidity(
holderAddress,
messageSender,
amount,
block.timestamp
);
success = true;
return success;
}
/**
* @dev Set 'WhitelistedPTokenEmissionContract', called from constructor
*
* Emits a {SetWhitelistedPTokenEmissionContract} event with '_contract' set to the whitelistedPTokenEmission contract address.
*
*/
function setWhitelistedPTokenEmissionContract(
address whitelistedPTokenEmissionContract
) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LP4");
_whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract;
emit SetWhitelistedPTokenEmissionContract(
whitelistedPTokenEmissionContract
);
}
/**
* @dev Set 'whitelistedRewardEmissionContract', called from constructor
*
* Emits a {SetWhitelistedRewardEmissionContract} event with '_contract' set to the whitelistedRewardEmission contract address.
*
*/
function setWhitelistedRewardEmissionContract(
address whitelistedRewardEmissionContract
) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LP5");
_whitelistedRewardEmissionContract = whitelistedRewardEmissionContract;
emit SetWhitelistedRewardEmissionContract(
whitelistedRewardEmissionContract
);
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "LP6");
_pause();
return true;
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "LP7");
_unpause();
return true;
}
}
|
constant pertaining to access roles valueDivisor to store fractional values for various reward attributes like _rewardTokenEmission variable pertaining to contract upgrades versioning ------------------------------------------------------------------------- ------------------------------------------------------------------------- VARIABLES PERTAINING TO CALCULATION OF LPTIMESHARE balance of user, for an LP Token supply of LP tokens reserve, for an LP Token last updated total LPTimeShare, for an LP Token last recorded timestamp when user's LPTimeShare was updated, for a user, for an LP Token ------------------------------------------------------------------------- ------------------------------------------------------------------------- required to store the whitelisting holder logic data for PToken rewards, initiated from WhitelistedEmission contract required to store the whitelisting holder logic data for other rewards, initiated from WhitelistedEmission contract
|
{
using SafeMathUpgradeable for uint256;
using FullMath for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
uint256 public _valueDivisor;
uint256 public _version;
mapping(address => mapping(address => uint256)) public _lpBalance;
mapping(address => uint256) public _lpSupply;
mapping(address => uint256) public _lastLPTimeShare;
mapping(address => mapping(address => uint256))
public _lastLiquidityTimestamp;
address public _whitelistedPTokenEmissionContract;
address public _whitelistedRewardEmissionContract;
function initialize(
address pauserAddress,
address whitelistedPTokenEmissionContract,
address whitelistedRewardEmissionContract,
uint256 valueDivisor
Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors
) public virtual initializer {
__AccessControl_init();
__Pausable_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, pauserAddress);
_whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract;
_whitelistedRewardEmissionContract = whitelistedRewardEmissionContract;
_valueDivisor = valueDivisor;
}
function calculatePendingRewards(
address holderAddress,
address accountAddress
)
public
view
virtual
override
returns (
uint256[] memory rewardAmounts,
address[] memory rewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress,
uint256 updatedSupplyLPTimeshare,
uint256 newSupplyLPTimeShare
)
{
uint256 _userLPTimeShare;
uint256 _totalSupplyLPTimeShare;
uint256[] memory holderRewards;
(
holderRewards,
sTokenAddresses,
,
lpTokenAddress
) = IWhitelistedPTokenEmission(_whitelistedPTokenEmissionContract)
.calculateAllPendingHolderRewards(holderAddress);
if (
holderAddress == address(0) ||
lpTokenAddress == address(0) ||
accountAddress == address(0)
) {
return (
rewardAmounts,
rewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
);
}
(_lpBalance[lpTokenAddress][accountAddress]).mul(
block.timestamp.sub(
_lastLiquidityTimestamp[lpTokenAddress][accountAddress]
)
)
);
(_lpSupply[lpTokenAddress]).mul(
block.timestamp.sub(
IWhitelistedRewardEmission(
_whitelistedRewardEmissionContract
).getLastLPTimeShareTimestamp(lpTokenAddress)
)
)
);
newSupplyLPTimeShare
);
_userLPTimeShare
);
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
) = IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.calculateOtherPendingRewards(
holderAddress,
lpTokenAddress,
accountAddress,
_userLPTimeShare,
newSupplyLPTimeShare
);
(rewardAmounts, rewardTokens) = _getRewardData(
holderAddress,
sTokenAddresses,
holderRewards,
_userLPTimeShare,
_totalSupplyLPTimeShare,
otherRewardAmounts,
otherRewardTokens
);
}
function calculatePendingRewards(
address holderAddress,
address accountAddress
)
public
view
virtual
override
returns (
uint256[] memory rewardAmounts,
address[] memory rewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress,
uint256 updatedSupplyLPTimeshare,
uint256 newSupplyLPTimeShare
)
{
uint256 _userLPTimeShare;
uint256 _totalSupplyLPTimeShare;
uint256[] memory holderRewards;
(
holderRewards,
sTokenAddresses,
,
lpTokenAddress
) = IWhitelistedPTokenEmission(_whitelistedPTokenEmissionContract)
.calculateAllPendingHolderRewards(holderAddress);
if (
holderAddress == address(0) ||
lpTokenAddress == address(0) ||
accountAddress == address(0)
) {
return (
rewardAmounts,
rewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
);
}
(_lpBalance[lpTokenAddress][accountAddress]).mul(
block.timestamp.sub(
_lastLiquidityTimestamp[lpTokenAddress][accountAddress]
)
)
);
(_lpSupply[lpTokenAddress]).mul(
block.timestamp.sub(
IWhitelistedRewardEmission(
_whitelistedRewardEmissionContract
).getLastLPTimeShareTimestamp(lpTokenAddress)
)
)
);
newSupplyLPTimeShare
);
_userLPTimeShare
);
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
) = IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.calculateOtherPendingRewards(
holderAddress,
lpTokenAddress,
accountAddress,
_userLPTimeShare,
newSupplyLPTimeShare
);
(rewardAmounts, rewardTokens) = _getRewardData(
holderAddress,
sTokenAddresses,
holderRewards,
_userLPTimeShare,
_totalSupplyLPTimeShare,
otherRewardAmounts,
otherRewardTokens
);
}
_userLPTimeShare = (
newSupplyLPTimeShare = (
_totalSupplyLPTimeShare = _lastLPTimeShare[lpTokenAddress].add(
updatedSupplyLPTimeshare = _totalSupplyLPTimeShare.sub(
(
function _getRewardData(
address holderAddress,
address[] memory sTokenAddresses,
uint256[] memory holderRewards,
uint256 userLPTimeShare,
uint256 totalSupplyLPTimeShare,
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
)
internal
view
returns (uint256[] memory rewardAmounts, address[] memory rewardTokens)
{
uint256 i;
uint256 rewardPool;
rewardAmounts = new uint256[](
(otherRewardAmounts.length).add(sTokenAddresses.length)
);
rewardTokens = new address[](
(otherRewardTokens.length).add(sTokenAddresses.length)
);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
rewardTokens[i] = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
if (totalSupplyLPTimeShare > 0) {
rewardPool = IUTokensV2(rewardTokens[i]).balanceOf(
holderAddress
);
rewardPool = rewardPool.add(holderRewards[i]);
rewardAmounts[i] = rewardPool.mulDiv(
userLPTimeShare,
totalSupplyLPTimeShare
);
}
}
for (i = 0; i < otherRewardAmounts.length; i = i.add(1)) {
rewardTokens[i.add(sTokenAddresses.length)] = otherRewardTokens[i];
rewardAmounts[i.add(sTokenAddresses.length)] = otherRewardAmounts[
i
];
}
}
function _getRewardData(
address holderAddress,
address[] memory sTokenAddresses,
uint256[] memory holderRewards,
uint256 userLPTimeShare,
uint256 totalSupplyLPTimeShare,
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
)
internal
view
returns (uint256[] memory rewardAmounts, address[] memory rewardTokens)
{
uint256 i;
uint256 rewardPool;
rewardAmounts = new uint256[](
(otherRewardAmounts.length).add(sTokenAddresses.length)
);
rewardTokens = new address[](
(otherRewardTokens.length).add(sTokenAddresses.length)
);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
rewardTokens[i] = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
if (totalSupplyLPTimeShare > 0) {
rewardPool = IUTokensV2(rewardTokens[i]).balanceOf(
holderAddress
);
rewardPool = rewardPool.add(holderRewards[i]);
rewardAmounts[i] = rewardPool.mulDiv(
userLPTimeShare,
totalSupplyLPTimeShare
);
}
}
for (i = 0; i < otherRewardAmounts.length; i = i.add(1)) {
rewardTokens[i.add(sTokenAddresses.length)] = otherRewardTokens[i];
rewardAmounts[i.add(sTokenAddresses.length)] = otherRewardAmounts[
i
];
}
}
function _getRewardData(
address holderAddress,
address[] memory sTokenAddresses,
uint256[] memory holderRewards,
uint256 userLPTimeShare,
uint256 totalSupplyLPTimeShare,
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
)
internal
view
returns (uint256[] memory rewardAmounts, address[] memory rewardTokens)
{
uint256 i;
uint256 rewardPool;
rewardAmounts = new uint256[](
(otherRewardAmounts.length).add(sTokenAddresses.length)
);
rewardTokens = new address[](
(otherRewardTokens.length).add(sTokenAddresses.length)
);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
rewardTokens[i] = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
if (totalSupplyLPTimeShare > 0) {
rewardPool = IUTokensV2(rewardTokens[i]).balanceOf(
holderAddress
);
rewardPool = rewardPool.add(holderRewards[i]);
rewardAmounts[i] = rewardPool.mulDiv(
userLPTimeShare,
totalSupplyLPTimeShare
);
}
}
for (i = 0; i < otherRewardAmounts.length; i = i.add(1)) {
rewardTokens[i.add(sTokenAddresses.length)] = otherRewardTokens[i];
rewardAmounts[i.add(sTokenAddresses.length)] = otherRewardAmounts[
i
];
}
}
function _getRewardData(
address holderAddress,
address[] memory sTokenAddresses,
uint256[] memory holderRewards,
uint256 userLPTimeShare,
uint256 totalSupplyLPTimeShare,
uint256[] memory otherRewardAmounts,
address[] memory otherRewardTokens
)
internal
view
returns (uint256[] memory rewardAmounts, address[] memory rewardTokens)
{
uint256 i;
uint256 rewardPool;
rewardAmounts = new uint256[](
(otherRewardAmounts.length).add(sTokenAddresses.length)
);
rewardTokens = new address[](
(otherRewardTokens.length).add(sTokenAddresses.length)
);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
rewardTokens[i] = ISTokensV2(sTokenAddresses[i]).getUTokenAddress();
if (totalSupplyLPTimeShare > 0) {
rewardPool = IUTokensV2(rewardTokens[i]).balanceOf(
holderAddress
);
rewardPool = rewardPool.add(holderRewards[i]);
rewardAmounts[i] = rewardPool.mulDiv(
userLPTimeShare,
totalSupplyLPTimeShare
);
}
}
for (i = 0; i < otherRewardAmounts.length; i = i.add(1)) {
rewardTokens[i.add(sTokenAddresses.length)] = otherRewardTokens[i];
rewardAmounts[i.add(sTokenAddresses.length)] = otherRewardAmounts[
i
];
}
}
function _calculateRewards(address holderAddress, address accountAddress)
internal
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
uint256 updatedSupplyLPTimeshare;
uint256 newSupplyLPTimeShare;
uint256 i;
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
) = calculatePendingRewards(holderAddress, accountAddress);
_lastLiquidityTimestamp[lpTokenAddress][accountAddress] = block
.timestamp;
_lastLPTimeShare[lpTokenAddress] = updatedSupplyLPTimeshare;
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastCummulativeSupplyLPTimeShare(
lpTokenAddress,
newSupplyLPTimeShare
);
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastLPTimeShareTimestamp(lpTokenAddress, block.timestamp);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
if (RewardAmounts[i] > 0)
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
i = sTokenAddresses.length;
i < RewardTokens.length;
i = i.add(1)
) {
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setRewardPoolUserTimestamp(
holderAddress,
RewardTokens[i],
accountAddress,
block.timestamp
);
if (RewardAmounts[i] > 0) {
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
}
emit CalculateRewardsStakeLP(
holderAddress,
lpTokenAddress,
accountAddress,
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
function _calculateRewards(address holderAddress, address accountAddress)
internal
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
uint256 updatedSupplyLPTimeshare;
uint256 newSupplyLPTimeShare;
uint256 i;
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
) = calculatePendingRewards(holderAddress, accountAddress);
_lastLiquidityTimestamp[lpTokenAddress][accountAddress] = block
.timestamp;
_lastLPTimeShare[lpTokenAddress] = updatedSupplyLPTimeshare;
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastCummulativeSupplyLPTimeShare(
lpTokenAddress,
newSupplyLPTimeShare
);
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastLPTimeShareTimestamp(lpTokenAddress, block.timestamp);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
if (RewardAmounts[i] > 0)
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
i = sTokenAddresses.length;
i < RewardTokens.length;
i = i.add(1)
) {
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setRewardPoolUserTimestamp(
holderAddress,
RewardTokens[i],
accountAddress,
block.timestamp
);
if (RewardAmounts[i] > 0) {
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
}
emit CalculateRewardsStakeLP(
holderAddress,
lpTokenAddress,
accountAddress,
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
for (
function _calculateRewards(address holderAddress, address accountAddress)
internal
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
uint256 updatedSupplyLPTimeshare;
uint256 newSupplyLPTimeShare;
uint256 i;
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
) = calculatePendingRewards(holderAddress, accountAddress);
_lastLiquidityTimestamp[lpTokenAddress][accountAddress] = block
.timestamp;
_lastLPTimeShare[lpTokenAddress] = updatedSupplyLPTimeshare;
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastCummulativeSupplyLPTimeShare(
lpTokenAddress,
newSupplyLPTimeShare
);
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastLPTimeShareTimestamp(lpTokenAddress, block.timestamp);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
if (RewardAmounts[i] > 0)
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
i = sTokenAddresses.length;
i < RewardTokens.length;
i = i.add(1)
) {
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setRewardPoolUserTimestamp(
holderAddress,
RewardTokens[i],
accountAddress,
block.timestamp
);
if (RewardAmounts[i] > 0) {
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
}
emit CalculateRewardsStakeLP(
holderAddress,
lpTokenAddress,
accountAddress,
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
function _calculateRewards(address holderAddress, address accountAddress)
internal
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
uint256 updatedSupplyLPTimeshare;
uint256 newSupplyLPTimeShare;
uint256 i;
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress,
updatedSupplyLPTimeshare,
newSupplyLPTimeShare
) = calculatePendingRewards(holderAddress, accountAddress);
_lastLiquidityTimestamp[lpTokenAddress][accountAddress] = block
.timestamp;
_lastLPTimeShare[lpTokenAddress] = updatedSupplyLPTimeshare;
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastCummulativeSupplyLPTimeShare(
lpTokenAddress,
newSupplyLPTimeShare
);
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setLastLPTimeShareTimestamp(lpTokenAddress, block.timestamp);
for (i = 0; i < sTokenAddresses.length; i = i.add(1)) {
if (RewardAmounts[i] > 0)
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
i = sTokenAddresses.length;
i < RewardTokens.length;
i = i.add(1)
) {
IWhitelistedRewardEmission(_whitelistedRewardEmissionContract)
.setRewardPoolUserTimestamp(
holderAddress,
RewardTokens[i],
accountAddress,
block.timestamp
);
if (RewardAmounts[i] > 0) {
IHolderV2(holderAddress).safeTransfer(
RewardTokens[i],
accountAddress,
RewardAmounts[i]
);
}
}
emit CalculateRewardsStakeLP(
holderAddress,
lpTokenAddress,
accountAddress,
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
function calculateSyncedRewards(address holderAddress)
public
virtual
override
whenNotPaused
returns (
uint256[] memory RewardAmounts,
address[] memory RewardTokens,
address[] memory sTokenAddresses,
address lpTokenAddress
)
{
require(holderAddress != address(0), "LP1");
IWhitelistedPTokenEmission(_whitelistedPTokenEmissionContract)
.calculateAllHolderRewards(holderAddress);
(
RewardAmounts,
RewardTokens,
sTokenAddresses,
lpTokenAddress
) = _calculateRewards(holderAddress, _msgSender());
require(lpTokenAddress != address(0), "LP2");
emit TriggeredCalculateSyncedRewards(
holderAddress,
_msgSender(),
RewardAmounts,
RewardTokens,
sTokenAddresses,
block.timestamp
);
}
function addLiquidity(address holderAddress, uint256 amount)
public
virtual
override
whenNotPaused
returns (bool success)
{
(, , , address lpTokenAddress) = calculateSyncedRewards(holderAddress);
address messageSender = _msgSender();
_lpBalance[lpTokenAddress][messageSender] = _lpBalance[lpTokenAddress][
messageSender
].add(amount);
_lpSupply[lpTokenAddress] = _lpSupply[lpTokenAddress].add(amount);
TransferHelper.safeTransferFrom(
lpTokenAddress,
messageSender,
address(this),
amount
);
emit AddLiquidity(
holderAddress,
messageSender,
amount,
block.timestamp
);
success = true;
return success;
}
function removeLiquidity(address holderAddress, uint256 amount)
public
virtual
override
whenNotPaused
nonReentrant
returns (bool success)
{
(, , , address lpTokenAddress) = calculateSyncedRewards(holderAddress);
address messageSender = _msgSender();
require(_lpBalance[lpTokenAddress][messageSender] >= amount, "LP3");
_lpBalance[lpTokenAddress][messageSender] = _lpBalance[lpTokenAddress][
messageSender
].sub(amount);
_lpSupply[lpTokenAddress] = _lpSupply[lpTokenAddress].sub(amount);
TransferHelper.safeTransfer(lpTokenAddress, messageSender, amount);
emit RemoveLiquidity(
holderAddress,
messageSender,
amount,
block.timestamp
);
success = true;
return success;
}
function setWhitelistedPTokenEmissionContract(
address whitelistedPTokenEmissionContract
) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LP4");
_whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract;
emit SetWhitelistedPTokenEmissionContract(
whitelistedPTokenEmissionContract
);
}
function setWhitelistedRewardEmissionContract(
address whitelistedRewardEmissionContract
) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "LP5");
_whitelistedRewardEmissionContract = whitelistedRewardEmissionContract;
emit SetWhitelistedRewardEmissionContract(
whitelistedRewardEmissionContract
);
}
function pause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "LP6");
_pause();
return true;
}
function unpause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "LP7");
_unpause();
return true;
}
}
| 996,761 |
/**
*Submitted for verification at Etherscan.io on 2021-03-10
*/
/**
*Submitted for verification at Etherscan.io on 2021-02-27
*/
pragma solidity >=0.5.0 <0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
// 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;
}
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint 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(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
interface iERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address recipient, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function transferFrom(address sender, address recipient, uint amount) external returns (bool);
function increaseAllowance(address spender, uint addedValue) external returns (bool);
function decreaseAllowance(address spender, uint subtractedValue) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
contract ownerable {
address public contract_owner;
constructor() public {
contract_owner = msg.sender;
}
modifier KOwnerOnly() {
require(msg.sender == contract_owner, 'NotOwner'); _;
}
function tranferOwnerShip(address newOwner) external KOwnerOnly {
contract_owner = newOwner;
}
}
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*/
contract pausable is ownerable {
bool public paused;
/**
* @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);
/**
* @dev Initialize the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
paused = false;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier KWhenNotPaused() {
require(!paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier KWhenPaused() {
require(paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function Pause() public KOwnerOnly {
paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function Unpause() public KOwnerOnly {
paused = false;
emit Unpaused(msg.sender);
}
}
contract VCMINEToken is iERC20, pausable {
using SafeMath for uint;
string public name = "VCMINE";
string public symbol = "VCFT";
uint8 public decimals = 6;
uint public totalSupply = 210000000e6;
mapping (address => uint) internal _balances;
mapping (address => mapping (address => uint)) internal _allowances;
constructor(
address receiver,
address defaultOwner
) public {
contract_owner = defaultOwner;
_balances[receiver] = totalSupply;
emit Transfer(address(0), receiver, totalSupply);
}
function balanceOf(address account) public view returns (uint) {
return _balances[account];
}
function transfer(address recipient, uint amount) external KWhenNotPaused returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
function allowance(address owner, address spender) external view returns (uint) {
return _allowances[owner][spender];
}
function approve(address spender, uint value) external KWhenNotPaused returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transferFrom(address sender, address recipient, uint amount) external KWhenNotPaused 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, uint addedValue) external KWhenNotPaused returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
function decreaseAllowance(address spender, uint subtractedValue) external KWhenNotPaused 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, uint 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);
}
function _approve(address owner, address spender, uint value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
|
Called by a pauser to pause, triggers stopped state./
|
function Pause() public KOwnerOnly {
paused = true;
emit Paused(msg.sender);
}
| 6,608,424 |
./partial_match/1/0xeCC094e20561001caBBE63Fe9E6C2d3081DeA271/sources/contracts/AssetsInteraction.sol
|
Internal function to set isResurrected status on previously resurrected Teen Bulls tokenIds: Array of Teen Bull IDs to set isResurrected status boolean: Boolean to set isResurrected status Only used to set isResurrected status on Teen Bulls resurrected before the contract deployment
|
function setIsResurrected(
uint256[] memory tokenIds,
bool boolean
) external onlyOwner {
for (uint256 i = 0; i < tokenIds.length; i++) {
isResurrected[tokenIds[i]] = boolean;
}
}
| 2,776,148 |
./full_match/42220/0xb67E717e6Be4DcFa29359D1cb22C78B97488d6c9/sources/MasterChef.sol
|
Deposit LP tokens to MasterChef for Celofarms allocation.
|
function deposit(uint256 _pid, uint256 _amount) public {
require (_pid != 0, 'deposit Celofarms by staking');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accCelofarmsPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeCelofarmsTransfer(msg.sender, pending);
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user.amount.mul(pool.accCelofarmsPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
| 16,343,987 |
pragma solidity 0.5.8;
import "truffle/Assert.sol";
import "../contracts/StringUtil.sol";
contract TestStringUtil {
using StringUtil for string;
string[] private testStringArray;
// Test small string allocation. Make sure that there is always enough allocated.
function testSmallStringSizeAllocation()
public
{
string memory testString = "one";
uint size = bytes(testString).length;
Assert.equal(size, 3, "Test string size should be three (3)");
Assert.equal(StringUtil.getSize(testString), 64, "Test string allocation size should be 64");
}
// Test bigger string allocation. Make sure that size will be increased.
function testBigStringSizeAllocation()
public
{
string memory testString = "onetwothreefourfivesixseveneightnineteneleventwelvethirteenfourteen";
uint size = bytes(testString).length;
Assert.equal(size, 67, "Test string size should be sixtyseven (67)");
Assert.equal(StringUtil.getSize(testString), 128, "Test string size should be 128");
}
// Test logic with empty array. Should return empty string.
function testConvertEmptyArrayInBytes()
public
{
testStringArray = new string[](0);
bytes memory emptyStringArrayInBytes = convertStringArrayToBytes();
string memory arraString = string(emptyStringArrayInBytes);
Assert.equal(arraString, "", "Test array should be empty");
}
// Test if array contains only one entry. Entry should be found from the
// beginning of converted string.
function testConvertArrayContainingOneStringInBytes()
public
{
testStringArray = ["one"];
string memory arraString = string(convertStringArrayToBytes());
string memory firstString = substring(arraString, 0, 3);
string memory expected = "one";
Assert.equal(firstString, expected, "Test array should contain only string 'one'");
}
// Test if array contains multiple entry. Entry should be found from the
// beginning of every 64 slot.
function testConvertArrayContainingMultipleStringsInBytes()
public
{
testStringArray = ["one", "two", "three"];
string memory arraString = string(convertStringArrayToBytes());
string memory firstString = substring(arraString, 0, 3);
string memory secondString = substring(arraString, 64, 67);
string memory thirdString = substring(arraString, 128, 133);
Assert.equal(firstString, "one", "Test array should contain only string 'one'");
Assert.equal(secondString, "two", "Test array should contain only string 'two'");
Assert.equal(thirdString, "three", "Test array should contain only string 'three'");
}
/** @dev Get substring of given string. This is test helper method.
* @return substr Substring of the given string
*/
function substring(string memory str, uint startIndex, uint endIndex)
private
pure
returns (string memory substr)
{
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for (uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
/** @dev Get string array in bytes. Iterate through array items and
* transfer strings into bytes. This is test helper method.
* @return serialized Names array in bytes.
*/
function convertStringArrayToBytes()
private
view
returns(bytes memory serialized)
{
uint offset = 64*testStringArray.length;
bytes memory buffer = new bytes(offset);
string memory str = new string(32);
for (uint i = testStringArray.length - 1; i < testStringArray.length; i--) {
str = testStringArray[i];
StringUtil.stringToBytes(offset, bytes(str), buffer);
offset -= str.getSize();
}
return (buffer);
}
}
|
Get string array in bytes. Iterate through array items and transfer strings into bytes. This is test helper method. return serialized Names array in bytes./
|
function convertStringArrayToBytes()
private
view
returns(bytes memory serialized)
{
uint offset = 64*testStringArray.length;
bytes memory buffer = new bytes(offset);
string memory str = new string(32);
for (uint i = testStringArray.length - 1; i < testStringArray.length; i--) {
str = testStringArray[i];
StringUtil.stringToBytes(offset, bytes(str), buffer);
offset -= str.getSize();
}
return (buffer);
}
| 1,037,891 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// Adapted from Open Zeppelin's RefundVault
/**
* @title Vault
* @dev This contract is used for storing funds.
*/
contract TreeCampaignVault is Ownable {
using SafeMath for uint256;
struct TreeDeposit {
address payable treeOwner; //who is contributing to the farmer
uint256 firstDepositTimestamp;
uint256 nextDisbursement;
uint256 balance;
}
// Wallet from the project team
address payable public trustedWallet;
mapping(bytes32 => TreeDeposit) public deposits;
event LogVaultCreated(address indexed wallet);
event LogDeposited(
address indexed contributor,
bytes32 treeId,
uint256 amount,
uint256 firstDepositTimestamp
);
event LogRefunded(
address indexed contributor,
bytes32 treeId,
uint256 amount
);
event LogFundsSentToWallet(
bytes32 indexed treeId,
address trustedWallet,
uint256 amount
);
event LogAllFundsSentToWallet(
bytes32 indexed treeId,
address trustedWallet,
uint256 amount
);
constructor(address payable _wallet) public {
require(_wallet != address(0), "Wallet address should not be 0.");
trustedWallet = _wallet;
emit LogVaultCreated(_wallet);
}
function depositValue(
address payable _contributor,
string calldata _treeLocation
) external payable onlyOwner {
//check if tree is available
bytes32 _treeId = keccak256(abi.encodePacked(_treeLocation));
TreeDeposit memory deposit = deposits[_treeId];
require(deposit.treeOwner == address(0), "Tree must not have an owner");
require(deposit.balance == 0, "Tree balance must be zero.");
require(msg.value == 1 ether, "Each tree must cost 1 Ether");
uint256 amount = msg.value;
uint256 fee_10percent = amount.div(10);
uint256 remain = amount.sub(fee_10percent);
trustedWallet.transfer(fee_10percent); //first, transfer 10% to trusted wallet
deposits[_treeId] = TreeDeposit({
treeOwner: _contributor,
firstDepositTimestamp: block.timestamp,
nextDisbursement: (block.timestamp + 365 days),
balance: remain
});
emit LogDeposited(_contributor, _treeId, msg.value, block.timestamp);
}
/// @dev Refunds ether to the contributors if in the contributors wants funds back.
function refund(bytes32 _treeId) external {
TreeDeposit storage deposit = deposits[_treeId];
require(
deposit.balance > 0,
"Refund not allowed if deposit balance is 0."
);
require(
deposit.treeOwner == msg.sender,
"Only owner of the deposit can request a refund."
);
uint256 refundAmount = deposit.balance; //will refund what is lefted
deposit.balance = 0;
deposit.treeOwner.transfer(refundAmount);
emit LogRefunded(deposit.treeOwner, _treeId, refundAmount);
}
/// @dev Sends the disbursement amount to the wallet after the disbursement period has passed. Can be called by anyone.
function sendFundsToWallet(bytes32 _treeId) external {
TreeDeposit storage deposit = deposits[_treeId];
require(
deposit.nextDisbursement <= block.timestamp,
"Next disbursement period timestamp has not yet passed, too early to withdraw."
);
require(deposit.balance > 0, "TreeDeposit balance is 0.");
if (
block.timestamp > deposit.nextDisbursement &&
block.timestamp < deposit.firstDepositTimestamp + 10 * (365 days)
) {
uint256 initialDeposited = 1 ether;
uint256 fee_10percent = initialDeposited.div(10);
uint256 remain = deposit.balance.sub(fee_10percent);
deposit.balance = remain;
deposit.nextDisbursement = deposit.nextDisbursement + 365 days;
trustedWallet.transfer(fee_10percent);
emit LogFundsSentToWallet(_treeId, trustedWallet, fee_10percent);
}
//if more than 10 years has passed, all funds can be collected
else if (
block.timestamp >= deposit.firstDepositTimestamp + 10 * (365 days)
) {
uint256 allFunds = deposit.balance;
deposit.balance = 0;
trustedWallet.transfer(allFunds);
emit LogAllFundsSentToWallet(_treeId, trustedWallet, allFunds);
}
}
}
|
Refunds ether to the contributors if in the contributors wants funds back.
|
function refund(bytes32 _treeId) external {
TreeDeposit storage deposit = deposits[_treeId];
require(
deposit.balance > 0,
"Refund not allowed if deposit balance is 0."
);
require(
deposit.treeOwner == msg.sender,
"Only owner of the deposit can request a refund."
);
deposit.balance = 0;
deposit.treeOwner.transfer(refundAmount);
emit LogRefunded(deposit.treeOwner, _treeId, refundAmount);
}
| 6,427,230 |
./full_match/1/0x0740B4029AEa19F7c80f86dA485e880ECE8C93bd/sources/contracts/v2/Editions/Fairxyz721Editions.sol
|
See {IFairxyz721Editions-setTokenRoyalty}./
|
function setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 royaltyFraction
) external override onlyCreator {
_setTokenRoyalty(tokenId, receiver, royaltyFraction);
}
| 16,444,044 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../interfaces/IGrow.sol";
import "../utils/SwapUtils.sol";
import "./GrowMinter.sol";
contract GrowRewarder is IGrowRewarder, Ownable, ReentrancyGuard {
uint256 constant REWARD_DECIMAL = 1e18;
using SafeMath for uint256;
using SafeERC20 for IERC20;
GrowMinter public immutable growMinter;
/// @dev Utils for swap token and get price in BNB
address public SWAP_UTILS;
constructor(address _growMinter, address _SWAP_UTILS) public {
growMinter = GrowMinter(_growMinter);
SWAP_UTILS = _SWAP_UTILS;
}
modifier onlyStrategy(address strategyAddress) {
require(growMinter.isStrategyActive(msg.sender), "GrowMaster: caller is not on the strategy");
require(address(msg.sender) == strategyAddress, "GrowMaster: caller is not current strategy");
_;
}
// --------------------------------------------------------------
// Config Interface
// --------------------------------------------------------------
function updateSwapUtils(address _swapUtilsAddress) external onlyOwner {
SWAP_UTILS = _swapUtilsAddress;
}
// --------------------------------------------------------------
// Misc
// --------------------------------------------------------------
function approveToken(address token, address to, uint256 amount) internal {
if (IERC20(token).allowance(address(this), to) < amount) {
IERC20(token).safeApprove(to, 0);
IERC20(token).safeApprove(to, uint256(~0));
}
}
function _swap(address tokenA, address tokenB, uint256 amount) internal returns (uint256) {
if (tokenA == tokenB) return amount;
approveToken(tokenA, SWAP_UTILS, amount);
uint256 tokenReceived = SwapUtils(SWAP_UTILS).swap(tokenA, tokenB, amount);
IERC20(tokenB).safeTransferFrom(SWAP_UTILS, address(this), tokenReceived);
return tokenReceived;
}
// --------------------------------------------------------------
// Block Reward (MasterChef-Like)
// --------------------------------------------------------------
function blockRewardUpdateRewards(address strategyAddress) private {
(uint256 allocPoint, uint256 lastRewardBlock, uint256 accGrowPerShare) = growMinter.getBlockRewardConfig(strategyAddress);
if (block.number <= lastRewardBlock) {
return;
}
uint256 totalShares = IGrowStrategy(strategyAddress).totalShares();
if (totalShares == 0 || growMinter.blockRewardTotalAllocPoint() == 0 || growMinter.blockRewardGrowPreBlock() == 0) {
growMinter.updateBlockRewardLastRewardBlock(strategyAddress);
return;
}
uint256 multiplier = block.number.sub(lastRewardBlock);
uint256 growReward = multiplier
.mul(growMinter.blockRewardGrowPreBlock())
.mul(allocPoint)
.div(growMinter.blockRewardTotalAllocPoint());
if (growReward > 0) {
growMinter.mintForReward(growReward);
}
// = accGrowPerShare + (growReward × REWARD_DECIMAL / totalSupply)
growMinter.updateBlockRewardAccGrowPerShare(strategyAddress, accGrowPerShare.add(
growReward
.mul(REWARD_DECIMAL)
.div(totalShares)
));
growMinter.updateBlockRewardLastRewardBlock(strategyAddress);
}
// --------------------------------------------------------------
// Deposit Reward (Directly set by strategy with timelock)
// --------------------------------------------------------------
function depositRewardAddReward(address strategyAddress, address userAddress, uint256 amountInNativeToken) external override onlyStrategy(strategyAddress) {
if (amountInNativeToken <= 0) return; // nothing happened
(uint256 multiplier, uint256 membershipMultiplier,) = growMinter.getDepositRewardConfig(strategyAddress);
if (growMinter.hasMembership(userAddress)) {
multiplier = membershipMultiplier;
}
if (multiplier <= 0) return; // nothing happened
growMinter.addLockedRewards(strategyAddress, userAddress, amountInNativeToken.mul(multiplier).div(REWARD_DECIMAL));
}
// --------------------------------------------------------------
// Profit Reward (Take some profits and reward as GROW)
// --------------------------------------------------------------
function profitRewardAddReward(address strategyAddress, address profitToken, address userAddress, uint256 profitTokenAmount) external override onlyStrategy(strategyAddress) {
if (profitTokenAmount <= 0) return; // nothing happened
if (profitToken == address(0)) return; // nothing happened
IERC20(profitToken).safeTransferFrom(strategyAddress, address(this), profitTokenAmount);
uint256 rate = growMinter.hasMembership(userAddress) ? 8800 : 8000;
uint256 profitForSwapGrow = profitTokenAmount.mul(10000).mul(rate).div(10000).div(10000);
profitTokenAmount = profitTokenAmount.sub(profitForSwapGrow);
if (profitForSwapGrow > 0) {
uint256 growRewardAmount = _swap(profitToken, address(growMinter.GROW()), profitForSwapGrow);
growMinter.addPendingRewards(strategyAddress, userAddress, growRewardAmount);
}
address profitStrategy = growMinter.profitStrategies(profitToken);
if (profitStrategy != address(0)) {
IERC20(profitToken).safeApprove(profitStrategy, profitTokenAmount);
IGrowProfitReceiver(profitStrategy).pump(profitTokenAmount);
} else {
// if no profit strategy, dev will receive it
IERC20(profitToken).safeTransfer(growMinter.growDev(), profitTokenAmount);
}
}
// --------------------------------------------------------------
// Reward Manage
// --------------------------------------------------------------
function updateRewards(address strategyAddress) public {
blockRewardUpdateRewards(strategyAddress);
}
function _getRewards(address strategyAddress, address userAddress) private {
// 1. settlement current rewards
settlementRewards(strategyAddress, userAddress);
uint256 pendingGrows = growMinter.getPendingRewards(strategyAddress, userAddress);
uint256 currentRewarderBalance = IERC20(growMinter.GROW()).balanceOf(address(growMinter));
if (pendingGrows > currentRewarderBalance) {
growMinter.mintForReward(pendingGrows.sub(currentRewarderBalance));
}
// 2. transfer
growMinter.transferPendingGrow(strategyAddress, userAddress);
emit LogGetRewards(strategyAddress, userAddress, pendingGrows);
}
function getRewards(address strategyAddress, address userAddress) external override onlyStrategy(strategyAddress) {
_getRewards(strategyAddress, userAddress);
}
function updateRewardDebt(address strategyAddress, address userAddress, uint256 sharesUpdateTo) private {
(,,uint256 accGrowPerShare) = growMinter.getBlockRewardConfig(strategyAddress);
growMinter.updateBlockRewardUserRewardDebt(strategyAddress, userAddress, sharesUpdateTo.mul(accGrowPerShare).div(REWARD_DECIMAL));
}
function settlementRewards(address strategyAddress, address userAddress) private {
uint256 currentUserShares = IGrowStrategy(strategyAddress).sharesOf(userAddress);
// 1. update reward data
updateRewards(strategyAddress);
(,, uint256 accGrowPerShare) = growMinter.getBlockRewardConfig(strategyAddress);
uint256 blockRewardDebt = growMinter.getBlockRewardUserInfo(strategyAddress, userAddress);
// reward by shares (Block reward & Profit reward)
if (currentUserShares > 0) {
// Block reward
uint256 pendingBlockReward = currentUserShares
.mul(accGrowPerShare)
.div(REWARD_DECIMAL)
.sub(blockRewardDebt);
growMinter.updateBlockRewardUserRewardDebt(
strategyAddress, userAddress,
currentUserShares
.mul(accGrowPerShare)
.div(REWARD_DECIMAL)
);
growMinter.addPendingRewards(strategyAddress, userAddress, pendingBlockReward);
}
// deposit reward
growMinter.unlockLockedRewards(strategyAddress, userAddress, false);
emit LogSettlementRewards(strategyAddress, userAddress, growMinter.getPendingRewards(strategyAddress, userAddress));
}
// --------------------------------------------------------------
// Share manage
// --------------------------------------------------------------
function notifyUserSharesUpdate(address strategyAddress, address userAddress, uint256 sharesUpdateTo, bool isWithdraw) external override onlyStrategy(strategyAddress) {
// 0. if strategyAddress is EMERGENCY_MODE
if (IGrowStrategy(strategyAddress).IS_EMERGENCY_MODE()) {
growMinter.unlockLockedRewards(strategyAddress, userAddress, true);
}
// 1. check if need revert deposit reward
if (isWithdraw) {
growMinter.checkNeedResetLockedRewards(strategyAddress, userAddress);
}
// 2. settlement current rewards
settlementRewards(strategyAddress, userAddress);
// 3. reset reward debt base on current shares
updateRewardDebt(strategyAddress, userAddress, sharesUpdateTo);
emit LogSharesUpdate(strategyAddress, userAddress, sharesUpdateTo);
}
// --------------------------------------------------------------
// User Write Interface
// --------------------------------------------------------------
function getSelfRewards(address strategyAddress) external nonReentrant {
_getRewards(strategyAddress, msg.sender);
}
// --------------------------------------------------------------
// Events
// --------------------------------------------------------------
event LogGrowMint(address to, uint256 amount);
event LogSharesUpdate(address strategyAddress, address user, uint256 shares);
event LogSettlementRewards(address strategyAddress, address user, uint256 amount);
event LogGetRewards(address strategyAddress, address user, uint256 amount);
}
|
if no profit strategy, dev will receive it
|
function profitRewardAddReward(address strategyAddress, address profitToken, address userAddress, uint256 profitTokenAmount) external override onlyStrategy(strategyAddress) {
IERC20(profitToken).safeTransferFrom(strategyAddress, address(this), profitTokenAmount);
uint256 rate = growMinter.hasMembership(userAddress) ? 8800 : 8000;
uint256 profitForSwapGrow = profitTokenAmount.mul(10000).mul(rate).div(10000).div(10000);
profitTokenAmount = profitTokenAmount.sub(profitForSwapGrow);
if (profitForSwapGrow > 0) {
uint256 growRewardAmount = _swap(profitToken, address(growMinter.GROW()), profitForSwapGrow);
growMinter.addPendingRewards(strategyAddress, userAddress, growRewardAmount);
}
address profitStrategy = growMinter.profitStrategies(profitToken);
if (profitStrategy != address(0)) {
IERC20(profitToken).safeApprove(profitStrategy, profitTokenAmount);
IGrowProfitReceiver(profitStrategy).pump(profitTokenAmount);
IERC20(profitToken).safeTransfer(growMinter.growDev(), profitTokenAmount);
}
}
| 13,026,595 |
pragma solidity 0.5.17;
import "../../other/1inch.sol";
import "../../other/reetrancy.sol";
import "../../other/Initializable.sol";
interface IOracle{
function getiTokenDetails(uint _poolIndex) external returns(string memory, string memory,string memory);
function getTokenDetails(uint _poolIndex) external returns(address[] memory,uint[] memory,uint ,uint);
}
interface Iitokendeployer{
function createnewitoken(string calldata _name, string calldata _symbol) external returns(address);
}
interface Iitoken{
function mint(address account, uint256 amount) external returns (bool);
function burn(address account, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IMAsterChef{
function depositFromDaaAndDAO(uint256 _pid, uint256 _amount, uint256 vault, address _sender,bool isPremium) external;
function distributeExitFeeShare(uint256 _amount) external;
}
interface IPoolConfiguration{
function checkDao(address daoAddress) external returns(bool);
function getperformancefees() external view returns(uint256);
function getmaxTokenSupported() external view returns(uint256);
function getslippagerate() external view returns(uint256);
function getoracleaddress() external view returns(address);
function getEarlyExitfees() external view returns(uint256);
function checkStableCoin(address _stable) external view returns(bool);
}
contract PoolV1 is ReentrancyGuard,Initializable {
using SafeMath for uint;
using SafeERC20 for IERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// Kovan addresses
// address public EXCHANGE_CONTRACT = 0x5e676a2Ed7CBe15119EBe7E96e1BB0f3d157206F;
// address public WETH_ADDRESS = 0x7816fBBEd2C321c24bdB2e2477AF965Efafb7aC0;
// address public baseStableCoin = 0xc6196e00Fd2970BD91777AADd387E08574cDf92a;
// Mainnet Addresses
address public EXCHANGE_CONTRACT = 0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e;
address public WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public baseStableCoin = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// ASTRA token Address
address public ASTRTokenAddress;
// Manager Account Address
address public managerAddresses;
// Pool configuration contract address. This contract manage the configuration for this contract.
address public _poolConf;
// Chef contract address for staking
address public poolChef;
// Address of itoken deployer. This will contract will be responsible for deploying itokens.
address public itokendeployer;
// Structure for storing the pool details
struct PoolInfo {
// Array for token addresses.
address[] tokens;
// Weight for each token. Share is calculated by dividing the weight with total weight.
uint256[] weights;
// Total weight. Sum of all the weight in array.
uint256 totalWeight;
// Check if pool is active or not
bool active;
// Next rebalance time for pool/index in unix timestamp
uint256 rebaltime;
// Threshold value. Minimum value after that pool will start buying token
uint256 threshold;
// Number of rebalance performed on this pool.
uint256 currentRebalance;
// Unix timeseamp for the last rebalance time
uint256 lastrebalance;
// itoken Created address
address itokenaddr;
// Owner address for owner
address owner;
//description for token
string description;
}
struct PoolUser
{
// Balance of user in pool
uint256 currentBalance;
// Number of rebalance pupto which user account is synced
uint256 currentPool;
// Pending amount for which no tokens are bought
uint256 pendingBalance;
// Total amount deposited in stable coin.
uint256 USDTdeposit;
// ioktne balance for that pool. This will tell the total itoken balance either staked at chef or hold at account.
uint256 Itokens;
// Check id user account is active
bool active;
// Check if user account is whitelisted or not.
bool isenabled;
}
// Mapping for user infor based on the structure created above.
mapping ( uint256 =>mapping(address => PoolUser)) public poolUserInfo;
// Array for storing indices details
PoolInfo[] public poolInfo;
// Private array variable use internally by functions.
uint256[] private buf;
// address[] private _Tokens;
// uint256[] private _Values;
address[] private _TokensStable;
uint256[] private _ValuesStable;
// Mapping to show the token balance for a particular pool.
mapping(uint256 => mapping(address => uint256)) public tokenBalances;
// Store the tota pool balance
mapping(uint256 => uint256) public totalPoolbalance;
// Store the pending balance for which tokens are not bought.
mapping(uint256 => uint256) public poolPendingbalance;
//Track the initial block where user deposit amount.
mapping(address =>mapping (uint256 => uint256)) public initialDeposit;
//Check if user already exist or not.
mapping(address =>mapping (uint256 => bool)) public existingUser;
bool public active = true;
mapping(address => bool) public systemAddresses;
/**
* @dev Modifier to check if the called is Admin or not.
*/
modifier systemOnly {
require(systemAddresses[msg.sender], "EO1");
_;
}
// Event emitted
event Transfer(address indexed src, address indexed dst, uint wad);
event Withdrawn(address indexed from, uint value);
event WithdrawnToken(address indexed from, address indexed token, uint amount);
/**
* Error code:
* EO1: system only
* E02: Invalid Pool Index
* E03: Already whitelisted
* E04: Only manager can whitelist
* E05: Only owner can whitelist
* E06: Invalid config length
* E07: Only whitelisted user
* E08: Only one token allowed
* E09: Deposit some amount
* E10: Only stable coins
* E11: Not enough tokens
* E12: Rebalnce time not reached
* E13: Only owner can update the public pool
* E14: No balance in Pool
* E15: Zero address
* E16: More than allowed token in indices
*/
function initialize(address _ASTRTokenAddress, address poolConfiguration,address _itokendeployer, address _chef) public initializer{
require(_ASTRTokenAddress != address(0), "E15");
require(poolConfiguration != address(0), "E15");
require(_itokendeployer != address(0), "E15");
require(_chef != address(0), "E15");
ReentrancyGuard.__init();
systemAddresses[msg.sender] = true;
ASTRTokenAddress = _ASTRTokenAddress;
managerAddresses = msg.sender;
_poolConf = poolConfiguration;
itokendeployer = _itokendeployer;
poolChef = _chef;
}
/**
* @notice White users address
* @param _address Account that needs to be whitelisted.
* @param _poolIndex Pool Index in which user wants to invest.
* @dev Whitelist users for deposit on pool. Without this user will not be able to deposit.
*/
function whitelistaddress(address _address, uint _poolIndex) external {
// Check if pool configuration is correct or not
require(_address != address(0), "E15");
require(_poolIndex<poolInfo.length, "E02");
require(!poolUserInfo[_poolIndex][_address].active,"E03");
// Only pool manager can whitelist users
if(poolInfo[_poolIndex].owner == address(this)){
require(managerAddresses == msg.sender, "E04");
}else{
require(poolInfo[_poolIndex].owner == msg.sender, "E05");
}
// Create new object for user.
PoolUser memory newPoolUser = PoolUser(0, poolInfo[_poolIndex].currentRebalance,0,0,0,true,true);
poolUserInfo[_poolIndex][_address] = newPoolUser;
}
function calculateTotalWeight(uint[] memory _weights) internal view returns(uint){
uint _totalWeight;
// Calculate total weight for new index.
for(uint i = 0; i < _weights.length; i++) {
_totalWeight = _totalWeight.add(_weights[i]);
}
return _totalWeight;
}
/**
* @notice Add public pool
* @param _tokens tokens to purchase in pool.
* @param _weights Weight of new tokens.
* @param _threshold Threshold amount to purchase token.
* @param _rebalanceTime Next Rebalance time.
* @param _name itoken name.
* @param _symbol itoken symbol.
* @dev Add new public pool by any users.Here any users can add there custom pools
*/
function addPublicPool(address[] memory _tokens, uint[] memory _weights,uint _threshold,uint _rebalanceTime,string memory _name,string memory _symbol,string memory _description) public{
//Currently it will only check if configuration is correct as staking amount is not decided to add the new pool.
address _itokenaddr;
address _poolOwner;
uint _poolIndex = poolInfo.length;
address _OracleAddress = IPoolConfiguration(_poolConf).getoracleaddress();
if(_tokens.length == 0){
require(systemAddresses[msg.sender], "EO1");
(_tokens, _weights,_threshold,_rebalanceTime) = IOracle(_OracleAddress).getTokenDetails(_poolIndex);
// Get the new itoken name and symbol from pool
(_name,_symbol,_description) = IOracle(_OracleAddress).getiTokenDetails(_poolIndex);
_poolOwner = address(this);
}else{
_poolOwner = msg.sender;
}
require (_tokens.length == _weights.length, "E06");
require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16");
// Deploy new itokens
_itokenaddr = Iitokendeployer(itokendeployer).createnewitoken(_name, _symbol);
// Add new index.
poolInfo.push(PoolInfo({
tokens : _tokens,
weights : _weights,
totalWeight : calculateTotalWeight(_weights),
active : true,
rebaltime : _rebalanceTime,
currentRebalance : 0,
threshold: _threshold,
lastrebalance: block.timestamp,
itokenaddr: _itokenaddr,
owner: _poolOwner,
description:_description
}));
}
/**
* @notice Internal function to Buy Astra Tokens.
* @param _Amount Amount of Astra token to buy.
* @dev Buy Astra Tokens if user want to pay fees early exit fees by deposit in Astra
*/
function buyAstraToken(uint _Amount) internal returns(uint256){
uint _amount;
uint[] memory _distribution;
IERC20(baseStableCoin).approve(EXCHANGE_CONTRACT, _Amount);
// Get the expected amount of Astra you will recieve for the stable coin.
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, 2, 0);
uint256 minReturn = calculateMinimumReturn(_amount);
// Swap the stabe coin for Astra
IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, minReturn, _distribution, 0);
return _amount;
}
/**
* @notice Stake Astra Tokens.
* @param _amount Amount of Astra token to stake.
* @dev Stake Astra tokens for various functionality like Staking.
*/
function stakeAstra(uint _amount,bool premium)internal{
//Approve the astra amount to stake.
IERC20(ASTRTokenAddress).approve(address(poolChef),_amount);
// Stake the amount on chef contract. It will be staked for 6 months by default 0 pool id will be for the astra pool.
IMAsterChef(poolChef).depositFromDaaAndDAO(0,_amount,6,msg.sender,premium);
}
/**
* @notice Calculate Fees.
* @param _account User account.
* @param _amount Amount user wants to withdraw.
* @param _poolIndex Pool Index
* @dev Calculate Early Exit fees
* feeRate = Early Exit fee rate (Const 2%)
* startBlock = Deposit block
* withdrawBlock = Withdrawal block
* n = number of blocks between n1 and n2
* Averageblockperday = Average block per day (assumed: 6500)
* feeconstant =early exit fee cool down period (const 182)
* Wv = withdrawal value
* EEFv = Wv x EEFr - (EEFr x n/ABPx t)
* If EEFv <=0 then EEFv = 0
*/
function calculatefee(address _account, uint _amount,uint _poolIndex)internal returns(uint256){
// Calculate the early eit fees based on the formula mentioned above.
uint256 feeRate = IPoolConfiguration(_poolConf).getEarlyExitfees();
uint256 startBlock = initialDeposit[_account][_poolIndex];
uint256 withdrawBlock = block.number;
uint256 Averageblockperday = 6500;
uint256 feeconstant = 182;
uint256 blocks = withdrawBlock.sub(startBlock);
uint feesValue = feeRate.mul(blocks).div(100);
feesValue = feesValue.div(Averageblockperday).div(feeconstant);
feesValue = _amount.mul(feeRate).div(100).sub(feesValue);
return feesValue;
}
/**
* @notice Buy Tokens.
* @param _poolIndex Pool Index.
* @dev Buy token initially once threshold is reached this can only be called by poolIn function
*/
function buytokens(uint _poolIndex) internal {
// Check if pool configuration is correct or not.
// This function is called inernally when user deposit in pool or during rebalance to purchase the tokens for given stable coin amount.
require(_poolIndex<poolInfo.length, "E02");
address[] memory returnedTokens;
uint[] memory returnedAmounts;
uint ethValue = poolPendingbalance[_poolIndex];
uint[] memory buf3;
buf = buf3;
// Buy tokens for the pending stable amount
(returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, poolInfo[_poolIndex].tokens, poolInfo[_poolIndex].weights, poolInfo[_poolIndex].totalWeight,buf);
// After tokens are purchased update its details in mapping.
for (uint i = 0; i < returnedTokens.length; i++) {
tokenBalances[_poolIndex][returnedTokens[i]] = tokenBalances[_poolIndex][returnedTokens[i]].add(returnedAmounts[i]);
}
// Update the pool details for the purchased tokens
totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].add(ethValue);
poolPendingbalance[_poolIndex] = 0;
if (poolInfo[_poolIndex].currentRebalance == 0){
poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1);
}
}
/**
* @param _amount Amount of user to Update.
* @param _poolIndex Pool Index.
* @dev Update user Info at the time of deposit in pool
*/
function updateuserinfo(uint _amount,uint _poolIndex) internal {
// Update the user details in mapping. This function is called internally when user deposit in pool or withdraw from pool.
if(poolUserInfo[_poolIndex][msg.sender].active){
// Check if user account is synced with latest rebalance or not. In case not it will update its details.
if(poolUserInfo[_poolIndex][msg.sender].currentPool < poolInfo[_poolIndex].currentRebalance){
poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance);
poolUserInfo[_poolIndex][msg.sender].currentPool = poolInfo[_poolIndex].currentRebalance;
poolUserInfo[_poolIndex][msg.sender].pendingBalance = _amount;
}
else{
poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.add(_amount);
}
}
}
/**
* @dev Get the Token details in Index pool.
*/
function getIndexTokenDetails(uint _poolIndex) external view returns(address[] memory){
return (poolInfo[_poolIndex].tokens);
}
/**
* @dev Get the Token weight details in Index pool.
*/
function getIndexWeightDetails(uint _poolIndex) external view returns(uint[] memory){
return (poolInfo[_poolIndex].weights);
}
/**
@param _amount Amount to chec for slippage.
* @dev Function to calculate the Minimum return for slippage
*/
function calculateMinimumReturn(uint _amount) internal view returns (uint){
// This will get the slippage rate from configuration contract and calculate how much amount user can get after slippage.
uint256 sliprate= IPoolConfiguration(_poolConf).getslippagerate();
uint rate = _amount.mul(sliprate).div(100);
// Return amount after calculating slippage
return _amount.sub(rate);
}
/**
* @dev Get amount of itoken to be received.
* Iv = index value
* Pt = total iTokens outstanding
* Dv = deposit USDT value
* DPv = total USDT value in the pool
* pTR = iTokens received
* If Iv = 0 then pTR = DV
* If pt > 0 then pTR = (Dv/Iv)* Pt
*/
function getItokenValue(uint256 outstandingValue, uint256 indexValue, uint256 depositValue, uint256 totalDepositValue) public view returns(uint256){
// Get the itoken value based on the pool value and total itokens. This method is used in pool In.
// outstandingValue is total itokens.
// Index value is pool current value.
// deposit value is stable coin amount user will deposit
// totalDepositValue is total stable coin value deposited over the pool.
if(indexValue == uint(0)){
return depositValue;
}else if(outstandingValue>0){
return depositValue.mul(outstandingValue).div(indexValue);
}
else{
return depositValue;
}
}
/**
* @dev Deposit in Indices pool either public pool or pool created by Astra.
* @param _tokens Token in which user want to give the amount. Currenly ony Stable stable coin is used.
* @param _values Amount to spend.
* @param _poolIndex Pool Index in which user wants to invest.
*/
function poolIn(address[] calldata _tokens, uint[] calldata _values, uint _poolIndex) external payable nonReentrant {
// Require conditions to check if user is whitelisted or check the token configuration which user is depositing
// Only stable coin and Ether can be used in the initial stages.
require(poolUserInfo[_poolIndex][msg.sender].isenabled, "E07");
require(_poolIndex<poolInfo.length, "E02");
require(_tokens.length <2 && _values.length<2, "E08");
// Check if is the first deposit or user already deposit before this. It will be used to calculate early exit fees
if(!existingUser[msg.sender][_poolIndex]){
existingUser[msg.sender][_poolIndex] = true;
initialDeposit[msg.sender][_poolIndex] = block.number;
}
// Variable that are used internally for logic/calling other functions.
uint ethValue;
uint fees;
uint stableValue;
address[] memory returnedTokens;
uint[] memory returnedAmounts;
//Global variable mainted to push values in it. Now we are removing the any value that are stored prior to this.
_TokensStable = returnedTokens;
_ValuesStable = returnedAmounts;
//Check if give token length is greater than 0 or not.
// If it is zero then user should deposit in ether.
// Other deposit in stable coin
if(_tokens.length == 0) {
// User must deposit some amount in pool
require (msg.value > 0.001 ether, "E09");
// Swap the ether with stable coin.
ethValue = msg.value;
_TokensStable.push(baseStableCoin);
_ValuesStable.push(1);
(returnedTokens, returnedAmounts) = swap(ETH_ADDRESS, ethValue, _TokensStable, _ValuesStable, 1);
stableValue = returnedAmounts[0];
} else {
// //Check if the entered address in the parameter of stable coin or not.
// bool checkaddress = (address(_tokens[0]) == address(baseStableCoin));
// // Check if user send some stable amount and user account has that much stable coin balance
// require(checkaddress,"poolIn: Can only submit Stable coin");
// require(msg.value == 0, "poolIn: Submit one token at a time");
require(IPoolConfiguration(_poolConf).checkStableCoin(_tokens[0]) == true,"E10");
require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "E11");
if(address(_tokens[0]) == address(baseStableCoin)){
stableValue = _values[0];
//Transfer the stable coin from users addresses to contract address.
IERC20(baseStableCoin).safeTransferFrom(msg.sender,address(this),stableValue);
}else{
IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]);
stableValue = sellTokensForStable(_tokens, _values);
}
require(stableValue > 0.001 ether,"E09");
}
// else{
// require(supportedStableCoins[_tokens[0]] == true,"poolIn: Can only submit Stable coin");
// // require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "poolIn: Not enough tokens");
// IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]);
// stableValue = sellTokensForStable(_tokens, _values);
// }
// Get the value of itoken to mint.
uint256 ItokenValue = getItokenValue(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply(), getPoolValue(_poolIndex), stableValue, totalPoolbalance[_poolIndex]);
//Update the balance initially as the pending amount. Once the tokens are purchased it will be updated.
poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].add(stableValue);
//Check if total balance in pool if the threshold is reached.
uint checkbalance = totalPoolbalance[_poolIndex].add(poolPendingbalance[_poolIndex]);
//Update the user details in mapping.
poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.add(ItokenValue);
updateuserinfo(stableValue,_poolIndex);
//Buy the tokens if threshold is reached.
if (poolInfo[_poolIndex].currentRebalance == 0){
if(poolInfo[_poolIndex].threshold <= checkbalance){
buytokens( _poolIndex);
}
}
// poolOutstandingValue[_poolIndex] = poolOutstandingValue[_poolIndex].add();
// Again update details after tokens are bought.
updateuserinfo(0,_poolIndex);
//Mint new itokens and store details in mapping.
Iitoken(poolInfo[_poolIndex].itokenaddr).mint(msg.sender, ItokenValue);
}
/**
* @dev Withdraw from Pool using itoken.
* @param _poolIndex Pool Index to withdraw funds from.
* @param stakeEarlyFees Choose to stake early fees or not.
* @param withdrawAmount Amount to withdraw
*/
function withdraw(uint _poolIndex, bool stakeEarlyFees,bool stakePremium, uint withdrawAmount) external nonReentrant{
require(_poolIndex<poolInfo.length, "E02");
require(Iitoken(poolInfo[_poolIndex].itokenaddr).balanceOf(msg.sender)>=withdrawAmount, "E11");
// Update user info before withdrawal.
updateuserinfo(0,_poolIndex);
// Get the user share on the pool
uint userShare = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance).mul(withdrawAmount).div(poolUserInfo[_poolIndex][msg.sender].Itokens);
uint _balance;
uint _pendingAmount;
// Check if withdrawn amount is greater than pending amount. It will use the pending stable balance after that it will
if(userShare>poolUserInfo[_poolIndex][msg.sender].pendingBalance){
_balance = userShare.sub(poolUserInfo[_poolIndex][msg.sender].pendingBalance);
_pendingAmount = poolUserInfo[_poolIndex][msg.sender].pendingBalance;
}else{
_pendingAmount = userShare;
}
// Call the functions to sell the tokens and recieve stable based on the user share in that pool
uint256 _totalAmount = withdrawTokens(_poolIndex,_balance);
uint fees;
uint256 earlyfees;
uint256 pendingEarlyfees;
// Check if user actually make profit or not.
if(_totalAmount>_balance){
// Charge the performance fees on profit
fees = _totalAmount.sub(_balance).mul(IPoolConfiguration(_poolConf).getperformancefees()).div(100);
}
earlyfees = earlyfees.add(calculatefee(msg.sender,_totalAmount.sub(fees),_poolIndex));
pendingEarlyfees =calculatefee(msg.sender,_pendingAmount,_poolIndex);
poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.sub(withdrawAmount);
//Update details in mapping for the withdrawn aount.
poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].sub( _pendingAmount);
poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.sub(_pendingAmount);
totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].sub(_balance);
poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.sub(_balance);
// Burn the itokens and update details in mapping.
Iitoken(poolInfo[_poolIndex].itokenaddr).burn(msg.sender, withdrawAmount);
withdrawUserAmount(_poolIndex,fees,_totalAmount.sub(fees).sub(earlyfees),_pendingAmount.sub(pendingEarlyfees),earlyfees.add(pendingEarlyfees),stakeEarlyFees,stakePremium);
emit Withdrawn(msg.sender, _balance);
}
// Withdraw amoun and charge fees. Now this single function will be used instead of chargePerformancefees,chargeEarlyFees,withdrawStable,withdrawPendingAmount.
// Some comment code line is for refrence what original code looks like.
function withdrawUserAmount(uint _poolIndex,uint fees,uint totalAmount,uint _pendingAmount, uint earlyfees,bool stakeEarlyFees,bool stakePremium) internal{
// This logic is similar to charge early fees.
// If user choose to stake early exit fees it will buy astra and stake them.
// If user don't want to stake it will be distributes among stakers and index onwer.
// Distribution logic is similar to performance fees so it is integrated with that. Early fees is added with performance fees.
if(stakeEarlyFees == true){
uint returnAmount= buyAstraToken(earlyfees);
stakeAstra(returnAmount,false);
}else{
fees = fees.add(earlyfees);
}
// This logic is similar to withdrawStable stable coins.
// If user choose to stake the amount instead of withdraw it will buy Astra and stake them.
// If user don't want to stake then they will recieve on there account in base stable coins.
if(stakePremium == true){
uint returnAmount= buyAstraToken(totalAmount);
stakeAstra(returnAmount,true);
}
else{
transferTokens(baseStableCoin,msg.sender,totalAmount);
// IERC20(baseStableCoin).safeTransfer(msg.sender, totalAmount);
}
// This logic is similar to withdrawPendingAmount. Early exit fees for pending amount is calculated previously.
// It transfer the pending amount to user account for which token are not bought.
transferTokens(baseStableCoin,msg.sender,_pendingAmount);
// IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount);
// This logic is similar to chargePerformancefees.
// 80 percent of fees will be send to the inde creator. Remaining 20 percent will be distributed among stakers.
if(fees>0){
uint distribution = fees.mul(80).div(100);
if(poolInfo[_poolIndex].owner==address(this)){
transferTokens(baseStableCoin,managerAddresses,distribution);
// IERC20(baseStableCoin).safeTransfer(managerAddresses, distribution);
}else{
transferTokens(baseStableCoin,poolInfo[_poolIndex].owner,distribution);
//IERC20(baseStableCoin).safeTransfer(poolInfo[_poolIndex].owner, distribution);
}
uint returnAmount= buyAstraToken(fees.sub(distribution));
transferTokens(ASTRTokenAddress,address(poolChef),returnAmount);
// IERC20(ASTRTokenAddress).safeTransfer(address(poolChef),returnAmount);
IMAsterChef(poolChef).distributeExitFeeShare(returnAmount);
}
}
function transferTokens(address _token, address _reciever,uint _amount) internal{
IERC20(_token).safeTransfer(_reciever, _amount);
}
/**
* @dev Internal fucntion to Withdraw from Pool using itoken.
* @param _poolIndex Pool Index to withdraw funds from.
* @param _balance Amount to withdraw from Pool.
*/
function withdrawTokens(uint _poolIndex,uint _balance) internal returns(uint256){
uint localWeight;
// Check if total pool balance is more than 0.
if(totalPoolbalance[_poolIndex]>0){
localWeight = _balance.mul(1 ether).div(totalPoolbalance[_poolIndex]);
// localWeight = _balance.mul(1 ether).div(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply());
}
uint _totalAmount;
// Run loop over the tokens in the indices pool to sell the user share.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
uint _amount;
uint[] memory _distribution;
// Get the total token balance in that Pool.
uint tokenBalance = tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]];
// Get the user share from the total token amount
uint withdrawBalance = tokenBalance.mul(localWeight).div(1 ether);
if (withdrawBalance == 0) {
continue;
}
// Skip if withdraw amount is 0
if (poolInfo[_poolIndex].tokens[i] == baseStableCoin) {
_totalAmount = _totalAmount.add(withdrawBalance);
continue;
}
// Approve the Exchnage contract before selling thema.
IERC20(poolInfo[_poolIndex].tokens[i]).approve(EXCHANGE_CONTRACT, withdrawBalance);
// Get the expected amount of tokens to sell
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, 2, 0);
if (_amount == 0) {
continue;
}
_totalAmount = _totalAmount.add(_amount);
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = tokenBalance.sub(withdrawBalance);
// Swap the tokens and get stable in return so that users can withdraw.
IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, _amount, _distribution, 0);
}
return _totalAmount;
}
/**
* @param _poolIndex Pool Index to withdraw funds from.
* @param _pendingAmount Pending Amounts to withdraw from Pool.
* @dev Withdraw the pending amount that is submitted before next.
*/
function withdrawPendingAmount(uint256 _poolIndex,uint _pendingAmount)internal returns(uint256){
uint _earlyfee;
// Withdraw the pending Stable amount for which no tokens are bought. Here early exit fees wil be charged before transfering to user
if(_pendingAmount>0){
//Calculate how much early exit fees must be applicable
_earlyfee = calculatefee(msg.sender,_pendingAmount,_poolIndex);
IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount.sub(_earlyfee));
}
return _earlyfee;
}
/**
* @dev Update pool function to do the rebalaning.
* @param _tokens New tokens to purchase after rebalance.
* @param _weights Weight of new tokens.
* @param _threshold Threshold amount to purchase token.
* @param _rebalanceTime Next Rebalance time.
* @param _poolIndex Pool Index to do rebalance.
*/
function updatePool(address[] memory _tokens,uint[] memory _weights,uint _threshold,uint _rebalanceTime,uint _poolIndex) public nonReentrant{
require(block.timestamp >= poolInfo[_poolIndex].rebaltime,"E12");
// require(poolUserInfo[_poolIndex][msg.sender].currentBalance>poolInfo[_poolIndex].threshold,"Threshold not reached");
// Check if entered indices pool is public or Astra managed.
// Also check if is public pool then request came from the owner or not.
if(poolInfo[_poolIndex].owner != address(this)){
require(_tokens.length == _weights.length, "E02");
require(poolInfo[_poolIndex].owner == msg.sender, "E13");
}else{
(_tokens, _weights,_threshold,_rebalanceTime) = IOracle(IPoolConfiguration(_poolConf).getoracleaddress()).getTokenDetails(_poolIndex);
}
require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16");
address[] memory newTokens;
uint[] memory newWeights;
uint newTotalWeight;
uint _newTotalWeight;
// Loop over the tokens details to update its total weight.
for(uint i = 0; i < _tokens.length; i++) {
require (_tokens[i] != ETH_ADDRESS && _tokens[i] != WETH_ADDRESS);
_newTotalWeight = _newTotalWeight.add(_weights[i]);
}
// Update new tokens details
newTokens = _tokens;
newWeights = _weights;
newTotalWeight = _newTotalWeight;
// Update the pool details for next rebalance
poolInfo[_poolIndex].threshold = _threshold;
poolInfo[_poolIndex].rebaltime = _rebalanceTime;
//Sell old tokens and buy new tokens.
rebalance(newTokens, newWeights,newTotalWeight,_poolIndex);
// Buy the token for Stable which is in pending state.
if(poolPendingbalance[_poolIndex]>0){
buytokens(_poolIndex);
}
}
/**
* @dev Enable or disable Pool can only be called by admin
*/
function setPoolStatus(address _exchange, address _weth, address _stable) external systemOnly {
// poolInfo[_poolIndex].active = _active;
EXCHANGE_CONTRACT = _exchange;
WETH_ADDRESS = _weth;
baseStableCoin = _stable;
}
/**
* @dev Internal function called while updating the pool.
*/
function rebalance(address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint _poolIndex) internal {
require(poolInfo[_poolIndex].currentRebalance >0, "E14");
// Variable used to call the functions internally
uint[] memory buf2;
buf = buf2;
uint ethValue;
address[] memory returnedTokens;
uint[] memory returnedAmounts;
//Updating the balancing of tokens you are selling in storage and make update the balance in main mapping.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
buf.push(tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]]);
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = 0;
}
// Sell the Tokens in pool to recieve tokens
if(totalPoolbalance[_poolIndex]>0){
ethValue = sellTokensForStable(poolInfo[_poolIndex].tokens, buf);
}
// Updating pool configuration/mapping to update the new tokens details
poolInfo[_poolIndex].tokens = newTokens;
poolInfo[_poolIndex].weights = newWeights;
poolInfo[_poolIndex].totalWeight = newTotalWeight;
poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1);
poolInfo[_poolIndex].lastrebalance = block.timestamp;
// Return if you recieve 0 value for selling all the tokens
if (ethValue == 0) {
return;
}
uint[] memory buf3;
buf = buf3;
// Buy new tokens for the pool.
if(totalPoolbalance[_poolIndex]>0){
//Buy new tokens
(returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, newTokens, newWeights,newTotalWeight,buf);
// Update those tokens details in mapping.
for(uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = buf[i];
}
}
}
/**
* @dev Get the current value of pool to check the value of pool
*/
function getPoolValue(uint256 _poolIndex)public view returns(uint256){
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Return the total Amount of Stable you will recieve for selling. This will be total value of pool that it has purchased.
uint _totalAmount;
// Run loops over the tokens in the pool to get the token worth.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]], 2, 0);
if (_amount == 0) {
continue;
}
_totalAmount = _totalAmount.add(_amount);
}
// Return the total values of pool locked
return _totalAmount;
}
/**
* @dev Function to swap two token. Used by other functions during buying and selling. It used where ether is used like at the time of ether deposit.
*/
function swap(address _token, uint _value, address[] memory _tokens, uint[] memory _weights, uint _totalWeight) internal returns(address[] memory, uint[] memory) {
// Use to get the share of particular token based on there share.
uint _tokenPart;
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Run loops over the tokens in the parametess to buy them.
for(uint i = 0; i < _tokens.length; i++) {
// Calculate the share of token based on the weight and the buy for that.
_tokenPart = _value.mul(_weights[i]).div(_totalWeight);
// Get the amount of tokens pool will recieve based on the token selled.
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(_tokens[i]), _tokenPart, 2, 0);
// calculate slippage
uint256 minReturn = calculateMinimumReturn(_amount);
_weights[i] = _amount;
// Check condition if token you are selling is ETH or another ERC20 and then sell the tokens.
if (_token == ETH_ADDRESS) {
_amount = IOneSplit(EXCHANGE_CONTRACT).swap.value(_tokenPart)(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0);
} else {
IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _tokenPart);
_amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0);
}
}
return (_tokens, _weights);
}
/**
* @dev Function to swap two token. It used in case of ERC20 - ERC20 swap.
*/
function swap2(address _token, uint _value, address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint[] memory _buf) internal returns(address[] memory, uint[] memory) {
// Use to get the share of particular token based on there share.
uint _tokenPart;
// Used to get the Expected amount for the token you are selling.
uint _amount;
buf = _buf;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Approve before selling the tokens
IERC20(_token).approve(EXCHANGE_CONTRACT, _value);
// Run loops over the tokens in the parametess to buy them.
for(uint i = 0; i < newTokens.length; i++) {
_tokenPart = _value.mul(newWeights[i]).div(newTotalWeight);
if(_tokenPart == 0) {
buf.push(0);
continue;
}
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(newTokens[i]), _tokenPart, 2, 0);
uint256 minReturn = calculateMinimumReturn(_amount);
buf.push(_amount);
newWeights[i] = _amount;
_amount= IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(newTokens[i]), _tokenPart, minReturn, _distribution, 0);
}
return (newTokens, newWeights);
}
/**
* @dev Sell tokens for Stable is used during the rebalancing to sell previous token and buy new tokens
*/
function sellTokensForStable(address[] memory _tokens, uint[] memory _amounts) internal returns(uint) {
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Return the total Amount of Stable you will recieve for selling
uint _totalAmount;
// Run loops over the tokens in the parametess to sell them.
for(uint i = 0; i < _tokens.length; i++) {
if (_amounts[i] == 0) {
continue;
}
if (_tokens[i] == baseStableCoin) {
_totalAmount = _totalAmount.add(_amounts[i]);
continue;
}
// Approve token access to Exchange contract.
IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _amounts[i]);
// Get the amount of Stable tokens you will recieve for selling tokens
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], 2, 0);
// Skip remaining execution if no token is available
if (_amount == 0) {
continue;
}
// Calculate slippage over the the expected amount
uint256 minReturn = calculateMinimumReturn(_amount);
_totalAmount = _totalAmount.add(_amount);
// Actually swap tokens
_amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], minReturn, _distribution, 0);
}
return _totalAmount;
}
}
pragma solidity ^0.5.0;
// import "./token.sol";
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the decimal of tokens in existence.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
external
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
)
external
payable
returns(uint256 returnAmount);
}
contract IOneSplitMulti is IOneSplit {
function getExpectedReturnWithGasMulti(
IERC20[] calldata tokens,
uint256 amount,
uint256[] calldata parts,
uint256[] calldata flags,
uint256[] calldata destTokenEthPriceTimesGasPrices
)
external
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swapMulti(
IERC20[] calldata tokens,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256[] calldata flags
)
external
payable
returns(uint256 returnAmount);
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
function __init() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity 0.5.17;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
|
Use to get the share of particular token based on there share. Used to get the Expected amount for the token you are selling. Used to get the distributing dex details for the token you are selling. Approve before selling the tokens Run loops over the tokens in the parametess to buy them.
|
function swap2(address _token, uint _value, address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint[] memory _buf) internal returns(address[] memory, uint[] memory) {
uint _tokenPart;
uint _amount;
buf = _buf;
uint[] memory _distribution;
IERC20(_token).approve(EXCHANGE_CONTRACT, _value);
for(uint i = 0; i < newTokens.length; i++) {
_tokenPart = _value.mul(newWeights[i]).div(newTotalWeight);
if(_tokenPart == 0) {
buf.push(0);
continue;
}
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(newTokens[i]), _tokenPart, 2, 0);
uint256 minReturn = calculateMinimumReturn(_amount);
buf.push(_amount);
newWeights[i] = _amount;
_amount= IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(newTokens[i]), _tokenPart, minReturn, _distribution, 0);
}
return (newTokens, newWeights);
}
| 10,118,512 |
pragma solidity ^0.4.24;
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
contract PullPayment {
using SafeMath for uint256;
mapping(address => uint256) public payments;
uint256 public totalPayments;
/**
* @dev Withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
uint256 payment = payments[payee];
require(payment != 0);
require(address(this).balance >= payment);
totalPayments = totalPayments.sub(payment);
payments[payee] = 0;
payee.transfer(payment);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param dest The destination address of the funds.
* @param amount The amount to transfer.
*/
function asyncSend(address dest, uint256 amount) internal {
payments[dest] = payments[dest].add(amount);
totalPayments = totalPayments.add(amount);
}
}
contract CryptoMiningWarInterface {
address public sponsor;
address public administrator;
mapping(address => PlayerData) public players;
struct PlayerData {
uint256 roundNumber;
mapping(uint256 => uint256) minerCount;
uint256 hashrate;
uint256 crystals;
uint256 lastUpdateTime;
uint256 referral_count;
uint256 noQuest;
}
function getHashratePerDay(address /*minerAddr*/) public pure returns (uint256 /*personalProduction*/) {}
function addCrystal( address /*_addr*/, uint256 /*_value*/ ) public pure {}
function subCrystal( address /*_addr*/, uint256 /*_value*/ ) public pure {}
function fallback() public payable {}
}
interface MiniGameInterface {
function isContractMiniGame() external pure returns( bool _isContractMiniGame );
function fallback() external payable;
}
contract CryptoEngineer is PullPayment{
// engineer info
address public administrator;
uint256 public prizePool = 0;
uint256 public engineerRoundNumber = 0;
uint256 public numberOfEngineer;
uint256 public numberOfBoosts;
address public gameSponsor;
uint256 public gameSponsorPrice;
uint256 private randNonce;
uint256 constant public VIRUS_MINING_PERIOD = 86400;
uint256 constant public VIRUS_NORMAL = 0;
uint256 constant public HALF_TIME_ATK = 60 * 15;
// mining war game infomation
address public miningWarContractAddress;
address public miningWarAdministrator;
uint256 constant public CRTSTAL_MINING_PERIOD = 86400;
uint256 constant public BASE_PRICE = 0.01 ether;
CryptoMiningWarInterface public MiningWarContract;
// engineer player information
mapping(address => PlayerData) public players;
// engineer boost information
mapping(uint256 => BoostData) public boostData;
// engineer information
mapping(uint256 => EngineerData) public engineers;
// engineer virut information
mapping(uint256 => VirusData) public virus;
// minigame info
mapping(address => bool) public miniGames;
struct PlayerData {
uint256 engineerRoundNumber;
mapping(uint256 => uint256) engineersCount;
uint256 virusNumber;
uint256 virusDefence;
uint256 research;
uint256 lastUpdateTime;
uint256 nextTimeAtk;
uint256 endTimeUnequalledDef;
}
struct BoostData {
address owner;
uint256 boostRate;
uint256 basePrice;
}
struct EngineerData {
uint256 basePrice;
uint256 baseETH;
uint256 baseResearch;
uint256 limit;
}
struct VirusData {
uint256 atk;
uint256 def;
}
event eventEndAttack(
address playerAtk,
address playerDef,
bool isWin,
uint256 winCrystals,
uint256 virusPlayerAtkDead,
uint256 virusPlayerDefDead,
uint256 timeAtk,
uint256 engineerRoundNumber,
uint256 atk,
uint256 def // def of player
);
modifier disableContract()
{
require(tx.origin == msg.sender);
_;
}
modifier isAdministrator()
{
require(msg.sender == administrator);
_;
}
modifier onlyContractsMiniGame()
{
require(miniGames[msg.sender] == true);
_;
}
constructor() public {
administrator = msg.sender;
//default game sponsor
gameSponsor = administrator;
gameSponsorPrice = 0.32 ether;
// set interface main contract
miningWarContractAddress = address(0xf84c61bb982041c030b8580d1634f00fffb89059);
MiningWarContract = CryptoMiningWarInterface(miningWarContractAddress);
miningWarAdministrator = MiningWarContract.administrator();
numberOfEngineer = 8;
numberOfBoosts = 5;
// setting virusupd
virus[VIRUS_NORMAL] = VirusData(1,1);
// price crystals price ETH research limit
engineers[0] = EngineerData(10, BASE_PRICE * 0, 10, 10 ); //lv1
engineers[1] = EngineerData(50, BASE_PRICE * 1, 200, 2 ); //lv2
engineers[2] = EngineerData(200, BASE_PRICE * 2, 800, 4 ); //lv3
engineers[3] = EngineerData(800, BASE_PRICE * 4, 3200, 8 ); //lv4
engineers[4] = EngineerData(3200, BASE_PRICE * 8, 9600, 16 ); //lv5
engineers[5] = EngineerData(12800, BASE_PRICE * 16, 38400, 32 ); //lv6
engineers[6] = EngineerData(102400, BASE_PRICE * 32, 204800, 64 ); //lv7
engineers[7] = EngineerData(819200, BASE_PRICE * 64, 819200, 65536); //lv8
initData();
}
function () public payable
{
addPrizePool(msg.value);
}
function initData() private
{
//init booster data
boostData[0] = BoostData(0x0, 150, BASE_PRICE * 1);
boostData[1] = BoostData(0x0, 175, BASE_PRICE * 2);
boostData[2] = BoostData(0x0, 200, BASE_PRICE * 4);
boostData[3] = BoostData(0x0, 225, BASE_PRICE * 8);
boostData[4] = BoostData(0x0, 250, BASE_PRICE * 16);
}
/**
* @dev MainContract used this function to verify game's contract
*/
function isContractMiniGame() public pure returns( bool _isContractMiniGame )
{
_isContractMiniGame = true;
}
/**
* @dev Main Contract call this function to setup mini game.
*/
function setupMiniGame( uint256 /*_miningWarRoundNumber*/, uint256 /*_miningWarDeadline*/ ) public
{
}
//--------------------------------------------------------------------------
// SETTING CONTRACT MINI GAME
//--------------------------------------------------------------------------
function setContractsMiniGame( address _contractMiniGameAddress ) public isAdministrator
{
MiniGameInterface MiniGame = MiniGameInterface( _contractMiniGameAddress );
if( MiniGame.isContractMiniGame() == false ) { revert(); }
miniGames[_contractMiniGameAddress] = true;
}
/**
* @dev remove mini game contract from main contract
* @param _contractMiniGameAddress mini game contract address
*/
function removeContractMiniGame(address _contractMiniGameAddress) public isAdministrator
{
miniGames[_contractMiniGameAddress] = false;
}
//@dev use this function in case of bug
function upgrade(address addr) public
{
require(msg.sender == administrator);
selfdestruct(addr);
}
//--------------------------------------------------------------------------
// BOOSTER
//--------------------------------------------------------------------------
function buyBooster(uint256 idx) public payable
{
require(idx < numberOfBoosts);
BoostData storage b = boostData[idx];
if (msg.value < b.basePrice || msg.sender == b.owner) {
revert();
}
address beneficiary = b.owner;
uint256 devFeePrize = devFee(b.basePrice);
distributedToOwner(devFeePrize);
addMiningWarPrizePool(devFeePrize);
addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3)));
updateVirus(msg.sender);
if ( beneficiary != 0x0 ) {
updateVirus(beneficiary);
}
// transfer ownership
b.owner = msg.sender;
}
function getBoosterData(uint256 idx) public view returns (address _owner,uint256 _boostRate, uint256 _basePrice)
{
require(idx < numberOfBoosts);
BoostData memory b = boostData[idx];
_owner = b.owner;
_boostRate = b.boostRate;
_basePrice = b.basePrice;
}
function hasBooster(address addr) public view returns (uint256 _boostIdx)
{
_boostIdx = 999;
for(uint256 i = 0; i < numberOfBoosts; i++){
uint256 revert_i = numberOfBoosts - i - 1;
if(boostData[revert_i].owner == addr){
_boostIdx = revert_i;
break;
}
}
}
//--------------------------------------------------------------------------
// GAME SPONSOR
//--------------------------------------------------------------------------
/**
*/
function becomeGameSponsor() public payable disableContract
{
uint256 gameSponsorPriceFee = SafeMath.div(SafeMath.mul(gameSponsorPrice, 150), 100);
require(msg.value >= gameSponsorPriceFee);
require(msg.sender != gameSponsor);
//
uint256 repayPrice = SafeMath.div(SafeMath.mul(gameSponsorPrice, 110), 100);
gameSponsor.send(repayPrice);
// add to prize pool
addPrizePool(SafeMath.sub(msg.value, repayPrice));
// update game sponsor info
gameSponsor = msg.sender;
gameSponsorPrice = gameSponsorPriceFee;
}
/**
* @dev add virus for player
* @param _addr player address
* @param _value number of virus
*/
function addVirus(address _addr, uint256 _value) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
uint256 additionalVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
p.virusNumber = SafeMath.add(p.virusNumber, additionalVirus);
}
/**
* @dev subtract virus of player
* @param _addr player address
* @param _value number virus subtract
*/
function subVirus(address _addr, uint256 _value) public onlyContractsMiniGame
{
updateVirus(_addr);
PlayerData storage p = players[_addr];
uint256 subtractVirus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if ( p.virusNumber < subtractVirus ) { revert(); }
p.virusNumber = SafeMath.sub(p.virusNumber, subtractVirus);
}
/**
* @dev additional time unequalled defence
* @param _addr player address
*/
function setAtkNowForPlayer(address _addr) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
p.nextTimeAtk = now;
}
function addTimeUnequalledDefence(address _addr, uint256 _value) public onlyContractsMiniGame
{
PlayerData storage p = players[_addr];
uint256 currentTimeUnequalled = p.endTimeUnequalledDef;
if (currentTimeUnequalled < now) {
currentTimeUnequalled = now;
}
p.endTimeUnequalledDef = SafeMath.add(currentTimeUnequalled, _value);
}
/**
* @dev claim price pool to next new game
* @param _addr mini game contract address
* @param _value eth claim;
*/
function claimPrizePool(address _addr, uint256 _value) public onlyContractsMiniGame
{
require(prizePool > _value);
prizePool = SafeMath.sub(prizePool, _value);
MiniGameInterface MiniGame = MiniGameInterface( _addr );
MiniGame.fallback.value(_value)();
}
//--------------------------------------------------------------------------
// WARS
//--------------------------------------------------------------------------
function setVirusInfo(uint256 _atk, uint256 _def) public isAdministrator
{
VirusData storage v = virus[VIRUS_NORMAL];
v.atk = _atk;
v.def = _def;
}
/**
* @dev add virus defence
* @param _value number of virus defence
*/
function addVirusDefence(uint256 _value) public disableContract
{
updateVirus(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 _virus = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if ( p.virusNumber < _virus ) { revert(); }
p.virusDefence = SafeMath.add(p.virusDefence, _virus);
p.virusNumber = SafeMath.sub(p.virusNumber, _virus);
}
/**
* @dev atk and def ramdom from 50% to 150%
* @param _defAddress player address to attack
* @param _value number of virus send to attack
*/
function attack( address _defAddress, uint256 _value) public disableContract
{
require(canAttack(msg.sender, _defAddress) == true);
updateVirus(msg.sender);
PlayerData storage pAtk = players[msg.sender];
PlayerData storage pDef = players[_defAddress];
uint256 virusAtk = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
if (pAtk.virusNumber < virusAtk) { revert(); }
// current crystals of defence geater 5000 crystals
if (calCurrentCrystals(_defAddress) < 5000) { revert(); }
// virus normal info
VirusData memory v = virus[VIRUS_NORMAL];
// ramdom attack and defence for players from 50% to 150%
uint256 rateAtk = 50 + randomNumber(msg.sender, 100);
uint256 rateDef = 50 + randomNumber(_defAddress, 100);
// calculate attack of player attack and defence of player defence
uint256 atk = SafeMath.div(SafeMath.mul(SafeMath.mul(virusAtk, v.atk), rateAtk), 100);
uint256 def = SafeMath.div(SafeMath.mul(SafeMath.mul(pDef.virusDefence, v.def), rateDef), 100);
bool isWin = false;
uint256 virusPlayerAtkDead = 0;
uint256 virusPlayerDefDead = 0;
/**
* @dev calculate virus dead in war
*/
// if attack > defense, sub virus of player atk and player def.
// number virus for kin
if (atk > def) {
virusPlayerAtkDead = SafeMath.min(virusAtk, SafeMath.div(SafeMath.mul(def, 100), SafeMath.mul(v.atk, rateAtk)));
virusPlayerDefDead = pDef.virusDefence;
isWin = true;
}
/**
* @dev update result of war and call end attack
*/
pAtk.virusNumber = SafeMath.sub(pAtk.virusNumber, virusPlayerAtkDead);
pDef.virusDefence = SafeMath.sub(pDef.virusDefence, virusPlayerDefDead);
//update player attack
pAtk.nextTimeAtk = now + HALF_TIME_ATK;
endAttack(msg.sender,_defAddress,isWin, virusPlayerAtkDead, virusPlayerDefDead, atk, def);
}
/**
* @dev check player can atk or not
* @param _atkAddress player address attack
* @param _defAddress player address defence
*/
function canAttack(address _atkAddress, address _defAddress) public view returns(bool _canAtk)
{
if (
_atkAddress != _defAddress &&
players[_atkAddress].nextTimeAtk <= now &&
players[_defAddress].endTimeUnequalledDef < now
)
{
_canAtk = true;
}
}
/**
* @dev result of war
* @param _atkAddress player address attack
* @param _defAddress player address defence
*/
function endAttack(
address _atkAddress,
address _defAddress,
bool _isWin,
uint256 _virusPlayerAtkDead,
uint256 _virusPlayerDefDead,
uint256 _atk,
uint256 _def
) private
{
uint256 winCrystals;
if ( _isWin == true ) {
uint256 pDefCrystals = calCurrentCrystals(_defAddress);
// subtract random 10% to 50% current crystals of player defence
uint256 rate =10 + randomNumber(_defAddress, 40);
winCrystals = SafeMath.div(SafeMath.mul(pDefCrystals,rate),100);
if (winCrystals > 0) {
MiningWarContract.subCrystal(_defAddress, winCrystals);
MiningWarContract.addCrystal(_atkAddress, winCrystals);
}
}
emit eventEndAttack(_atkAddress, _defAddress, _isWin, winCrystals, _virusPlayerAtkDead, _virusPlayerDefDead, now, engineerRoundNumber, _atk, _def);
}
//--------------------------------------------------------------------------
// PLAYERS
//--------------------------------------------------------------------------
/**
*/
function buyEngineer(uint256[] engineerNumbers) public payable disableContract
{
require(engineerNumbers.length == numberOfEngineer);
updateVirus(msg.sender);
PlayerData storage p = players[msg.sender];
uint256 priceCrystals = 0;
uint256 priceEth = 0;
uint256 research = 0;
for (uint256 engineerIdx = 0; engineerIdx < numberOfEngineer; engineerIdx++) {
uint256 engineerNumber = engineerNumbers[engineerIdx];
EngineerData memory e = engineers[engineerIdx];
// require for engineerNumber
if(engineerNumber > e.limit || engineerNumber < 0) {
revert();
}
// engineer you want buy
if (engineerNumber > 0) {
uint256 currentEngineerCount = p.engineersCount[engineerIdx];
// update player data
p.engineersCount[engineerIdx] = SafeMath.min(e.limit, SafeMath.add(p.engineersCount[engineerIdx], engineerNumber));
// calculate no research you want buy
research = SafeMath.add(research, SafeMath.mul(SafeMath.sub(p.engineersCount[engineerIdx],currentEngineerCount), e.baseResearch));
// calculate price crystals and eth you will pay
priceCrystals = SafeMath.add(priceCrystals, SafeMath.mul(e.basePrice, engineerNumber));
priceEth = SafeMath.add(priceEth, SafeMath.mul(e.baseETH, engineerNumber));
}
}
// check price eth
if (priceEth < msg.value) {
revert();
}
uint256 devFeePrize = devFee(priceEth);
distributedToOwner(devFeePrize);
addMiningWarPrizePool(devFeePrize);
addPrizePool(SafeMath.sub(msg.value, SafeMath.mul(devFeePrize,3)));
// pay and update
MiningWarContract.subCrystal(msg.sender, priceCrystals);
updateResearch(msg.sender, research);
}
/**
* @dev update virus for player
* @param _addr player address
*/
function updateVirus(address _addr) private
{
if (players[_addr].engineerRoundNumber != engineerRoundNumber) {
return resetPlayer(_addr);
}
PlayerData storage p = players[_addr];
p.virusNumber = calculateCurrentVirus(_addr);
p.lastUpdateTime = now;
}
function calculateCurrentVirus(address _addr) public view returns(uint256 _currentVirus)
{
PlayerData memory p = players[_addr];
uint256 secondsPassed = SafeMath.sub(now, p.lastUpdateTime);
uint256 researchPerDay = getResearchPerDay(_addr);
_currentVirus = p.virusNumber;
if (researchPerDay > 0) {
_currentVirus = SafeMath.add(_currentVirus, SafeMath.mul(researchPerDay, secondsPassed));
}
}
/**
* @dev reset player data
* @param _addr player address
*/
function resetPlayer(address _addr) private
{
require(players[_addr].engineerRoundNumber != engineerRoundNumber);
PlayerData storage p = players[_addr];
p.engineerRoundNumber = engineerRoundNumber;
p.virusNumber = 0;
p.virusDefence = 0;
p.research = 0;
p.lastUpdateTime = now;
p.nextTimeAtk = now;
p.endTimeUnequalledDef = now;
// reset player engineer data
for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) {
p.engineersCount[idx] = 0;
}
}
/**
* @dev update research for player
* @param _addr player address
* @param _research number research want to add
*/
function updateResearch(address _addr, uint256 _research) private
{
PlayerData storage p = players[_addr];
p.research = SafeMath.add(p.research, _research);
}
function getResearchPerDay(address _addr) public view returns( uint256 _researchPerDay)
{
PlayerData memory p = players[_addr];
_researchPerDay = p.research;
uint256 boosterIdx = hasBooster(_addr);
if (boosterIdx != 999) {
BoostData memory b = boostData[boosterIdx];
_researchPerDay = SafeMath.div(SafeMath.mul(_researchPerDay, b.boostRate), 100);
}
}
/**
* @dev get player data
* @param _addr player address
*/
function getPlayerData(address _addr)
public
view
returns(
uint256 _engineerRoundNumber,
uint256 _virusNumber,
uint256 _virusDefence,
uint256 _research,
uint256 _researchPerDay,
uint256 _lastUpdateTime,
uint256[8] _engineersCount,
uint256 _nextTimeAtk,
uint256 _endTimeUnequalledDef
)
{
PlayerData storage p = players[_addr];
for ( uint256 idx = 0; idx < numberOfEngineer; idx++ ) {
_engineersCount[idx] = p.engineersCount[idx];
}
_engineerRoundNumber = p.engineerRoundNumber;
_virusNumber = SafeMath.div(p.virusNumber, VIRUS_MINING_PERIOD);
_virusDefence = SafeMath.div(p.virusDefence, VIRUS_MINING_PERIOD);
_nextTimeAtk = p.nextTimeAtk;
_lastUpdateTime = p.lastUpdateTime;
_endTimeUnequalledDef = p.endTimeUnequalledDef;
_research = p.research;
_researchPerDay = getResearchPerDay(_addr);
}
//--------------------------------------------------------------------------
// INTERNAL
//--------------------------------------------------------------------------
function addPrizePool(uint256 _value) private
{
prizePool = SafeMath.add(prizePool, _value);
}
/**
* @dev add 5% value of transaction payable
*/
function addMiningWarPrizePool(uint256 _value) private
{
MiningWarContract.fallback.value(_value)();
}
/**
* @dev calculate current crystals of player
* @param _addr player address
*/
function calCurrentCrystals(address _addr) public view returns(uint256 _currentCrystals)
{
uint256 lastUpdateTime;
(,, _currentCrystals, lastUpdateTime) = getMiningWarPlayerData(_addr);
uint256 hashratePerDay = getHashratePerDay(_addr);
uint256 secondsPassed = SafeMath.sub(now, lastUpdateTime);
if (hashratePerDay > 0) {
_currentCrystals = SafeMath.add(_currentCrystals, SafeMath.mul(hashratePerDay, secondsPassed));
}
_currentCrystals = SafeMath.div(_currentCrystals, CRTSTAL_MINING_PERIOD);
}
function devFee(uint256 _amount) private pure returns(uint256)
{
return SafeMath.div(SafeMath.mul(_amount, 5), 100);
}
/**
* @dev with transaction payable send 5% value for admin and sponsor
* @param _value fee
*/
function distributedToOwner(uint256 _value) private
{
gameSponsor.send(_value);
miningWarAdministrator.send(_value);
}
function randomNumber(address _addr, uint256 _maxNumber) private returns(uint256)
{
randNonce = randNonce + 1;
return uint256(keccak256(abi.encodePacked(now, _addr, randNonce))) % _maxNumber;
}
function getMiningWarPlayerData(address _addr) private view returns(uint256 _roundNumber, uint256 _hashrate, uint256 _crytals, uint256 _lastUpdateTime)
{
(_roundNumber,_hashrate,_crytals,_lastUpdateTime,,)= MiningWarContract.players(_addr);
}
function getHashratePerDay(address _addr) private view returns(uint256)
{
return MiningWarContract.getHashratePerDay(_addr);
}
}
|
atk and def ramdom from 50% to 150% _defAddress player address to attack _value number of virus send to attack/ current crystals of defence geater 5000 crystals virus normal info ramdom attack and defence for players from 50% to 150% calculate attack of player attack and defence of player defence if attack > defense, sub virus of player atk and player def. number virus for kin
|
function attack( address _defAddress, uint256 _value) public disableContract
{
require(canAttack(msg.sender, _defAddress) == true);
updateVirus(msg.sender);
PlayerData storage pAtk = players[msg.sender];
PlayerData storage pDef = players[_defAddress];
uint256 virusAtk = SafeMath.mul(_value,VIRUS_MINING_PERIOD);
VirusData memory v = virus[VIRUS_NORMAL];
uint256 rateAtk = 50 + randomNumber(msg.sender, 100);
uint256 rateDef = 50 + randomNumber(_defAddress, 100);
uint256 atk = SafeMath.div(SafeMath.mul(SafeMath.mul(virusAtk, v.atk), rateAtk), 100);
uint256 def = SafeMath.div(SafeMath.mul(SafeMath.mul(pDef.virusDefence, v.def), rateDef), 100);
bool isWin = false;
uint256 virusPlayerAtkDead = 0;
uint256 virusPlayerDefDead = 0;
if (atk > def) {
virusPlayerAtkDead = SafeMath.min(virusAtk, SafeMath.div(SafeMath.mul(def, 100), SafeMath.mul(v.atk, rateAtk)));
virusPlayerDefDead = pDef.virusDefence;
isWin = true;
}
pDef.virusDefence = SafeMath.sub(pDef.virusDefence, virusPlayerDefDead);
endAttack(msg.sender,_defAddress,isWin, virusPlayerAtkDead, virusPlayerDefDead, atk, def);
}
| 976,206 |
./partial_match/3/0x7ddfE63d48b6fF1932DA7b0a395634a22B86292a/sources/USDTFATLPTokenCashPool.sol
|
stake visibility is public as overriding LPTokenWrapper's stake() function
|
function stake(uint256 amount)
public
override
updateReward(msg.sender)
checkStart
{
require(amount > 0, 'Cannot stake 0');
super.stake(amount);
emit Staked(msg.sender, amount);
}
| 5,259,029 |
/**
*Submitted for verification at Etherscan.io on 2020-01-30
*/
// File: contracts/math/SafeMath.sol
pragma solidity 0.5.12;
/// @title SafeMath
/// @dev Math operations with safety checks that throw on error
library SafeMath {
/// @dev Add two integers
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
//assert(c >= a);
return c;
}
/// @dev Subtract two integers
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
/// @dev Multiply tow integers
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
/// @dev Floor divide two integers
function div(uint a, uint b) internal pure returns (uint) {
return a / b;
}
}
// File: contracts/ownership/Ownable.sol
pragma solidity 0.5.12;
/// @title Ownable
/// @dev Provide a simple access control with a single authority: the owner
contract Ownable {
// Ethereum address of current owner
address public owner;
// Ethereum address of the next owner
// (has to claim ownership first to become effective owner)
address public newOwner;
// @dev Log event on ownership transferred
// @param previousOwner Ethereum address of previous owner
// @param newOwner Ethereum address of new owner
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev Forbid call by anyone but owner
modifier onlyOwner() {
require(msg.sender == owner, "Restricted to owner");
_;
}
/// @dev Deployer account becomes initial owner
constructor() public {
owner = msg.sender;
}
/// @dev Transfer ownership to a new Ethereum account (safe method)
/// Note: the new owner has to claim his ownership to become effective owner.
/// @param _newOwner Ethereum address to transfer ownership to
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0), "New owner is zero");
newOwner = _newOwner;
}
/// @dev Transfer ownership to a new Ethereum account (unsafe method)
/// Note: It's strongly recommended to use the safe variant via transferOwnership
/// and claimOwnership, to prevent accidental transfers to a wrong address.
/// @param _newOwner Ethereum address to transfer ownership to
function transferOwnershipUnsafe(address _newOwner) public onlyOwner {
require(_newOwner != address(0x0), "New owner is zero");
_transferOwnership(_newOwner);
}
/// @dev Become effective owner (if dedicated so by previous owner)
function claimOwnership() public {
require(msg.sender == newOwner, "Restricted to new owner");
_transferOwnership(msg.sender);
}
/// @dev Transfer ownership (internal method)
/// @param _newOwner Ethereum address to transfer ownership to
function _transferOwnership(address _newOwner) private {
if (_newOwner != owner) {
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
newOwner = address(0x0);
}
}
// File: contracts/whitelist/Whitelist.sol
pragma solidity 0.5.12;
/// @title Whitelist
/// @author STOKR
contract Whitelist is Ownable {
// Set of admins
mapping(address => bool) public admins;
// Set of Whitelisted addresses
mapping(address => bool) public isWhitelisted;
/// @dev Log entry on admin added to set
/// @param admin An Ethereum address
event AdminAdded(address indexed admin);
/// @dev Log entry on admin removed from set
/// @param admin An Ethereum address
event AdminRemoved(address indexed admin);
/// @dev Log entry on investor added set
/// @param admin An Ethereum address
/// @param investor An Ethereum address
event InvestorAdded(address indexed admin, address indexed investor);
/// @dev Log entry on investor removed from set
/// @param admin An Ethereum address
/// @param investor An Ethereum address
event InvestorRemoved(address indexed admin, address indexed investor);
/// @dev Only admin
modifier onlyAdmin() {
require(admins[msg.sender], "Restricted to whitelist admin");
_;
}
/// @dev Add admin to set
/// @param _admin An Ethereum address
function addAdmin(address _admin) public onlyOwner {
require(_admin != address(0x0), "Whitelist admin is zero");
if (!admins[_admin]) {
admins[_admin] = true;
emit AdminAdded(_admin);
}
}
/// @dev Remove admin from set
/// @param _admin An Ethereum address
function removeAdmin(address _admin) public onlyOwner {
require(_admin != address(0x0), "Whitelist admin is zero"); // Necessary?
if (admins[_admin]) {
admins[_admin] = false;
emit AdminRemoved(_admin);
}
}
/// @dev Add investor to set of whitelisted addresses
/// @param _investors A list where each entry is an Ethereum address
function addToWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (!isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = true;
emit InvestorAdded(msg.sender, _investors[i]);
}
}
}
/// @dev Remove investor from set of whitelisted addresses
/// @param _investors A list where each entry is an Ethereum address
function removeFromWhitelist(address[] calldata _investors) external onlyAdmin {
for (uint256 i = 0; i < _investors.length; i++) {
if (isWhitelisted[_investors[i]]) {
isWhitelisted[_investors[i]] = false;
emit InvestorRemoved(msg.sender, _investors[i]);
}
}
}
}
// File: contracts/whitelist/Whitelisted.sol
pragma solidity 0.5.12;
/// @title Whitelisted
/// @author STOKR
contract Whitelisted is Ownable {
Whitelist public whitelist;
/// @dev Log entry on change of whitelist contract instance
/// @param previous Ethereum address of previous whitelist
/// @param current Ethereum address of new whitelist
event WhitelistChange(address indexed previous, address indexed current);
/// @dev Ensure only whitelisted addresses can call
modifier onlyWhitelisted(address _address) {
require(whitelist.isWhitelisted(_address), "Address is not whitelisted");
_;
}
/// @dev Constructor
/// @param _whitelist address of whitelist contract
constructor(Whitelist _whitelist) public {
setWhitelist(_whitelist);
}
/// @dev Set the address of whitelist
/// @param _newWhitelist An Ethereum address
function setWhitelist(Whitelist _newWhitelist) public onlyOwner {
require(address(_newWhitelist) != address(0x0), "Whitelist address is zero");
if (address(_newWhitelist) != address(whitelist)) {
emit WhitelistChange(address(whitelist), address(_newWhitelist));
whitelist = Whitelist(_newWhitelist);
}
}
}
// File: contracts/token/ERC20.sol
pragma solidity 0.5.12;
/// @title ERC20 interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
interface ERC20 {
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
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);
}
// File: contracts/token/ProfitSharing.sol
pragma solidity 0.5.12;
/// @title ProfitSharing
/// @author STOKR
contract ProfitSharing is Ownable {
using SafeMath for uint;
// An InvestorAccount object keeps track of the investor's
// - balance: amount of tokens he/she holds (always up-to-date)
// - profitShare: amount of wei this token owed him/her at the last update
// - lastTotalProfits: determines when his/her profitShare was updated
// Note, this construction requires:
// - totalProfits to never decrease
// - totalSupply to be fixed
// - profitShare of all involved parties to get updated prior to any token transfer
// - lastTotalProfits to be set to current totalProfits upon profitShare update
struct InvestorAccount {
uint balance; // token balance
uint lastTotalProfits; // totalProfits [wei] at the time of last profit share update
uint profitShare; // profit share [wei] of last update
}
// Investor account database
mapping(address => InvestorAccount) public accounts;
// Authority who is allowed to deposit profits [wei] on this
address public profitDepositor;
// Authority who is allowed to distribute profit shares [wei] to investors
// (so, that they don't need to withdraw it by themselves)
address public profitDistributor;
// Amount of total profits [wei] stored to this token
// In contrast to the wei balance (which may be reduced due to profit share withdrawal)
// this value will never decrease
uint public totalProfits;
// As long as the total supply isn't fixed, i.e. new tokens can appear out of thin air,
// the investors' profit shares aren't determined
bool public totalSupplyIsFixed;
// Total amount of tokens
uint internal totalSupply_;
/// @dev Log entry on change of profit deposit authority
/// @param previous Ethereum address of previous profit depositor
/// @param current Ethereum address of new profit depositor
event ProfitDepositorChange(
address indexed previous,
address indexed current
);
/// @dev Log entry on change of profit distribution authority
/// @param previous Ethereum address of previous profit distributor
/// @param current Ethereum address of new profit distributor
event ProfitDistributorChange(
address indexed previous,
address indexed current
);
/// @dev Log entry on profit deposit
/// @param depositor Profit depositor's address
/// @param amount Deposited profits in wei
event ProfitDeposit(
address indexed depositor,
uint amount
);
/// @dev Log entry on profit share update
/// @param investor Investor's address
/// @param amount New wei amount the token owes the investor
event ProfitShareUpdate(
address indexed investor,
uint amount
);
/// @dev Log entry on profit withdrawal
/// @param investor Investor's address
/// @param amount Wei amount the investor withdrew from this token
event ProfitShareWithdrawal(
address indexed investor,
address indexed beneficiary,
uint amount
);
/// @dev Restrict operation to profit deposit authority only
modifier onlyProfitDepositor() {
require(msg.sender == profitDepositor, "Restricted to profit depositor");
_;
}
/// @dev Restrict operation to profit distribution authority only
modifier onlyProfitDistributor() {
require(msg.sender == profitDistributor, "Restricted to profit distributor");
_;
}
/// @dev Restrict operation to when total supply doesn't change anymore
modifier onlyWhenTotalSupplyIsFixed() {
require(totalSupplyIsFixed, "Total supply may change");
_;
}
/// @dev Constructor
/// @param _profitDepositor Profit deposit authority
constructor(address _profitDepositor, address _profitDistributor) public {
setProfitDepositor(_profitDepositor);
setProfitDistributor(_profitDistributor);
}
/// @dev Profit deposit if possible via fallback function
function () external payable {
require(msg.data.length == 0, "Fallback call with data");
depositProfit();
}
/// @dev Change profit depositor
/// @param _newProfitDepositor An Ethereum address
function setProfitDepositor(address _newProfitDepositor) public onlyOwner {
require(_newProfitDepositor != address(0x0), "New profit depositor is zero");
if (_newProfitDepositor != profitDepositor) {
emit ProfitDepositorChange(profitDepositor, _newProfitDepositor);
profitDepositor = _newProfitDepositor;
}
}
/// @dev Change profit distributor
/// @param _newProfitDistributor An Ethereum address
function setProfitDistributor(address _newProfitDistributor) public onlyOwner {
require(_newProfitDistributor != address(0x0), "New profit distributor is zero");
if (_newProfitDistributor != profitDistributor) {
emit ProfitDistributorChange(profitDistributor, _newProfitDistributor);
profitDistributor = _newProfitDistributor;
}
}
/// @dev Deposit profit
function depositProfit() public payable onlyProfitDepositor onlyWhenTotalSupplyIsFixed {
require(totalSupply_ > 0, "Total supply is zero");
totalProfits = totalProfits.add(msg.value);
emit ProfitDeposit(msg.sender, msg.value);
}
/// @dev Profit share owing
/// @param _investor An Ethereum address
/// @return A positive number
function profitShareOwing(address _investor) public view returns (uint) {
if (!totalSupplyIsFixed || totalSupply_ == 0) {
return 0;
}
InvestorAccount memory account = accounts[_investor];
return totalProfits.sub(account.lastTotalProfits)
.mul(account.balance)
.div(totalSupply_)
.add(account.profitShare);
}
/// @dev Update profit share
/// @param _investor An Ethereum address
function updateProfitShare(address _investor) public onlyWhenTotalSupplyIsFixed {
uint newProfitShare = profitShareOwing(_investor);
accounts[_investor].lastTotalProfits = totalProfits;
accounts[_investor].profitShare = newProfitShare;
emit ProfitShareUpdate(_investor, newProfitShare);
}
/// @dev Withdraw profit share
function withdrawProfitShare() public {
_withdrawProfitShare(msg.sender, msg.sender);
}
function withdrawProfitShareTo(address payable _beneficiary) public {
_withdrawProfitShare(msg.sender, _beneficiary);
}
/// @dev Withdraw profit share
function withdrawProfitShares(address payable[] calldata _investors)
external
onlyProfitDistributor
{
for (uint i = 0; i < _investors.length; ++i) {
_withdrawProfitShare(_investors[i], _investors[i]);
}
}
/// @dev Withdraw profit share
function _withdrawProfitShare(address _investor, address payable _beneficiary) internal {
updateProfitShare(_investor);
uint withdrawnProfitShare = accounts[_investor].profitShare;
accounts[_investor].profitShare = 0;
_beneficiary.transfer(withdrawnProfitShare);
emit ProfitShareWithdrawal(_investor, _beneficiary, withdrawnProfitShare);
}
}
// File: contracts/token/MintableToken.sol
pragma solidity 0.5.12;
/// @title MintableToken
/// @author STOKR
/// @dev Extension of the ERC20 compliant ProfitSharing Token
/// that allows the creation of tokens via minting for a
/// limited time period (until minting gets finished).
contract MintableToken is ERC20, ProfitSharing, Whitelisted {
address public minter;
uint public numberOfInvestors = 0;
/// @dev Log entry on mint
/// @param to Beneficiary who received the newly minted tokens
/// @param amount The amount of minted token units
event Minted(address indexed to, uint amount);
/// @dev Log entry on mint finished
event MintFinished();
/// @dev Restrict an operation to be callable only by the minter
modifier onlyMinter() {
require(msg.sender == minter, "Restricted to minter");
_;
}
/// @dev Restrict an operation to be executable only while minting was not finished
modifier canMint() {
require(!totalSupplyIsFixed, "Total supply has been fixed");
_;
}
/// @dev Set minter authority
/// @param _minter Ethereum address of minter authority
function setMinter(address _minter) public onlyOwner {
require(minter == address(0x0), "Minter has already been set");
require(_minter != address(0x0), "Minter is zero");
minter = _minter;
}
/// @dev Mint tokens, i.e. create tokens out of thin air
/// @param _to Beneficiary who will receive the newly minted tokens
/// @param _amount The amount of minted token units
function mint(address _to, uint _amount) public onlyMinter canMint onlyWhitelisted(_to) {
if (accounts[_to].balance == 0) {
numberOfInvestors++;
}
totalSupply_ = totalSupply_.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
accounts[_to].balance = accounts[_to].balance.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Minted(_to, _amount);
emit Transfer(address(0x0), _to, _amount);
}
/// @dev Finish minting -- this should be irreversible
function finishMinting() public onlyMinter canMint {
totalSupplyIsFixed = true;
emit MintFinished();
}
}
// File: contracts/crowdsale/RateSourceInterface.sol
pragma solidity 0.5.12;
/// @title RateSource
/// @author STOKR
interface RateSource {
/// @dev The current price of an Ether in EUR cents
/// @return Current ether rate
function etherRate() external view returns (uint);
}
// File: contracts/crowdsale/MintingCrowdsale.sol
pragma solidity 0.5.12;
/// @title MintingCrowdsale
/// @author STOKR
contract MintingCrowdsale is Ownable {
using SafeMath for uint;
// Maximum Time of offering period after extension
uint constant MAXOFFERINGPERIOD = 80 days;
// Ether rate oracle contract providing the price of an Ether in EUR cents
RateSource public rateSource;
// The token to be sold
// In the following, the term "token unit" always refers to the smallest
// and non-divisible quantum. Thus, token unit amounts are always integers.
// One token is expected to consist of 10^18 token units.
MintableToken public token;
// Token amounts in token units
// The public and the private sale are both capped (i.e. two distinct token pools)
// The tokenRemaining variables keep track of how many token units are available
// for the respective type of sale
uint public tokenCapOfPublicSale;
uint public tokenCapOfPrivateSale;
uint public tokenRemainingForPublicSale;
uint public tokenRemainingForPrivateSale;
// Prices are in Euro cents (i.e. 1/100 EUR)
uint public tokenPrice;
// The minimum amount of tokens a purchaser has to buy via one transaction
uint public tokenPurchaseMinimum;
// The maximum total amount of tokens a purchaser may buy during start phase
uint public tokenPurchaseLimit;
// Total token purchased by investor (while purchase amount is limited)
mapping(address => uint) public tokenPurchased;
// Public sale period
uint public openingTime;
uint public closingTime;
uint public limitEndTime;
// Ethereum address where invested funds will be transferred to
address payable public companyWallet;
// Amount and receiver of reserved tokens
uint public tokenReservePerMill;
address public reserveAccount;
// Wether this crowdsale was finalized or not
bool public isFinalized = false;
/// @dev Log entry upon token distribution event
/// @param beneficiary Ethereum address of token recipient
/// @param amount Number of token units
/// @param isPublicSale Whether the distribution was via public sale
event TokenDistribution(address indexed beneficiary, uint amount, bool isPublicSale);
/// @dev Log entry upon token purchase event
/// @param buyer Ethereum address of token purchaser
/// @param value Worth in wei of purchased token amount
/// @param amount Number of token units
event TokenPurchase(address indexed buyer, uint value, uint amount);
/// @dev Log entry upon rate change event
/// @param previous Previous closing time of sale
/// @param current Current closing time of sale
event ClosingTimeChange(uint previous, uint current);
/// @dev Log entry upon finalization event
event Finalization();
/// @dev Constructor
/// @param _rateSource Ether rate oracle contract
/// @param _token The token to be sold
/// @param _tokenCapOfPublicSale Maximum number of token units to mint in public sale
/// @param _tokenCapOfPrivateSale Maximum number of token units to mint in private sale
/// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once
/// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase
/// @param _tokenPrice Price of a token in EUR cent
/// @param _openingTime Block (Unix) timestamp of sale opening time
/// @param _closingTime Block (Unix) timestamp of sale closing time
/// @param _limitEndTime Block (Unix) timestamp until token purchases are limited
/// @param _companyWallet Ethereum account who will receive sent ether
/// @param _tokenReservePerMill Per mill amount of sold tokens to mint for reserve account
/// @param _reserveAccount Ethereum address of reserve tokens recipient
constructor(
RateSource _rateSource,
MintableToken _token,
uint _tokenCapOfPublicSale,
uint _tokenCapOfPrivateSale,
uint _tokenPurchaseMinimum,
uint _tokenPurchaseLimit,
uint _tokenReservePerMill,
uint _tokenPrice,
uint _openingTime,
uint _closingTime,
uint _limitEndTime,
address payable _companyWallet,
address _reserveAccount
)
public
{
require(address(_rateSource) != address(0x0), "Rate source is zero");
require(address(_token) != address(0x0), "Token address is zero");
require(_token.minter() == address(0x0), "Token has another minter");
require(_tokenCapOfPublicSale > 0, "Cap of public sale is zero");
require(_tokenCapOfPrivateSale > 0, "Cap of private sale is zero");
require(_tokenPurchaseMinimum <= _tokenCapOfPublicSale
&& _tokenPurchaseMinimum <= _tokenCapOfPrivateSale,
"Purchase minimum exceeds cap");
require(_tokenPrice > 0, "Token price is zero");
require(_openingTime >= now, "Opening lies in the past");
require(_closingTime >= _openingTime, "Closing lies before opening");
require(_companyWallet != address(0x0), "Company wallet is zero");
require(_reserveAccount != address(0x0), "Reserve account is zero");
// Note: There are no time related requirements regarding limitEndTime.
// If it's below openingTime, token purchases will never be limited.
// If it's above closingTime, token purchases will always be limited.
if (_limitEndTime > _openingTime) {
// But, if there's a purchase limitation phase, the limit must be at
// least the purchase minimum or above to make purchases possible.
require(_tokenPurchaseLimit >= _tokenPurchaseMinimum,
"Purchase limit is below minimum");
}
// Utilize safe math to ensure the sum of three token pools does't overflow
_tokenCapOfPublicSale.add(_tokenCapOfPrivateSale).mul(_tokenReservePerMill);
rateSource = _rateSource;
token = _token;
tokenCapOfPublicSale = _tokenCapOfPublicSale;
tokenCapOfPrivateSale = _tokenCapOfPrivateSale;
tokenPurchaseMinimum = _tokenPurchaseMinimum;
tokenPurchaseLimit= _tokenPurchaseLimit;
tokenReservePerMill = _tokenReservePerMill;
tokenPrice = _tokenPrice;
openingTime = _openingTime;
closingTime = _closingTime;
limitEndTime = _limitEndTime;
companyWallet = _companyWallet;
reserveAccount = _reserveAccount;
tokenRemainingForPublicSale = _tokenCapOfPublicSale;
tokenRemainingForPrivateSale = _tokenCapOfPrivateSale;
}
/// @dev Fallback function: buys tokens
function () external payable {
require(msg.data.length == 0, "Fallback call with data");
buyTokens();
}
/// @dev Distribute tokens purchased off-chain via public sale
/// Note: additional requirements are enforced in internal function.
/// @param beneficiaries List of recipients' Ethereum addresses
/// @param amounts List of token units each recipient will receive
function distributeTokensViaPublicSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
tokenRemainingForPublicSale =
distributeTokens(tokenRemainingForPublicSale, beneficiaries, amounts, true);
}
/// @dev Distribute tokens purchased off-chain via private sale
/// Note: additional requirements are enforced in internal function.
/// @param beneficiaries List of recipients' Ethereum addresses
/// @param amounts List of token units each recipient will receive
function distributeTokensViaPrivateSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
tokenRemainingForPrivateSale =
distributeTokens(tokenRemainingForPrivateSale, beneficiaries, amounts, false);
}
/// @dev Check whether the sale has closed
/// @return True iff sale closing time has passed
function hasClosed() public view returns (bool) {
return now >= closingTime;
}
/// @dev Check wether the sale is open
/// @return True iff sale opening time has passed and sale is not closed yet
function isOpen() public view returns (bool) {
return now >= openingTime && !hasClosed();
}
/// @dev Determine the remaining open time of sale
/// @return Time in seconds until sale gets closed, or 0 if sale was closed
function timeRemaining() public view returns (uint) {
if (hasClosed()) {
return 0;
}
return closingTime - now;
}
/// @dev Determine the amount of sold tokens (off-chain and on-chain)
/// @return Token units amount
function tokenSold() public view returns (uint) {
return (tokenCapOfPublicSale - tokenRemainingForPublicSale)
+ (tokenCapOfPrivateSale - tokenRemainingForPrivateSale);
}
/// @dev Purchase tokens
function buyTokens() public payable {
require(isOpen(), "Sale is not open");
uint etherRate = rateSource.etherRate();
require(etherRate > 0, "Ether rate is zero");
// Units: [1e-18*ether] * [cent/ether] / [cent/token] => [1e-18*token]
uint amount = msg.value.mul(etherRate).div(tokenPrice);
require(amount <= tokenRemainingForPublicSale, "Not enough tokens available");
require(amount >= tokenPurchaseMinimum, "Investment is too low");
// Is the total amount an investor can purchase with Ether limited?
if (now < limitEndTime) {
uint purchased = tokenPurchased[msg.sender].add(amount);
require(purchased <= tokenPurchaseLimit, "Purchase limit reached");
tokenPurchased[msg.sender] = purchased;
}
tokenRemainingForPublicSale = tokenRemainingForPublicSale.sub(amount);
token.mint(msg.sender, amount);
forwardFunds();
emit TokenPurchase(msg.sender, msg.value, amount);
}
/// @dev Extend the offering period of the crowd sale.
/// @param _newClosingTime new closingTime of the crowdsale
function changeClosingTime(uint _newClosingTime) public onlyOwner {
require(!hasClosed(), "Sale has already ended");
require(_newClosingTime > now, "ClosingTime not in the future");
require(_newClosingTime > openingTime, "New offering is zero");
require(_newClosingTime - openingTime <= MAXOFFERINGPERIOD, "New offering too long");
emit ClosingTimeChange(closingTime, _newClosingTime);
closingTime = _newClosingTime;
}
/// @dev Finalize, i.e. end token minting phase and enable token transfers
function finalize() public onlyOwner {
require(!isFinalized, "Sale has already been finalized");
require(hasClosed(), "Sale has not closed");
if (tokenReservePerMill > 0) {
token.mint(reserveAccount, tokenSold().mul(tokenReservePerMill).div(1000));
}
token.finishMinting();
isFinalized = true;
emit Finalization();
}
/// @dev Distribute tokens purchased off-chain (in Euro) to investors
/// @param tokenRemaining Token units available for sale
/// @param beneficiaries Ethereum addresses of purchasers
/// @param amounts Token unit amounts to deliver to each investor
/// @return Token units available for sale after distribution
function distributeTokens(
uint tokenRemaining,
address[] memory beneficiaries,
uint[] memory amounts,
bool isPublicSale
)
internal
onlyOwner
returns (uint)
{
require(!isFinalized, "Sale has been finalized");
require(beneficiaries.length == amounts.length, "Lengths are different");
for (uint i = 0; i < beneficiaries.length; ++i) {
address beneficiary = beneficiaries[i];
uint amount = amounts[i];
require(amount <= tokenRemaining, "Not enough tokens available");
tokenRemaining = tokenRemaining.sub(amount);
token.mint(beneficiary, amount);
emit TokenDistribution(beneficiary, amount, isPublicSale);
}
return tokenRemaining;
}
/// @dev Forward invested ether to company wallet
function forwardFunds() internal {
companyWallet.transfer(address(this).balance);
}
}
// File: contracts/token/TokenRecoverable.sol
pragma solidity 0.5.12;
/// @title TokenRecoverable
/// @author STOKR
contract TokenRecoverable is Ownable {
// Address that can do the TokenRecovery
address public tokenRecoverer;
/// @dev Event emitted when the TokenRecoverer changes
/// @param previous Ethereum address of previous token recoverer
/// @param current Ethereum address of new token recoverer
event TokenRecovererChange(address indexed previous, address indexed current);
/// @dev Event emitted in case of a TokenRecovery
/// @param oldAddress Ethereum address of old account
/// @param newAddress Ethereum address of new account
event TokenRecovery(address indexed oldAddress, address indexed newAddress);
/// @dev Restrict operation to token recoverer
modifier onlyTokenRecoverer() {
require(msg.sender == tokenRecoverer, "Restricted to token recoverer");
_;
}
/// @dev Constructor
/// @param _tokenRecoverer Ethereum address of token recoverer
constructor(address _tokenRecoverer) public {
setTokenRecoverer(_tokenRecoverer);
}
/// @dev Set token recoverer
/// @param _newTokenRecoverer Ethereum address of new token recoverer
function setTokenRecoverer(address _newTokenRecoverer) public onlyOwner {
require(_newTokenRecoverer != address(0x0), "New token recoverer is zero");
if (_newTokenRecoverer != tokenRecoverer) {
emit TokenRecovererChange(tokenRecoverer, _newTokenRecoverer);
tokenRecoverer = _newTokenRecoverer;
}
}
/// @dev Recover token
/// @param _oldAddress address
/// @param _newAddress address
function recoverToken(address _oldAddress, address _newAddress) public;
}
// File: contracts/token/StokrToken.sol
pragma solidity 0.5.12;
/// @title StokrToken
/// @author Stokr
contract StokrToken is MintableToken, TokenRecoverable {
string public name;
string public symbol;
uint8 public constant decimals = 18;
mapping(address => mapping(address => uint)) internal allowance_;
/// @dev Log entry on self destruction of the token
event TokenDestroyed();
/// @dev Constructor
/// @param _whitelist Ethereum address of whitelist contract
/// @param _tokenRecoverer Ethereum address of token recoverer
constructor(
string memory _name,
string memory _symbol,
Whitelist _whitelist,
address _profitDepositor,
address _profitDistributor,
address _tokenRecoverer
)
public
Whitelisted(_whitelist)
ProfitSharing(_profitDepositor, _profitDistributor)
TokenRecoverable(_tokenRecoverer)
{
name = _name;
symbol = _symbol;
}
/// @dev Self destruct can only be called by crowdsale contract in case the goal wasn't reached
function destruct() public onlyMinter {
emit TokenDestroyed();
selfdestruct(address(uint160(owner)));
}
/// @dev Recover token
/// @param _oldAddress address of old account
/// @param _newAddress address of new account
function recoverToken(address _oldAddress, address _newAddress)
public
onlyTokenRecoverer
onlyWhitelisted(_newAddress)
{
// Ensure that new address is *not* an existing account.
// Check for account.profitShare is not needed because of following implication:
// (account.lastTotalProfits == 0) ==> (account.profitShare == 0)
require(accounts[_newAddress].balance == 0 && accounts[_newAddress].lastTotalProfits == 0,
"New address exists already");
updateProfitShare(_oldAddress);
accounts[_newAddress] = accounts[_oldAddress];
delete accounts[_oldAddress];
emit TokenRecovery(_oldAddress, _newAddress);
emit Transfer(_oldAddress, _newAddress, accounts[_newAddress].balance);
}
/// @dev Total supply of this token
/// @return Token amount
function totalSupply() public view returns (uint) {
return totalSupply_;
}
/// @dev Token balance
/// @param _investor Ethereum address of token holder
/// @return Token amount
function balanceOf(address _investor) public view returns (uint) {
return accounts[_investor].balance;
}
/// @dev Allowed token amount a third party trustee may transfer
/// @param _investor Ethereum address of token holder
/// @param _spender Ethereum address of third party
/// @return Allowed token amount
function allowance(address _investor, address _spender) public view returns (uint) {
return allowance_[_investor][_spender];
}
/// @dev Approve a third party trustee to transfer tokens
/// Note: additional requirements are enforced within internal function.
/// @param _spender Ethereum address of third party
/// @param _value Maximum token amount that is allowed to get transferred
/// @return Always true
function approve(address _spender, uint _value) public returns (bool) {
return _approve(msg.sender, _spender, _value);
}
/// @dev Increase the amount of tokens a third party trustee may transfer
/// Note: additional requirements are enforces within internal function.
/// @param _spender Ethereum address of third party
/// @param _amount Additional token amount that is allowed to get transferred
/// @return Always true
function increaseAllowance(address _spender, uint _amount) public returns (bool) {
require(allowance_[msg.sender][_spender] + _amount >= _amount, "Allowance overflow");
return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].add(_amount));
}
/// @dev Decrease the amount of tokens a third party trustee may transfer
/// Note: additional requirements are enforces within internal function.
/// @param _spender Ethereum address of third party
/// @param _amount Reduced token amount that is allowed to get transferred
/// @return Always true
function decreaseAllowance(address _spender, uint _amount) public returns (bool) {
require(_amount <= allowance_[msg.sender][_spender], "Amount exceeds allowance");
return _approve(msg.sender, _spender, allowance_[msg.sender][_spender].sub(_amount));
}
/// @dev Check if a token transfer is possible
/// @param _from Ethereum address of token sender
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return True iff a transfer with given pramaters would succeed
function canTransfer(address _from, address _to, uint _value)
public view returns (bool)
{
return totalSupplyIsFixed
&& _from != address(0x0)
&& _to != address(0x0)
&& _value <= accounts[_from].balance
&& whitelist.isWhitelisted(_from)
&& whitelist.isWhitelisted(_to);
}
/// @dev Check if a token transfer by third party is possible
/// @param _spender Ethereum address of third party trustee
/// @param _from Ethereum address of token holder
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return True iff a transfer with given pramaters would succeed
function canTransferFrom(address _spender, address _from, address _to, uint _value)
public view returns (bool)
{
return canTransfer(_from, _to, _value) && _value <= allowance_[_from][_spender];
}
/// @dev Token transfer
/// Note: additional requirements are enforces within internal function.
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function transfer(address _to, uint _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/// @dev Token transfer by a third party
/// Note: additional requirements are enforces within internal function.
/// @param _from Ethereum address of token holder
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
require(_value <= allowance_[_from][msg.sender], "Amount exceeds allowance");
return _approve(_from, msg.sender, allowance_[_from][msg.sender].sub(_value))
&& _transfer(_from, _to, _value);
}
/// @dev Approve a third party trustee to transfer tokens (internal implementation)
/// @param _from Ethereum address of token holder
/// @param _spender Ethereum address of third party
/// @param _value Maximum token amount the trustee is allowed to transfer
/// @return Always true
function _approve(address _from, address _spender, uint _value)
internal
onlyWhitelisted(_from)
onlyWhenTotalSupplyIsFixed
returns (bool)
{
allowance_[_from][_spender] = _value;
emit Approval(_from, _spender, _value);
return true;
}
/// @dev Token transfer (internal implementation)
/// @param _from Ethereum address of token sender
/// @param _to Ethereum address of token recipient
/// @param _value Token amount to transfer
/// @return Always true
function _transfer(address _from, address _to, uint _value)
internal
onlyWhitelisted(_from)
onlyWhitelisted(_to)
onlyWhenTotalSupplyIsFixed
returns (bool)
{
require(_to != address(0x0), "Recipient is zero");
require(_value <= accounts[_from].balance, "Amount exceeds balance");
updateProfitShare(_from);
updateProfitShare(_to);
accounts[_from].balance = accounts[_from].balance.sub(_value);
accounts[_to].balance = accounts[_to].balance.add(_value);
emit Transfer(_from, _to, _value);
return true;
}
}
// File: contracts/crowdsale/StokrCrowdsale.sol
pragma solidity 0.5.12;
/// @title StokrCrowdsale
/// @author STOKR
contract StokrCrowdsale is MintingCrowdsale {
// Soft cap in token units
uint public tokenGoal;
// As long as the goal is not reached funds of purchases are held back
// and investments are assigned to investors here to enable a refunding
// if the goal is missed upon finalization
mapping(address => uint) public investments;
// Log entry upon investor refund event
event InvestorRefund(address indexed investor, uint value);
/// @dev Constructor
/// @param _token The token
/// @param _tokenCapOfPublicSale Available token units for public sale
/// @param _tokenCapOfPrivateSale Available token units for private sale
/// @param _tokenGoal Minimum number of sold token units to be successful
/// @param _tokenPurchaseMinimum Minimum amount of tokens an investor has to buy at once
/// @param _tokenPurchaseLimit Maximum total token amounts individually buyable in limit phase
/// @param _tokenReservePerMill Additional reserve tokens in per mill of sold tokens
/// @param _tokenPrice Price of a token in EUR cent
/// @param _rateSource Ethereum address of ether rate setting authority
/// @param _openingTime Block (Unix) timestamp of sale opening time
/// @param _closingTime Block (Unix) timestamp of sale closing time
/// @param _limitEndTime Block (Unix) timestamp until token purchases are limited
/// @param _companyWallet Ethereum account who will receive sent ether
/// @param _reserveAccount An address
constructor(
RateSource _rateSource,
StokrToken _token,
uint _tokenCapOfPublicSale,
uint _tokenCapOfPrivateSale,
uint _tokenGoal,
uint _tokenPurchaseMinimum,
uint _tokenPurchaseLimit,
uint _tokenReservePerMill,
uint _tokenPrice,
uint _openingTime,
uint _closingTime,
uint _limitEndTime,
address payable _companyWallet,
address _reserveAccount
)
public
MintingCrowdsale(
_rateSource,
_token,
_tokenCapOfPublicSale,
_tokenCapOfPrivateSale,
_tokenPurchaseMinimum,
_tokenPurchaseLimit,
_tokenReservePerMill,
_tokenPrice,
_openingTime,
_closingTime,
_limitEndTime,
_companyWallet,
_reserveAccount
)
{
require(
_tokenGoal <= _tokenCapOfPublicSale + _tokenCapOfPrivateSale,
"Goal is not attainable"
);
tokenGoal = _tokenGoal;
}
/// @dev Wether the goal of sold tokens was reached or not
/// @return True if the sale can be considered successful
function goalReached() public view returns (bool) {
return tokenSold() >= tokenGoal;
}
/// @dev Investors can claim refunds here if crowdsale was unsuccessful
function distributeRefunds(address payable[] calldata _investors) external {
for (uint i = 0; i < _investors.length; ++i) {
refundInvestor(_investors[i]);
}
}
/// @dev Investors can claim refunds here if crowdsale was unsuccessful
function claimRefund() public {
refundInvestor(msg.sender);
}
/// @dev Overwritten. Kill the token if goal was missed
function finalize() public onlyOwner {
super.finalize();
if (!goalReached()) {
StokrToken(address(token)).destruct();
}
}
function distributeTokensViaPublicSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
super.distributeTokensViaPublicSale(beneficiaries, amounts);
// The goal may get reached due to token distribution,
// so forward any accumulated funds to the company wallet.
forwardFunds();
}
function distributeTokensViaPrivateSale(
address[] memory beneficiaries,
uint[] memory amounts
)
public
{
super.distributeTokensViaPrivateSale(beneficiaries, amounts);
// The goal may get reached due to token distribution,
// so forward any accumulated funds to the company wallet.
forwardFunds();
}
/// @dev Overwritten. Funds are held back until goal was reached
function forwardFunds() internal {
if (goalReached()) {
super.forwardFunds();
}
else {
investments[msg.sender] = investments[msg.sender].add(msg.value);
}
}
/// @dev Refund an investor if the sale was not successful
/// @param _investor Ethereum address of investor
function refundInvestor(address payable _investor) internal {
require(isFinalized, "Sale has not been finalized");
require(!goalReached(), "Goal was reached");
uint investment = investments[_investor];
if (investment > 0) {
investments[_investor] = 0;
_investor.transfer(investment);
emit InvestorRefund(_investor, investment);
}
}
}
|
Approve a third party trustee to transfer tokens Note: additional requirements are enforced within internal function. _spender Ethereum address of third party _value Maximum token amount that is allowed to get transferred return Always true
|
function approve(address _spender, uint _value) public returns (bool) {
return _approve(msg.sender, _spender, _value);
}
| 1,787,013 |
./partial_match/1/0x118E662de0C4cdc2f8AD0fb1c6Ef4a85222baCF0/sources/contracts/base/Payments.sol
|
Sends ETH to the destination _recipient The destination address _amount Ether amount
|
function _sendETH(address _recipient, uint256 _amount) internal {
_require(success, ErrorCodes.FAILED_TO_SEND_ETHER);
}
| 3,587,912 |
pragma solidity ^0.4.21;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/ownership/Claimable.sol
/**
* @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 {
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/external/KYCWhitelist.sol
/**
* @title KYCWhitelist
* @dev Crowdsale in which only whitelisted users can contribute.
*/
contract KYCWhitelist is Claimable {
mapping(address => bool) public whitelist;
/**
* @dev Reverts if beneficiary is not whitelisted. Can be used when extending this contract.
*/
modifier isWhitelisted(address _beneficiary) {
require(whitelist[_beneficiary]);
_;
}
/**
* @dev Does a "require" check if _beneficiary address is approved
* @param _beneficiary Token beneficiary
*/
function validateWhitelisted(address _beneficiary) internal view {
require(whitelist[_beneficiary]);
}
/**
* @dev Adds single address to whitelist.
* @param _beneficiary Address to be added to the whitelist
*/
function addToWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = true;
}
/**
* @dev Adds list of addresses to whitelist. Not overloaded due to limitations with truffle testing.
* @param _beneficiaries Addresses to be added to the whitelist
*/
function addManyToWhitelist(address[] _beneficiaries) external onlyOwner {
for (uint256 i = 0; i < _beneficiaries.length; i++) {
whitelist[_beneficiaries[i]] = true;
}
}
/**
* @dev Removes single address from whitelist.
* @param _beneficiary Address to be removed to the whitelist
*/
function removeFromWhitelist(address _beneficiary) external onlyOwner {
whitelist[_beneficiary] = false;
}
}
// File: contracts/external/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Claimable {
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: zeppelin-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) {
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;
}
}
// File: zeppelin-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: zeppelin-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/PrivatePreSale.sol
/**
* @title PrivatePreSale
*
* Private Pre-sale contract for Energis tokens
*
* (c) Philip Louw / Zero Carbon Project 2018. The MIT Licence.
*/
contract PrivatePreSale is Claimable, KYCWhitelist, Pausable {
using SafeMath for uint256;
// Wallet Address for funds
address public constant FUNDS_WALLET = 0xDc17D222Bc3f28ecE7FCef42EDe0037C739cf28f;
// Token Wallet Address
address public constant TOKEN_WALLET = 0x1EF91464240BB6E0FdE7a73E0a6f3843D3E07601;
// Token adderss being sold
address public constant TOKEN_ADDRESS = 0x2169Cce281717d204FA0EcF846a6171e96234D72;
// Token being sold
ERC20 public constant TOKEN = ERC20(TOKEN_ADDRESS);
// Conversion Rate (Eth cost of 1 NRG) (Testing uses ETH price of $10 000)
uint256 public constant TOKENS_PER_ETH = 6740;
// Max NRG tokens to sell
uint256 public constant MAX_TOKENS = 20000000 * (10**18);
// Min investment in Tokens
uint256 public constant MIN_TOKEN_INVEST = 300000 * (10**18);
// Token sale start date
uint256 public START_DATE = 1525176000;
// -----------------------------------------
// State Variables
// -----------------------------------------
// Amount of wei raised
uint256 public weiRaised;
// Amount of tokens issued
uint256 public tokensIssued;
// If the pre-sale has ended
bool public closed;
// -----------------------------------------
// Events
// -----------------------------------------
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
// -----------------------------------------
// Constructor
// -----------------------------------------
function PrivatePreSale() public {
require(TOKENS_PER_ETH > 0);
require(FUNDS_WALLET != address(0));
require(TOKEN_WALLET != address(0));
require(TOKEN_ADDRESS != address(0));
require(MAX_TOKENS > 0);
require(MIN_TOKEN_INVEST >= 0);
}
// -----------------------------------------
// Private PreSale external Interface
// -----------------------------------------
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return tokensIssued >= MAX_TOKENS;
}
/**
* @dev Closes the sale, can only be called once. Once closed can not be opened again.
*/
function closeSale() public onlyOwner {
require(!closed);
closed = true;
}
/**
* @dev Returns the amount of tokens given for the amount in Wei
* @param _weiAmount Value in wei
*/
function getTokenAmount(uint256 _weiAmount) public pure returns (uint256) {
// Amount in wei (10**18 wei == 1 eth) and the token is 18 decimal places
return _weiAmount.mul(TOKENS_PER_ETH);
}
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
// -----------------------------------------
// Private PreSale internal
// -----------------------------------------
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) internal whenNotPaused {
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokenAmount = getTokenAmount(weiAmount);
// Validation Checks
preValidateChecks(_beneficiary, weiAmount, tokenAmount);
// update state
tokensIssued = tokensIssued.add(tokenAmount);
weiRaised = weiRaised.add(weiAmount);
// Send tokens from token wallet
TOKEN.transferFrom(TOKEN_WALLET, _beneficiary, tokenAmount);
// Forward the funds to wallet
FUNDS_WALLET.transfer(msg.value);
// Event trigger
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
}
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
* @param _tokenAmount Amount of token to purchase
*/
function preValidateChecks(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal view {
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(now >= START_DATE);
require(!closed);
// KYC Check
validateWhitelisted(_beneficiary);
// Test Min Investment
require(_tokenAmount >= MIN_TOKEN_INVEST);
// Test hard cap
require(tokensIssued.add(_tokenAmount) <= MAX_TOKENS);
}
}
|
Returns the amount of tokens given for the amount in Wei _weiAmount Value in wei/ Amount in wei (1018 wei == 1 eth) and the token is 18 decimal places
|
function getTokenAmount(uint256 _weiAmount) public pure returns (uint256) {
return _weiAmount.mul(TOKENS_PER_ETH);
}
| 1,837,680 |
//Address: 0x4d4377ef856e89cbf76f8e994ab3065445d82f4f
//Contract name: Airdrop
//Balance: 0 Ether
//Verification Date: 5/18/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @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 Standard ERC20 token
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
}
else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool public paused = false;
event Pause();
event Unpause();
/**
* @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 Capped 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 CappedMintableToken is PausableToken {
uint256 public hard_cap;
// List of agents that are allowed to create new tokens
mapping (address => bool) mintAgents;
event MintingAgentChanged(address addr, bool state);
event Mint(address indexed to, uint256 amount);
/*
* @dev Modifier to check if `msg.sender` is an agent allowed to create new tokens
*/
modifier onlyMintAgent() {
require(mintAgents[msg.sender]);
_;
}
/**
* @dev Owner can allow a crowdsale contract to mint new tokens
*/
function setMintAgent(address addr, bool state) onlyOwner whenNotPaused public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
/**
* @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) onlyMintAgent whenNotPaused public returns (bool) {
require (totalSupply.add(_amount) <= hard_cap);
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Gets if an specified address is allowed to mint tokens
* @param _user The address to query if is allowed to mint tokens
* @return An bool representing if the address passed is allowed to mint tokens
*/
function isMintAgent(address _user) public view returns (bool state) {
return mintAgents[_user];
}
}
/**
* @title Platform Token
* @dev Contract that allows the Genbby platform to work properly and being scalable
*/
contract PlatformToken is CappedMintableToken {
mapping (address => bool) trustedContract;
event TrustedContract(address addr, bool state);
/**
* @dev Modifier that check that `msg.sender` is an trusted contract
*/
modifier onlyTrustedContract() {
require(trustedContract[msg.sender]);
_;
}
/**
* @dev The owner can set a contract as a trusted contract
*/
function setTrustedContract(address addr, bool state) onlyOwner whenNotPaused public {
trustedContract[addr] = state;
TrustedContract(addr, state);
}
/**
* @dev Function that trusted contracts can use to perform any buying that users do in the platform
*/
function buy(address who, uint256 amount) onlyTrustedContract whenNotPaused public {
require (balances[who] >= amount);
balances[who] = balances[who].sub(amount);
totalSupply = totalSupply.sub(amount);
}
/**
* @dev Function to check if a contract is marked as a trusted one
* @param _contract The address of the contract to query of
* @return A bool indicanting if the passed contract is considered as a trusted one
*/
function isATrustedContract(address _contract) public view returns (bool state) {
return trustedContract[_contract];
}
}
/**
* @title UpgradeAgent
* @dev Interface of a contract that transfers tokens to itself
* Inspired by Lunyr
*/
contract UpgradeAgent {
function upgradeBalance(address who, uint256 amount) public;
function upgradeAllowance(address _owner, address _spender, uint256 amount) public;
function upgradePendingExchange(address _owner, uint256 amount) public;
}
/**
* @title UpgradableToken
* @dev Allows users to transfers their tokens to a new contract when the token is paused and upgrading
* It is like a guard for unexpected situations
*/
contract UpgradableToken is PlatformToken {
// The next contract where the tokens will be migrated
UpgradeAgent public upgradeAgent;
uint256 public totalSupplyUpgraded;
bool public upgrading = false;
event UpgradeBalance(address who, uint256 amount);
event UpgradeAllowance(address owner, address spender, uint256 amount);
event UpgradePendingExchange(address owner, uint256 value);
event UpgradeStateChange(bool state);
/**
* @dev Modifier to make a function callable only when the contract is upgrading
*/
modifier whenUpgrading() {
require(upgrading);
_;
}
/**
* @dev Function that allows the `owner` to set the upgrade agent
*/
function setUpgradeAgent(address addr) onlyOwner public {
upgradeAgent = UpgradeAgent(addr);
}
/**
* @dev called by the owner when token is paused, triggers upgrading state
*/
function startUpgrading() onlyOwner whenPaused public {
upgrading = true;
UpgradeStateChange(true);
}
/**
* @dev called by the owner then token is paused and upgrading, returns to a non-upgrading state
*/
function stopUpgrading() onlyOwner whenPaused whenUpgrading public {
upgrading = false;
UpgradeStateChange(false);
}
/**
* @dev Allows anybody to upgrade tokens from these contract to the new one
*/
function upgradeBalanceOf(address who) whenUpgrading public {
uint256 value = balances[who];
require (value != 0);
balances[who] = 0;
totalSupply = totalSupply.sub(value);
totalSupplyUpgraded = totalSupplyUpgraded.add(value);
upgradeAgent.upgradeBalance(who, value);
UpgradeBalance(who, value);
}
/**
* @dev Allows anybody to upgrade allowances from these contract to the new one
*/
function upgradeAllowance(address _owner, address _spender) whenUpgrading public {
uint256 value = allowed[_owner][_spender];
require (value != 0);
allowed[_owner][_spender] = 0;
upgradeAgent.upgradeAllowance(_owner, _spender, value);
UpgradeAllowance(_owner, _spender, value);
}
}
/**
* @title Genbby Token
* @dev Token setting
*/
contract GenbbyToken is UpgradableToken {
string public contactInformation;
string public name = "Genbby Token";
string public symbol = "GG";
uint256 public constant decimals = 18;
uint256 public constant factor = 10 ** decimals;
event UpgradeTokenInformation(string newName, string newSymbol);
function GenbbyToken() public {
hard_cap = (10 ** 9) * factor;
contactInformation = 'https://genbby.com/';
}
function setTokenInformation(string _name, string _symbol) onlyOwner public {
name = _name;
symbol = _symbol;
UpgradeTokenInformation(name, symbol);
}
function setContactInformation(string info) onlyOwner public {
contactInformation = info;
}
/*
* @dev Do not allow direct deposits
*/
function () public payable {
revert();
}
}
/**
* @title Airdrop
* @dev Airdrop smart contract used by https://ico.genbby.com/
*/
contract Airdrop is Pausable {
using SafeMath for uint256;
GenbbyToken public token;
uint256 public tokens_sold;
uint256 public constant decimals = 18;
uint256 public constant factor = 10 ** decimals;
uint256 public constant total_tokens = 500000 * factor; // 1% 5 % hard cap
event Drop(address to, uint256 amount);
/**
* @dev The `owner` can set the token that uses the crowdsale
*/
function setToken(address tokenAddress) onlyOwner public {
token = GenbbyToken(tokenAddress);
}
/**
* @dev Function to give tokens to Airdrop participants
* @param _to The address that will receive the tokens
* @param _amount The amount of tokens to give
* @return A boolean that indicates if the operation was successful
*/
function drop(address _to, uint256 _amount) onlyOwner whenNotPaused public returns (bool) {
require (tokens_sold.add(_amount) <= total_tokens);
token.mint(_to, _amount);
tokens_sold = tokens_sold.add(_amount);
Drop(_to, _amount);
return true;
}
/*
* @dev Do not allow direct deposits
*/
function () public payable {
revert();
}
}
|
Function to give tokens to Airdrop participants _to The address that will receive the tokens _amount The amount of tokens to give return A boolean that indicates if the operation was successful/
|
function drop(address _to, uint256 _amount) onlyOwner whenNotPaused public returns (bool) {
require (tokens_sold.add(_amount) <= total_tokens);
token.mint(_to, _amount);
tokens_sold = tokens_sold.add(_amount);
Drop(_to, _amount);
return true;
}
| 5,502,079 |
./partial_match/1/0x1ECFDCcf97EdD64Fb73890Ca4541f306456A21eC/sources/Metarelics.sol
|
Validates a Merkle proof based on a provided merkle root and leaf node./
|
function _verify(
bytes32[] memory proof,
bytes32 merkleRoot,
bytes32 leafNode
) internal pure returns (bool) {
return MerkleProof.verify(proof, merkleRoot, leafNode);
}
| 3,544,579 |
./full_match/80001/0x72B898947144073d60cC3AE2a5972b7297ed88e4/sources/project_/contracts/DistrictPower.sol
|
determine referrer 确定推荐人 if referrer is already set or msg.sender is the root user whose referrer is address(0)
|
) public payable notContract nonReentrant {
require(msg.value >= MIN_INVEST, "Too small");
require(msg.value <= MAX_INVEST, "Too large");
require(!gamePaused, "Paused");
UserGlobalInfo storage userGlobalInfo = userGlobalInfos[msg.sender];
address _referrer = userGlobalInfo.referrer;
function openPosition(
if (_referrer == address(0) && children[msg.sender].length == 0) {
require((referrer != address(0) && referrer != msg.sender) || referrer == platformAddress, "Invalid referrer");
require(
userGlobalInfos[referrer].referrer != address(0) || children[referrer].length > 0,
"Invalid referrer 2"
);
if(userGlobalInfos[referrer].supernode){
userGlobalInfo.supernodeAddress = referrer;
userGlobalInfo.supernodeAddress = userGlobalInfos[referrer].supernodeAddress;
}
userGlobalInfo.referrer = referrer;
children[referrer].push(msg.sender);
emit NewReferrer(msg.sender, referrer);
}
uint256 platformAmount = msg.value;
uint256 useTokenAmount = msg.value / 100;
function openPosition(
if (_referrer == address(0) && children[msg.sender].length == 0) {
require((referrer != address(0) && referrer != msg.sender) || referrer == platformAddress, "Invalid referrer");
require(
userGlobalInfos[referrer].referrer != address(0) || children[referrer].length > 0,
"Invalid referrer 2"
);
if(userGlobalInfos[referrer].supernode){
userGlobalInfo.supernodeAddress = referrer;
userGlobalInfo.supernodeAddress = userGlobalInfos[referrer].supernodeAddress;
}
userGlobalInfo.referrer = referrer;
children[referrer].push(msg.sender);
emit NewReferrer(msg.sender, referrer);
}
uint256 platformAmount = msg.value;
uint256 useTokenAmount = msg.value / 100;
}else if(userGlobalInfos[referrer].supernodeAddress != address(0)){
if(totalFlowAmount >= startUseTokenNum){
require(IERC20(tokenAddress).balanceOf(msg.sender) >= useTokenAmount, "Insufficient USDT amount");
require(IERC20(tokenAddress).allowance(msg.sender, address(this)) >= useTokenAmount, "Insufficient USDT allowance");
IERC20(tokenAddress).transferFrom(msg.sender, address(0), useTokenAmount);
}
bool success;
{
uint256 recommendReward = msg.value * RECOMMENDREWARD_RATIO / PRICE_PRECISION;
platformAmount -= recommendReward;
require(success, "Transfer failed.");
}
(success, ) = _referrer.call{value: recommendReward}("");
{
uint256 buybackAmount = msg.value * BUYBACK_RATIO / PRICE_PRECISION;
platformAmount -= buybackAmount;
if(lpMaticAmount < lpMaticLimit){
addLiquitidyWithId(buybackAmount * 100, buybackAmount);
lpMaticAmount += buybackAmount;
buyBurn(buybackAmount);
}
}
{
uint256 buybackAmount = msg.value * BUYBACK_RATIO / PRICE_PRECISION;
platformAmount -= buybackAmount;
if(lpMaticAmount < lpMaticLimit){
addLiquitidyWithId(buybackAmount * 100, buybackAmount);
lpMaticAmount += buybackAmount;
buyBurn(buybackAmount);
}
}
}else{
{
if(userGlobalInfo.supernodeAddress != address(0)){
uint256 supernodeAmount = msg.value * SUPERNODE_RATIO / PRICE_PRECISION;
platformAmount -= supernodeAmount;
require(success, "Transfer failed.");
}
}
uint256 MagicBoxAmount1 = msg.value * 35 / 100;
uint256 MagicBoxAmount2 = msg.value * 10 / 100;
uint256 MagicBoxAmount3 = msg.value * 15 / 100;
uint256 MagicBoxAmount4 = msg.value * 40 / 100;
uint256 distributionAmount = 0;
distributionAmount += setPosition(MagicBoxAmount1,0);
distributionAmount += setPosition(MagicBoxAmount2,1);
distributionAmount += setPosition(MagicBoxAmount3,2);
distributionAmount += setPosition(MagicBoxAmount4,3);
platformAmount -= distributionAmount;
{
if(userGlobalInfo.supernodeAddress != address(0)){
uint256 supernodeAmount = msg.value * SUPERNODE_RATIO / PRICE_PRECISION;
platformAmount -= supernodeAmount;
require(success, "Transfer failed.");
}
}
uint256 MagicBoxAmount1 = msg.value * 35 / 100;
uint256 MagicBoxAmount2 = msg.value * 10 / 100;
uint256 MagicBoxAmount3 = msg.value * 15 / 100;
uint256 MagicBoxAmount4 = msg.value * 40 / 100;
uint256 distributionAmount = 0;
distributionAmount += setPosition(MagicBoxAmount1,0);
distributionAmount += setPosition(MagicBoxAmount2,1);
distributionAmount += setPosition(MagicBoxAmount3,2);
distributionAmount += setPosition(MagicBoxAmount4,3);
platformAmount -= distributionAmount;
(success, ) = userGlobalInfo.supernodeAddress.call{value: supernodeAmount}("");
if(platformAmount > 0){
(success, ) = platformAddress.call{
value: platformAmount
}("");
require(success, "Transfer failed.");
}
totalFlowAmount += msg.value;
if(platformAmount > 0){
(success, ) = platformAddress.call{
value: platformAmount
}("");
require(success, "Transfer failed.");
}
totalFlowAmount += msg.value;
if(totalFlowAmount >= totalFlowAmountThreshold[0] && !totalAmountMagicBox[0]){
(uint8[] memory typeDays2,uint16[] memory stock2) = generateTypeDaysAndStock(10, 30);
setStock(2, typeDays2, stock2);
(uint8[] memory typeDays3,uint16[] memory stock3) = generateTypeDaysAndStock(30, 40);
setStock(3, typeDays3, stock3);
totalAmountMagicBox[0] = true;
}
if(totalFlowAmount >= totalFlowAmountThreshold[1] && !totalAmountMagicBox[1]){
(uint8[] memory typeDays2,uint16[] memory stock2) = generateTypeDaysAndStock(10, 40);
setStock(2, typeDays2, stock2);
(uint8[] memory typeDays3,uint16[] memory stock3) = generateTypeDaysAndStock(40, 50);
setStock(3, typeDays3, stock3);
totalAmountMagicBox[1] = true;
}
if(totalFlowAmount >= totalFlowAmountThreshold[2] && !totalAmountMagicBox[2]){
(uint8[] memory typeDays2,uint16[] memory stock2) = generateTypeDaysAndStock(10, 50);
setStock(2, typeDays2, stock2);
(uint8[] memory typeDays3,uint16[] memory stock3) = generateTypeDaysAndStock(40, 60);
setStock(3, typeDays3, stock3);
totalAmountMagicBox[2] = true;
}
}
| 872,132 |
pragma solidity ^0.5.11;
// Voken Shareholders Contract for Voken2.0
//
// More info:
// https://vision.network
// https://voken.io
//
// Contact us:
// [email protected]
// [email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath256 {
/**
* @dev Returns the addition of two unsigned integers, reverting on 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).
*/
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).
*/
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.
*/
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. Reverts on
* division by zero. The result is rounded towards 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.
*/
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);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @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 Interface of the ERC20 standard
*/
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
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);
}
/**
* @dev Interface of an allocation contract
*/
interface IAllocation {
function reservedOf(address account) external view returns (uint256);
}
/**
* @dev Interface of Voken2.0
*/
interface IVoken2 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function mintWithAllocation(address account, uint256 amount, address allocationContract) external returns (bool);
}
/**
* @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.
*/
contract Ownable {
address internal _owner;
address internal _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipAccepted(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the addresses of the current and new owner.
*/
function owner() public view returns (address currentOwner, address newOwner) {
currentOwner = _owner;
newOwner = _newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner(address account) public view returns (bool) {
return account == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* IMPORTANT: Need to run {acceptOwnership} by the new owner.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
/**
* @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 Accept ownership of the contract.
*
* Can only be called by the new owner.
*/
function acceptOwnership() public {
require(msg.sender == _newOwner, "Ownable: caller is not the new owner address");
require(msg.sender != address(0), "Ownable: caller is the zero address");
emit OwnershipAccepted(_owner, msg.sender);
_owner = msg.sender;
_newOwner = address(0);
}
/**
* @dev Rescue compatible ERC20 Token
*
* Can only be called by the current owner.
*/
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(recipient != address(0), "Rescue: recipient is the zero address");
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount, "Rescue: amount exceeds balance");
_token.transfer(recipient, amount);
}
/**
* @dev Withdraw Ether
*
* Can only be called by the current owner.
*/
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Withdraw: recipient is the zero address");
uint256 balance = address(this).balance;
require(balance >= amount, "Withdraw: amount exceeds balance");
recipient.transfer(amount);
}
}
/**
* @title Voken Shareholders
*/
contract VokenShareholders is Ownable, IAllocation {
using SafeMath256 for uint256;
using Roles for Roles.Role;
IVoken2 private _VOKEN = IVoken2(0xFfFAb974088Bd5bF3d7E6F522e93Dd7861264cDB);
Roles.Role private _proxies;
uint256 private _ALLOCATION_TIMESTAMP = 1598918399; // Sun, 30 Aug 2020 23:59:59 +0000
uint256 private _ALLOCATION_INTERVAL = 1 days;
uint256 private _ALLOCATION_STEPS = 60;
uint256 private _page;
uint256 private _weis;
uint256 private _vokens;
address[] private _shareholders;
mapping (address => bool) private _isShareholder;
mapping (address => uint256) private _withdrawPos;
mapping (uint256 => address[]) private _pageShareholders;
mapping (uint256 => mapping (address => bool)) private _isPageShareholder;
mapping (uint256 => uint256) private _pageEndingBlock;
mapping (uint256 => uint256) private _pageEthers;
mapping (uint256 => uint256) private _pageVokens;
mapping (uint256 => uint256) private _pageVokenSum;
mapping (uint256 => mapping (address => uint256)) private _pageVokenHoldings;
mapping (uint256 => mapping (address => uint256)) private _pageEtherDividends;
mapping (address => uint256) private _allocations;
event ProxyAdded(address indexed account);
event ProxyRemoved(address indexed account);
event Dividend(address indexed account, uint256 amount, uint256 page);
/**
* @dev Throws if called by account which is not a proxy.
*/
modifier onlyProxy() {
require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role");
_;
}
/**
* @dev Returns true if the `account` has the Proxy role.
*/
function isProxy(address account) public view returns (bool) {
return _proxies.has(account);
}
/**
* @dev Give an `account` access to the Proxy role.
*
* Can only be called by the current owner.
*/
function addProxy(address account) public onlyOwner {
_proxies.add(account);
emit ProxyAdded(account);
}
/**
* @dev Remove an `account` access from the Proxy role.
*
* Can only be called by the current owner.
*/
function removeProxy(address account) public onlyOwner {
_proxies.remove(account);
emit ProxyRemoved(account);
}
/**
* @dev Returns the VOKEN main contract address.
*/
function VOKEN() public view returns (IVoken2) {
return _VOKEN;
}
/**
* @dev Returns the max page number.
*/
function page() public view returns (uint256) {
return _page;
}
/**
* @dev Returns the amount of deposited Ether.
*/
function weis() public view returns (uint256) {
return _weis;
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders.
*/
function vokens() public view returns (uint256) {
return _vokens;
}
/**
* @dev Returns the shareholders list on `pageNumber`.
*/
function shareholders(uint256 pageNumber) public view returns (address[] memory) {
if (pageNumber > 0) {
return _pageShareholders[pageNumber];
}
return _shareholders;
}
/**
* @dev Returns the shareholders counter on `pageNumber`.
*/
function shareholdersCounter(uint256 pageNumber) public view returns (uint256) {
if (pageNumber > 0) {
return _pageShareholders[pageNumber].length;
}
return _shareholders.length;
}
/**
* @dev Returns the amount of deposited Ether at `pageNumber`.
*/
function pageEther(uint256 pageNumber) public view returns (uint256) {
return _pageEthers[pageNumber];
}
/**
* @dev Returns the amount of deposited Ether till `pageNumber`.
*/
function pageEtherSum(uint256 pageNumber) public view returns (uint256) {
uint256 __page = _pageNumber(pageNumber);
uint256 __amount;
for (uint256 i = 1; i <= __page; i++) {
__amount = __amount.add(_pageEthers[i]);
}
return __amount;
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders at `pageNumber`.
*/
function pageVoken(uint256 pageNumber) public view returns (uint256) {
return _pageVokens[pageNumber];
}
/**
* @dev Returns the amount of VOKEN holding by all shareholders till `pageNumber`.
*/
function pageVokenSum(uint256 pageNumber) public view returns (uint256) {
return _pageVokenSum[_pageNumber(pageNumber)];
}
/**
* Returns the ending block number of `pageNumber`.
*/
function pageEndingBlock(uint256 pageNumber) public view returns (uint256) {
return _pageEndingBlock[pageNumber];
}
/**
* Returns the page number greater than 0 by `pageNmber`.
*/
function _pageNumber(uint256 pageNumber) internal view returns (uint256) {
if (pageNumber > 0) {
return pageNumber;
}
else {
return _page;
}
}
/**
* @dev Returns the amount of VOKEN holding by `account` and `pageNumber`.
*/
function vokenHolding(address account, uint256 pageNumber) public view returns (uint256) {
uint256 __page;
uint256 __amount;
if (pageNumber > 0) {
__page = pageNumber;
}
else {
__page = _page;
}
for (uint256 i = 1; i <= __page; i++) {
__amount = __amount.add(_pageVokenHoldings[i][account]);
}
return __amount;
}
/**
* @dev Returns the ether dividend of `account` on `pageNumber`.
*/
function etherDividend(address account, uint256 pageNumber) public view returns (uint256 amount,
uint256 dividend,
uint256 remain) {
if (pageNumber > 0) {
amount = pageEther(pageNumber).mul(vokenHolding(account, pageNumber)).div(pageVokenSum(pageNumber));
dividend = _pageEtherDividends[pageNumber][account];
}
else {
for (uint256 i = 1; i <= _page; i++) {
uint256 __pageEtherDividend = pageEther(i).mul(vokenHolding(account, i)).div(pageVokenSum(i));
amount = amount.add(__pageEtherDividend);
dividend = dividend.add(_pageEtherDividends[i][account]);
}
}
remain = amount.sub(dividend);
}
/**
* @dev Returns the allocation of `account`.
*/
function allocation(address account) public view returns (uint256) {
return _allocations[account];
}
/**
* @dev Returns the reserved amount of VOKENs by `account`.
*/
function reservedOf(address account) public view returns (uint256 reserved) {
reserved = _allocations[account];
if (now > _ALLOCATION_TIMESTAMP && reserved > 0) {
uint256 __passed = now.sub(_ALLOCATION_TIMESTAMP).div(_ALLOCATION_INTERVAL).add(1);
if (__passed > _ALLOCATION_STEPS) {
reserved = 0;
}
else {
reserved = reserved.sub(reserved.mul(__passed).div(_ALLOCATION_STEPS));
}
}
}
/**
* @dev Constructor
*/
constructor () public {
_page = 1;
addProxy(msg.sender);
}
/**
* @dev {Deposit} or {Withdraw}
*/
function () external payable {
// deposit
if (msg.value > 0) {
_weis = _weis.add(msg.value);
_pageEthers[_page] = _pageEthers[_page].add(msg.value);
}
// withdraw
else if (_isShareholder[msg.sender]) {
uint256 __vokenHolding;
for (uint256 i = 1; i <= _page.sub(1); i++) {
__vokenHolding = __vokenHolding.add(_pageVokenHoldings[i][msg.sender]);
if (_withdrawPos[msg.sender] < i) {
uint256 __etherAmount = _pageEthers[i].mul(__vokenHolding).div(_pageVokenSum[i]);
_withdrawPos[msg.sender] = i;
_pageEtherDividends[i][msg.sender] = __etherAmount;
msg.sender.transfer(__etherAmount);
emit Dividend(msg.sender, __etherAmount, i);
}
}
}
assert(true);
}
/**
* @dev End the current page.
*/
function endPage() public onlyProxy {
require(_pageEthers[_page] > 0, "Ethers on current page is zero.");
_pageEndingBlock[_page] = block.number;
_page = _page.add(1);
_pageVokenSum[_page] = _vokens;
assert(true);
}
/**
* @dev Push shareholders.
*
* Can only be called by a proxy.
*/
function pushShareholders(address[] memory accounts, uint256[] memory values) public onlyProxy {
require(accounts.length == values.length, "Shareholders: batch length is not match");
for (uint256 i = 0; i < accounts.length; i++) {
address __account = accounts[i];
uint256 __value = values[i];
if (!_isShareholder[__account]) {
_shareholders.push(__account);
_isShareholder[__account] = true;
}
if (!_isPageShareholder[_page][__account]) {
_pageShareholders[_page].push(__account);
_isPageShareholder[_page][__account] = true;
}
_vokens = _vokens.add(__value);
_pageVokens[_page] = _pageVokens[_page].add(__value);
_pageVokenSum[_page] = _vokens;
_pageVokenHoldings[_page][__account] = _pageVokenHoldings[_page][__account].add(__value);
_allocations[__account] = _allocations[__account].add(__value);
assert(_VOKEN.mintWithAllocation(__account, __value, address(this)));
}
assert(true);
}
}
|
Returns the amount of deposited Ether till `pageNumber`./
|
function pageEtherSum(uint256 pageNumber) public view returns (uint256) {
uint256 __page = _pageNumber(pageNumber);
uint256 __amount;
for (uint256 i = 1; i <= __page; i++) {
__amount = __amount.add(_pageEthers[i]);
}
return __amount;
}
| 12,667,736 |
pragma solidity 0.5.17;
import "./XIERC20.sol";
import "./XSafeERC20.sol";
import "./XSafeMath.sol";
import "./ReentrancyGuard.sol";
import "./XERC20.sol";
import "./ERC20Detailed.sol";
interface IXStream {
function createStream(
address token,
address recipient,
uint256 depositAmount,
uint256 streamType,
uint256 startBlock
)
external
returns (uint256 streamId);
function isStream(uint256 streamId) external view returns (bool);
function getStream(uint256 streamId)
external
view
returns (
address sender,
address recipient,
uint256 depositAmount,
uint256 startBlock,
uint256 kBlock,
uint256 remaining,
uint256 withdrawable,
uint256 unlockRatio,
uint256 lastRewardBlock
);
function fundStream(uint256 streamId, uint256 amount)
external
returns (bool);
function withdrawFromStream(uint256 streamId, uint256 amount)
external
returns (bool);
function balanceOf(uint256 streamId)
external
view
returns (uint256 withdrawable, uint256 remaining);
function cancelStream(uint256 streamId) external returns (bool);
function hasStream(address who)
external
view
returns (bool hasVotingStream, bool hasNormalStream);
function getStreamId(address who, uint256 streamType)
external
view
returns (uint256);
function fundsToStream(address token ,uint256 streamId, uint256 amount)
external
returns (bool );
function addMinter(address _minter) external;
}
interface IXDEX {
function mint(address account, uint256 amount) external;
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool) ;
function addMinter(address _minter) external;
}
contract XFarmMasterFactory{
address[] public farmMasterys;
mapping(address => address[]) userInfo;
address public operatorAddress;
constructor() public{
operatorAddress = msg.sender;
}
modifier onlyDev {
require(msg.sender == operatorAddress, ":: Not operator");
_;
}
address xstream = 0x791fa9F3d914a3CD2f1b975c04e9d8A18d2beD17;
function deploy( address xdex,uint256 _startBlock,address _core, uint256[] memory _bonusEndBlocks,uint256[] memory _tokensPerBlock) public {
address farmMastery = address(new XFarmMastery(xdex,xstream,_startBlock,_core,_bonusEndBlocks,_tokensPerBlock));
farmMasterys.push(farmMastery);
address[] storage uInfos = userInfo[msg.sender];
uInfos.push(farmMastery);
userInfo[msg.sender] = uInfos;
}
}
// FarmMaster is the master of xDefi Farms.
contract XFarmMastery is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
uint256 constant ONE = 10**18;
uint256 constant onePercent = 10**16;
uint256 constant StreamTypeVoting = 0;
uint256 constant StreamTypeNormal = 1;
//min and max lpToken count in one pool
uint256 public constant LpTokenMinCount = 1;
uint256 public constant LpTokenMaxCount = 8;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
}
struct LpTokenInfo {
IERC20 lpToken; // Address of LP token contract.
// lpTokenType, Type of LP token
// Type0: XPT;
// Type1: UNI-LP;
// Type2: BPT;
// Type3: XLP;
// Type4: yCrv;
uint256 lpTokenType;
uint256 lpFactor;
uint256 lpAccPerShare; // Accumulated XDEX per share, times 1e12. See below.
mapping(address => UserInfo) userInfo; // Info of each user that stakes LP tokens.
}
// Info of each pool.
struct PoolInfo {
LpTokenInfo lpTokenInfo;
uint256 poolFactor; // How many allocation factor assigned to this pool. XDEX to distribute per block.
uint256 lastRewardBlock; // Last block number that XDEX distribution occurs.
}
/*
* In [0, 40000) blocks, 240 XDEX per block, 9600000 XDEX distributed;
* In [40000, 120000) blocks, 120 XDEX per block, 9600000 XDEX distributed;
* In [120000, 280000) blocks, 60 XDEX per block, 9600000 XDEX distributed;
* In [280001, 600000) blocks, 30 XDEX per block, 9600000 XDEX distributed;
* After 600000 blocks, 8 XDEX distributed per block.
*/
uint256[] public bonusEndBlocks ;
// 240, 120, 60, 30, 8 XDEX per block
uint256[] public tokensPerBlock ;
// First deposit incentive (once for each new user), 10 XDEX
uint256 public constant bonusFirstDeposit = 10 * ONE;
address public core;
address public SAFU;
// whitelist of claimable airdrop tokens
mapping(address => bool) public claimableTokens;
// The XDEX TOKEN
// IXDEXToken public xdex;
address public xdexToken;
address public stream ;//= 0x791fa9F3d914a3CD2f1b975c04e9d8A18d2beD17;
// The Halflife Protocol
// IXStream public stream;
// The main voting pool id
uint256 public votingPoolId;
// The block number when Token farming starts.
uint256 public startBlock;
// Info of each pool.
PoolInfo[] poolInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalXFactor = 0;
event AddPool(
uint256 indexed pid,
address indexed lpToken,
uint256 indexed lpType,
uint256 lpFactor
);
event AddLP(
uint256 indexed pid,
address indexed lpToken,
uint256 indexed lpType,
uint256 lpFactor
);
event UpdateFactor(
uint256 indexed pid,
address indexed lpToken,
uint256 lpFactor
);
event Deposit(
address indexed user,
uint256 indexed pid,
uint256 amount
);
event Withdraw(
address indexed user,
uint256 indexed pid,
address indexed lpToken,
uint256 amount
);
event EmergencyWithdraw(
address indexed user,
uint256 indexed pid,
address indexed lpToken,
uint256 amount
);
event SetSAFU(address indexed SAFU);
event Claim(
address indexed SAFU,
address indexed token,
uint256 indexed amount
);
event CoreTransferred(address indexed _core, address indexed _coreNew);
/**
* @dev Throws if the msg.sender unauthorized.
*/
modifier onlyCore() {
require(msg.sender == core, "Not authorized, only core");
_;
}
/**
* @dev Throws if the pid does not point to a valid pool.
*/
modifier poolExists(uint256 _pid) {
require(_pid < poolInfo.length, "pool does not exist");
_;
}
constructor(
address _xdex,
address _stream,
uint256 _startBlock,
address _core,
uint256[] memory _bonusEndBlocks,
uint256[] memory _tokensPerBlock
) public {
xdexToken = _xdex;
// xdex = IXDEX(_xdex);
stream = _stream;
startBlock = _startBlock;
core = _core;
bonusEndBlocks = _bonusEndBlocks;
tokensPerBlock = _tokensPerBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Set the voting pool id. Can only be called by the core.
function setVotingPool(uint256 _pid) public onlyCore {
votingPoolId = _pid;
}
// Add a new lp to the pool. Can only be called by the core.
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function addPool(
IERC20 _lpToken,
uint256 _lpTokenType,
uint256 _lpFactor,
bool _withUpdate
) public onlyCore {
require(_lpFactor > 0, "Lp Token Factor is zero");
if (_withUpdate) {
massUpdatePools();
}
uint256 _lastRewardBlock = block.number > startBlock
? block.number
: startBlock;
totalXFactor = totalXFactor.add(_lpFactor);
uint256 poolinfos_id = poolInfo.length++;
poolInfo[poolinfos_id].poolFactor = _lpFactor;
poolInfo[poolinfos_id].lastRewardBlock = _lastRewardBlock;
poolInfo[poolinfos_id].lpTokenInfo= LpTokenInfo({
lpToken: _lpToken,
lpTokenType: _lpTokenType,
lpFactor: _lpFactor,
lpAccPerShare: 0
});
emit AddPool(poolinfos_id, address(_lpToken), _lpTokenType, _lpFactor);
}
function getLpTokenInfosByPoolId(uint256 _pid)
public
view
poolExists(_pid)
returns (address lpToken,uint256 lpTokenType,uint256 lpFactor,uint256 lpAccPerShare)
{
PoolInfo memory pool = poolInfo[_pid];
lpToken = address(pool.lpTokenInfo.lpToken);
lpTokenType = pool.lpTokenInfo.lpTokenType;
lpFactor = pool.lpTokenInfo.lpFactor;
lpAccPerShare = pool.lpTokenInfo.lpAccPerShare;
}
// View function to see user lpToken amount in pool on frontend.
function getUserLpAmounts(uint256 _pid, address _user)
public
view
poolExists(_pid)
returns (address lpToken, uint256 amount)
{
PoolInfo memory pool = poolInfo[_pid];
lpToken = address(pool.lpTokenInfo.lpToken);
UserInfo memory user = poolInfo[_pid].lpTokenInfo
.userInfo[_user];
amount = user.amount;
}
// Update the given lpToken's lpFactor in the given pool. Can only be called by the owner.
// `_lpFactor` is 0, means the LpToken is soft deleted from pool.
function setLpFactor(
uint256 _pid,
IERC20 _lpToken,
uint256 _lpFactor,
bool _withUpdate
) public onlyCore poolExists(_pid) {
if (_withUpdate) {
massUpdatePools();
}
PoolInfo storage pool = poolInfo[_pid];
//update poolFactor and totalXFactor
uint256 poolFactorNew = pool
.poolFactor
.sub(pool.lpTokenInfo.lpFactor)
.add(_lpFactor);
pool.lpTokenInfo.lpFactor = _lpFactor;
totalXFactor = totalXFactor.sub(poolInfo[_pid].poolFactor).add(
poolFactorNew
);
poolInfo[_pid].poolFactor = poolFactorNew;
emit UpdateFactor(_pid, address(_lpToken), _lpFactor);
}
// 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) {
if (poolInfo[pid].poolFactor > 0) {
updatePool(pid);
}
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public poolExists(_pid) {
if (block.number <= poolInfo[_pid].lastRewardBlock) {
return;
}
if (poolInfo[_pid].poolFactor == 0 || totalXFactor == 0) {
return;
}
PoolInfo storage pool = poolInfo[_pid];
(uint256 poolReward, , ) = getXCountToReward(
pool.lastRewardBlock,
block.number
);
poolReward = poolReward.mul(pool.poolFactor).div(totalXFactor);
LpTokenInfo memory lpInfo = pool.lpTokenInfo;
uint256 totalLpSupply = lpInfo.lpToken.balanceOf(address(this));
if (totalLpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 lpReward = poolReward.mul(lpInfo.lpFactor).div(
pool.poolFactor
);
lpInfo.lpAccPerShare = lpInfo.lpAccPerShare.add(
lpReward.mul(1e12).div(totalLpSupply)
);
IXDEX(xdexToken).mint(address(this), poolReward);
pool.lastRewardBlock = block.number;
}
// View function to see pending XDEX on frontend.
function pendingXDEX(uint256 _pid, address _user)
external
view
poolExists(_pid)
returns (uint256)
{
PoolInfo memory pool = poolInfo[_pid];
uint256 totalPending = 0;
if (totalXFactor == 0 || pool.poolFactor == 0) {
UserInfo memory user = poolInfo[_pid].lpTokenInfo
.userInfo[_user];
totalPending = totalPending.add(
user
.amount
.mul(pool.lpTokenInfo.lpAccPerShare)
.div(1e12)
.sub(user.rewardDebt)
);
return totalPending;
}
(uint256 xdexReward, , ) = getXCountToReward(
pool.lastRewardBlock,
block.number
);
uint256 poolReward = xdexReward.mul(pool.poolFactor).div(totalXFactor);
LpTokenInfo memory lpInfo = pool.lpTokenInfo;
uint256 lpSupply = lpInfo.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock) {
if (lpSupply == 0) {
return 0;
}
uint256 lpReward = poolReward.mul(lpInfo.lpFactor).div(
pool.poolFactor
);
lpInfo.lpAccPerShare = lpInfo.lpAccPerShare.add(
lpReward.mul(1e12).div(lpSupply)
);
}
UserInfo memory user = poolInfo[_pid].lpTokenInfo
.userInfo[_user];
totalPending = totalPending.add(
user.amount.mul(lpInfo.lpAccPerShare).div(1e12).sub(
user.rewardDebt
)
);
return totalPending;
}
// Deposit LP tokens to FarmMaster for XDEX allocation.
function deposit(
uint256 _pid,
uint256 _amount
) public poolExists(_pid) {
require(msg.sender == tx.origin, "do not deposit from contract");
PoolInfo storage pool = poolInfo[_pid];
updatePool(_pid);
UserInfo storage user = poolInfo[_pid].lpTokenInfo.userInfo[msg
.sender];
if (user.amount > 0) {
uint256 pending = user
.amount
.mul(pool.lpTokenInfo.lpAccPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
//create the stream or add funds to stream
(bool hasVotingStream, bool hasNormalStream) = IXStream(stream).hasStream(
msg.sender
);
if (_pid == votingPoolId) {
if (hasVotingStream) {
//add funds
uint256 streamId = IXStream(stream).getStreamId(
msg.sender,
StreamTypeVoting
);
require(streamId > 0, "not valid stream id");
IXDEX(xdexToken).approve(stream, pending);
IXStream(stream).fundsToStream(xdexToken,streamId, pending);
}
} else {
if (hasNormalStream) {
//add funds
uint256 streamId = IXStream(stream).getStreamId(
msg.sender,
StreamTypeNormal
);
require(streamId > 0, "not valid stream id");
IXDEX(xdexToken).approve(stream, pending);
IXStream(stream).fundsToStream(xdexToken,streamId, pending);
}
}
}
} else {
uint256 streamStart = block.number + 1;
if (block.number < startBlock) {
streamStart = startBlock;
}
//if it is the first deposit
(bool hasVotingStream, bool hasNormalStream) = IXStream(stream).hasStream(
msg.sender
);
//create the stream for First Deposit Bonus
if (_pid == votingPoolId) {
if (hasVotingStream == false) {
IXDEX(xdexToken).mint(address(this), bonusFirstDeposit);
IXDEX(xdexToken).approve(stream, bonusFirstDeposit);
IXStream(stream).createStream(
xdexToken,
msg.sender,
bonusFirstDeposit,
StreamTypeVoting,
streamStart
);
}
} else {
if (hasNormalStream == false) {
IXDEX(xdexToken).mint(address(this), bonusFirstDeposit);
IXDEX(xdexToken).approve(stream, bonusFirstDeposit);
IXStream(stream).createStream(
xdexToken,
msg.sender,
bonusFirstDeposit,
StreamTypeNormal,
streamStart
);
}
}
}
if (_amount > 0) {
pool.lpTokenInfo.lpToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
user.amount = user.amount.add(_amount);
}
user.rewardDebt = user
.amount
.mul(pool.lpTokenInfo.lpAccPerShare)
.div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(
uint256 _pid,
IERC20 _lpToken,
uint256 _amount
) public nonReentrant poolExists(_pid) {
require(msg.sender == tx.origin, "do not withdraw from contract");
PoolInfo storage pool = poolInfo[_pid];
updatePool(_pid);
UserInfo storage user = poolInfo[_pid].lpTokenInfo.userInfo[msg
.sender];
require(user.amount >= _amount, "withdraw: _amount not good");
uint256 pending = user
.amount
.mul(pool.lpTokenInfo.lpAccPerShare)
.div(1e12)
.sub(user.rewardDebt);
if (pending > 0) {
//create the stream or add funds to stream
(bool hasVotingStream, bool hasNormalStream) = IXStream(stream).hasStream(
msg.sender
);
/* Approve the Stream contract to spend. */
IXDEX(xdexToken).approve(stream, pending);
if (_pid == votingPoolId) {
if (hasVotingStream) {
//add fund
uint256 streamId = IXStream(stream).getStreamId(
msg.sender,
StreamTypeVoting
);
require(streamId > 0, "not valid stream id");
IXDEX(xdexToken).approve(stream, pending);
IXStream(stream).fundsToStream(xdexToken,streamId, pending);
}
} else {
if (hasNormalStream) {
//add fund
uint256 streamId = IXStream(stream).getStreamId(
msg.sender,
StreamTypeNormal
);
require(streamId > 0, "not valid stream id");
IXDEX(xdexToken).approve(stream, pending);
IXStream(stream).fundsToStream(xdexToken,streamId, pending);
}
}
}
if (_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpTokenInfo.lpToken.safeTransfer(
address(msg.sender),
_amount
);
}
user.rewardDebt = user
.amount
.mul(pool.lpTokenInfo.lpAccPerShare)
.div(1e12);
emit Withdraw(msg.sender, _pid, address(_lpToken), _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid)
public
nonReentrant
poolExists(_pid)
{
PoolInfo storage pool = poolInfo[_pid];
LpTokenInfo storage lpInfo = pool.lpTokenInfo;
UserInfo storage user = lpInfo.userInfo[msg.sender];
if (user.amount > 0) {
lpInfo.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(
msg.sender,
_pid,
address(lpInfo.lpToken),
user.amount
);
user.amount = 0;
user.rewardDebt = 0;
}
}
function getXCountToReward(uint256 _from, uint256 _to)
public
view
returns (
uint256 _totalReward,
uint256 _stageFrom,
uint256 _stageTo
)
{
require(_from <= _to, "_from must <= _to");
uint256 stageFrom = 0;
uint256 stageTo = 0;
if (_to < startBlock) {
return (0, stageFrom, stageTo);
}
if(bonusEndBlocks.length==0) return (0, stageFrom, stageTo);
if (
_from >= startBlock.add(bonusEndBlocks[bonusEndBlocks.length - 1])
) {
return (
_to.sub(_from).mul(tokensPerBlock[tokensPerBlock.length - 1]),
stageFrom,
stageTo
);
}
uint256 total = 0;
for (uint256 i = 0; i < bonusEndBlocks.length; i++) {
uint256 actualEndBlock = startBlock.add(bonusEndBlocks[i]);
if (_from > actualEndBlock) {
stageFrom = stageFrom.add(1);
}
if (_to > actualEndBlock) {
stageTo = stageTo.add(1);
}
}
uint256 tStageFrom = stageFrom;
while (_from < _to) {
if (_from < startBlock) {
_from = startBlock;
}
uint256 indexDiff = stageTo.sub(tStageFrom);
if (indexDiff == 0) {
total += (_to - _from) * tokensPerBlock[tStageFrom];
_from = _to;
} else if (indexDiff > 0) {
uint256 actualRes = startBlock.add(bonusEndBlocks[tStageFrom]);
total += (actualRes - _from) * tokensPerBlock[tStageFrom];
_from = actualRes;
tStageFrom = tStageFrom.add(1);
} else {
//this never happen
break;
}
}
return (total, stageFrom, stageTo);
}
function getCurRewardPerBlock() public view returns (uint256) {
uint256 bnum = block.number;
if (bnum < startBlock) {
return 0;
}
if(bonusEndBlocks.length==0) return 0;
if (bnum >= startBlock.add(bonusEndBlocks[bonusEndBlocks.length - 1])) {
return tokensPerBlock[tokensPerBlock.length - 1];
}
uint256 stage = 0;
for (uint256 i = 0; i < bonusEndBlocks.length; i++) {
uint256 actualEndBlock = startBlock.add(bonusEndBlocks[i]);
if (bnum > actualEndBlock) {
stage = stage.add(1);
}
}
require(
stage >= 0 && stage < tokensPerBlock.length,
"tokensPerBlock.length: not good"
);
return tokensPerBlock[stage];
}
// Any airdrop tokens (in whitelist) sent to this contract, should transfer to SAFU
function claimRewards(address token, uint256 amount) public onlyCore {
require(SAFU != address(0), "not valid SAFU address");
require(claimableTokens[token], "not claimable token");
IERC20(token).safeTransfer(SAFU, amount);
emit Claim(SAFU, token, amount);
}
function updateClaimableTokens(address token, bool claimable)
public
onlyCore
{
claimableTokens[token] = claimable;
}
function setCore(address _core) public onlyCore {
core = _core;
emit CoreTransferred(core, _core);
}
function setSAFU(address _safu) public onlyCore {
SAFU = _safu;
emit SetSAFU(_safu);
}
}
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw(uint256 _pid)
public
nonReentrant
poolExists(_pid)
{
PoolInfo storage pool = poolInfo[_pid];
LpTokenInfo storage lpInfo = pool.lpTokenInfo;
UserInfo storage user = lpInfo.userInfo[msg.sender];
if (user.amount > 0) {
lpInfo.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(
msg.sender,
_pid,
address(lpInfo.lpToken),
user.amount
);
user.amount = 0;
user.rewardDebt = 0;
}
}
| 13,029,846 |
pragma solidity ^0.6.6;
contract Election {
struct Candidate {
uint id;
string name;
uint voteCount;
}
/*
Mapping types are declared as mapping(_KeyType => _ValueType).
_KeyType can be almost any type except for a mapping, a dynamically sized array, a contract, an enum and a struct.
_ValueType can actually be any type, including mappings.
So this mapping will map the id to a Candidate struct.
*/
mapping (uint => Candidate) public candidates;
// This uint will serve as an id for each candidate that will be stored in a map below.
// The id will simply be incremented for each candidate.
uint public candidateIdIncrement;
// We will store true if the the voter at the address has already voted, fals otherwise.
mapping (address => bool) public voter;
event eventVote(
uint indexed _candidateId
);
constructor() public {
// Constructor is once executed when this smart contract is deployed to the blockchain.
// Here we use it to add candidates to the candidates mapping.
addCandidate("Alice");
addCandidate("Bob");
// Note that the way this contract is built, the list of candidates can't be modified after deployment!
// (We could add functionality for that later)
}
// Add a candidate
function addCandidate(string memory _name) private {
// Increment the candidate id.
candidateIdIncrement++;
// Store a new Candiate struct instance in the candidates mapping.
candidates[candidateIdIncrement] = Candidate(candidateIdIncrement, _name, 0);
}
function vote(uint _candidateId) public {
// Constraint 1: Voter can not yet have voted already.
// Here msg.sender is the address of the voter, which we have registered to a boolean in our voter mapping.
require(!voter[msg.sender]);
// Constraint 2: _candidateId must be valid.
require(_candidateId > 0 && _candidateId <= candidateIdIncrement);
// Mark the voter as having performed a vote.
voter[msg.sender] = true;
// Increase the vote count of the candidate.
candidates[_candidateId].voteCount++;
emit eventVote(_candidateId);
}
}
|
Constraint 1: Voter can not yet have voted already. Here msg.sender is the address of the voter, which we have registered to a boolean in our voter mapping. Constraint 2: _candidateId must be valid. Mark the voter as having performed a vote. Increase the vote count of the candidate.
|
function vote(uint _candidateId) public {
require(!voter[msg.sender]);
require(_candidateId > 0 && _candidateId <= candidateIdIncrement);
voter[msg.sender] = true;
candidates[_candidateId].voteCount++;
emit eventVote(_candidateId);
}
| 12,879,276 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
import "hardhat/console.sol"; // dev & testing
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./IContractRegistry.sol";
import "./IProjectCollection.sol";
// The ProjectCollection represents offsetting projects as ERC721 tokens
// This makes it possible to transfer ownership of projects via transfers
// The Projects added serve as a data source for the BatchNFTs and project-vintage ERC20s
contract ProjectCollection is IProjectCollection, ERC721, Ownable {
using Counters for Counters.Counter;
event ProjectMinted(address sender, string purpose);
address public contractRegistry;
Counters.Counter private _tokenIds;
// WIP: The fields and naming is subject to change
// MetaData for attributes like retirement dates, link to the registry
struct ProjectData {
string projectId;
string standard;
string methodology;
string region;
string metaDataHash;
string tokenURI;
address controller; // could be a multisig that can change project data
}
mapping (uint256 => ProjectData) public projects;
// Mapping all projectIds for uniqueness check
mapping (string => bool) public projectIds;
mapping (string => uint) public pidToTokenId;
constructor() ERC721("Co2ken Project Collection", "Co2ken-PNFT") {}
// Note: Not sure if this function is really necessary
function setContractRegistry(address _address) public onlyOwner {
contractRegistry = _address;
}
// Updates the controller, the entity in charge of the ProjectData
// Note: Questionable if needed if this stays ERC721, as this could be the NFT owner
function updateController(uint tokenId, address _controller) public {
require(msg.sender==ownerOf(tokenId), "Error: Caller is not the owner");
projects[tokenId].controller = _controller;
}
// Adding a new project is currently permissionless
// updating will require permission
function addNewProject(
address to,
string memory projectId,
string memory standard,
string memory methodology,
string memory region,
string memory metaDataHash,
string memory tokenURI
)
public override
returns (uint256)
{
require(projectIds[projectId]==false, "Project already exists");
projectIds[projectId] = true;
_tokenIds.increment();
uint256 newItemId = _tokenIds.current();
// console.log("DEBUG sol: minting Project NFT to ", to);
// console.log("DEBUG sol: newItemId is ", newItemId);
_mint(to, newItemId);
projects[newItemId].projectId = projectId;
projects[newItemId].methodology = methodology;
projects[newItemId].standard = standard;
projects[newItemId].region = region;
projects[newItemId].metaDataHash = metaDataHash;
projects[newItemId].tokenURI = tokenURI;
emit ProjectMinted(to, tokenURI);
pidToTokenId[projectId] = newItemId;
return newItemId;
}
function updateProject(
uint tokenId,
string memory projectId,
string memory standard,
string memory methodology,
string memory region,
string memory metaDataHash,
string memory tokenURI
)
public onlyOwner()
{
require(projectIds[projectId]==true, "Project does not yet exist, can't update");
projects[tokenId].projectId = projectId;
projects[tokenId].methodology = methodology;
projects[tokenId].standard = standard;
projects[tokenId].region = region;
projects[tokenId].metaDataHash = metaDataHash;
projects[tokenId].tokenURI = tokenURI;
}
function removeProject(uint tokenId) public onlyOwner {
delete projects[tokenId];
}
// Retrieve all data from ProjectNFT struct
function getProjectDataByTokenId(uint256 tokenId) public view
returns (string memory, string memory, string memory, string memory, string memory, string memory)
{
return (
projects[tokenId].projectId,
projects[tokenId].methodology,
projects[tokenId].standard,
projects[tokenId].region,
projects[tokenId].metaDataHash,
projects[tokenId].tokenURI
);
}
// Retrieve data from ProjectNFT relevant for pools
function getProjectDataByProjectId(string memory projectId) public view
returns (string memory, string memory, string memory)
{
uint tokenId = pidToTokenId[projectId];
return (
projects[tokenId].standard,
projects[tokenId].methodology,
projects[tokenId].region
);
}
}
|
Retrieve all data from ProjectNFT struct
|
function getProjectDataByTokenId(uint256 tokenId) public view
returns (string memory, string memory, string memory, string memory, string memory, string memory)
{
return (
projects[tokenId].projectId,
projects[tokenId].methodology,
projects[tokenId].standard,
projects[tokenId].region,
projects[tokenId].metaDataHash,
projects[tokenId].tokenURI
);
}
| 12,590,231 |
/*
Copyright 2020 DODO ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
import {SafeMath} from "../lib/SafeMath.sol";
import {DecimalMath} from "../lib/DecimalMath.sol";
import {DODOMath} from "../lib/DODOMath.sol";
import {Types} from "../lib/Types.sol";
import {IDODOLpToken} from "../intf/IDODOLpToken.sol";
import {Storage} from "./Storage.sol";
import {Settlement} from "./Settlement.sol";
import {Pricing} from "./Pricing.sol";
/**
* @title LiquidityProvider
* @author DODO Breeder
*
* @notice Functions for liquidity provider operations
*/
contract LiquidityProvider is Storage, Pricing, Settlement {
using SafeMath for uint256;
// ============ Events ============
event Deposit(
address indexed payer,
address indexed receiver,
bool isBaseToken,
uint256 amount,
uint256 lpTokenAmount
);
event Withdraw(
address indexed payer,
address indexed receiver,
bool isBaseToken,
uint256 amount,
uint256 lpTokenAmount
);
event ChargePenalty(address indexed payer, bool isBaseToken, uint256 amount);
// ============ Modifiers ============
modifier depositQuoteAllowed() {
require(_DEPOSIT_QUOTE_ALLOWED_, "DEPOSIT_QUOTE_NOT_ALLOWED");
_;
}
modifier depositBaseAllowed() {
require(_DEPOSIT_BASE_ALLOWED_, "DEPOSIT_BASE_NOT_ALLOWED");
_;
}
// ============ Routine Functions ============
function withdrawBase(uint256 amount) external returns (uint256) {
return withdrawBaseTo(msg.sender, amount);
}
function depositBase(uint256 amount) external returns (uint256) {
return depositBaseTo(msg.sender, amount);
}
function withdrawQuote(uint256 amount) external returns (uint256) {
return withdrawQuoteTo(msg.sender, amount);
}
function depositQuote(uint256 amount) external returns (uint256) {
return depositQuoteTo(msg.sender, amount);
}
function withdrawAllBase() external returns (uint256) {
return withdrawAllBaseTo(msg.sender);
}
function withdrawAllQuote() external returns (uint256) {
return withdrawAllQuoteTo(msg.sender);
}
// ============ Deposit Functions ============
function depositQuoteTo(address to, uint256 amount)
public
preventReentrant
depositQuoteAllowed
returns (uint256)
{
(, uint256 quoteTarget) = getExpectedTarget();
uint256 totalQuoteCapital = getTotalQuoteCapital();
uint256 capital = amount;
if (totalQuoteCapital == 0) {
// give remaining quote token to lp as a gift
capital = amount.add(quoteTarget);
} else if (quoteTarget > 0) {
capital = amount.mul(totalQuoteCapital).div(quoteTarget);
}
// settlement
_quoteTokenTransferIn(msg.sender, amount);
_mintQuoteCapital(to, capital);
_TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.add(amount);
emit Deposit(msg.sender, to, false, amount, capital);
return capital;
}
function depositBaseTo(address to, uint256 amount)
public
preventReentrant
depositBaseAllowed
returns (uint256)
{
(uint256 baseTarget, ) = getExpectedTarget();
uint256 totalBaseCapital = getTotalBaseCapital();
uint256 capital = amount;
if (totalBaseCapital == 0) {
// give remaining base token to lp as a gift
capital = amount.add(baseTarget);
} else if (baseTarget > 0) {
capital = amount.mul(totalBaseCapital).div(baseTarget);
}
// settlement
_baseTokenTransferIn(msg.sender, amount);
_mintBaseCapital(to, capital);
_TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.add(amount);
emit Deposit(msg.sender, to, true, amount, capital);
return capital;
}
// ============ Withdraw Functions ============
function withdrawQuoteTo(address to, uint256 amount) public preventReentrant returns (uint256) {
// calculate capital
(, uint256 quoteTarget) = getExpectedTarget();
uint256 totalQuoteCapital = getTotalQuoteCapital();
require(totalQuoteCapital > 0, "NO_QUOTE_LP");
uint256 requireQuoteCapital = amount.mul(totalQuoteCapital).divCeil(quoteTarget);
require(
requireQuoteCapital <= getQuoteCapitalBalanceOf(msg.sender),
"LP_QUOTE_CAPITAL_BALANCE_NOT_ENOUGH"
);
// handle penalty, penalty may exceed amount
uint256 penalty = getWithdrawQuotePenalty(amount);
require(penalty < amount, "PENALTY_EXCEED");
// settlement
_TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(amount);
_burnQuoteCapital(msg.sender, requireQuoteCapital);
_quoteTokenTransferOut(to, amount.sub(penalty));
_donateQuoteToken(penalty);
emit Withdraw(msg.sender, to, false, amount.sub(penalty), requireQuoteCapital);
emit ChargePenalty(msg.sender, false, penalty);
return amount.sub(penalty);
}
function withdrawBaseTo(address to, uint256 amount) public preventReentrant returns (uint256) {
// calculate capital
(uint256 baseTarget, ) = getExpectedTarget();
uint256 totalBaseCapital = getTotalBaseCapital();
require(totalBaseCapital > 0, "NO_BASE_LP");
uint256 requireBaseCapital = amount.mul(totalBaseCapital).divCeil(baseTarget);
require(
requireBaseCapital <= getBaseCapitalBalanceOf(msg.sender),
"LP_BASE_CAPITAL_BALANCE_NOT_ENOUGH"
);
// handle penalty, penalty may exceed amount
uint256 penalty = getWithdrawBasePenalty(amount);
require(penalty <= amount, "PENALTY_EXCEED");
// settlement
_TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(amount);
_burnBaseCapital(msg.sender, requireBaseCapital);
_baseTokenTransferOut(to, amount.sub(penalty));
_donateBaseToken(penalty);
emit Withdraw(msg.sender, to, true, amount.sub(penalty), requireBaseCapital);
emit ChargePenalty(msg.sender, true, penalty);
return amount.sub(penalty);
}
// ============ Withdraw all Functions ============
function withdrawAllQuoteTo(address to) public preventReentrant returns (uint256) {
uint256 withdrawAmount = getLpQuoteBalance(msg.sender);
uint256 capital = getQuoteCapitalBalanceOf(msg.sender);
// handle penalty, penalty may exceed amount
uint256 penalty = getWithdrawQuotePenalty(withdrawAmount);
require(penalty <= withdrawAmount, "PENALTY_EXCEED");
// settlement
_TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(withdrawAmount);
_burnQuoteCapital(msg.sender, capital);
_quoteTokenTransferOut(to, withdrawAmount.sub(penalty));
_donateQuoteToken(penalty);
emit Withdraw(msg.sender, to, false, withdrawAmount, capital);
emit ChargePenalty(msg.sender, false, penalty);
return withdrawAmount.sub(penalty);
}
function withdrawAllBaseTo(address to) public preventReentrant returns (uint256) {
uint256 withdrawAmount = getLpBaseBalance(msg.sender);
uint256 capital = getBaseCapitalBalanceOf(msg.sender);
// handle penalty, penalty may exceed amount
uint256 penalty = getWithdrawBasePenalty(withdrawAmount);
require(penalty <= withdrawAmount, "PENALTY_EXCEED");
// settlement
_TARGET_BASE_TOKEN_AMOUNT_ = _TARGET_BASE_TOKEN_AMOUNT_.sub(withdrawAmount);
_burnBaseCapital(msg.sender, capital);
_baseTokenTransferOut(to, withdrawAmount.sub(penalty));
_donateBaseToken(penalty);
emit Withdraw(msg.sender, to, true, withdrawAmount, capital);
emit ChargePenalty(msg.sender, true, penalty);
return withdrawAmount.sub(penalty);
}
// ============ Helper Functions ============
function _mintBaseCapital(address user, uint256 amount) internal {
IDODOLpToken(_BASE_CAPITAL_TOKEN_).mint(user, amount);
}
function _mintQuoteCapital(address user, uint256 amount) internal {
IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).mint(user, amount);
}
function _burnBaseCapital(address user, uint256 amount) internal {
IDODOLpToken(_BASE_CAPITAL_TOKEN_).burn(user, amount);
}
function _burnQuoteCapital(address user, uint256 amount) internal {
IDODOLpToken(_QUOTE_CAPITAL_TOKEN_).burn(user, amount);
}
// ============ Getter Functions ============
function getLpBaseBalance(address lp) public view returns (uint256 lpBalance) {
uint256 totalBaseCapital = getTotalBaseCapital();
(uint256 baseTarget, ) = getExpectedTarget();
if (totalBaseCapital == 0) {
return 0;
}
lpBalance = getBaseCapitalBalanceOf(lp).mul(baseTarget).div(totalBaseCapital);
return lpBalance;
}
function getLpQuoteBalance(address lp) public view returns (uint256 lpBalance) {
uint256 totalQuoteCapital = getTotalQuoteCapital();
(, uint256 quoteTarget) = getExpectedTarget();
if (totalQuoteCapital == 0) {
return 0;
}
lpBalance = getQuoteCapitalBalanceOf(lp).mul(quoteTarget).div(totalQuoteCapital);
return lpBalance;
}
function getWithdrawQuotePenalty(uint256 amount) public view returns (uint256 penalty) {
require(amount <= _QUOTE_BALANCE_, "DODO_QUOTE_BALANCE_NOT_ENOUGH");
if (_R_STATUS_ == Types.RStatus.BELOW_ONE) {
uint256 spareBase = _BASE_BALANCE_.sub(_TARGET_BASE_TOKEN_AMOUNT_);
uint256 price = getOraclePrice();
uint256 fairAmount = DecimalMath.mul(spareBase, price);
uint256 targetQuote = DODOMath._SolveQuadraticFunctionForTarget(
_QUOTE_BALANCE_,
_K_,
fairAmount
);
// if amount = _QUOTE_BALANCE_, div error
uint256 targetQuoteWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget(
_QUOTE_BALANCE_.sub(amount),
_K_,
fairAmount
);
return targetQuote.sub(targetQuoteWithWithdraw.add(amount));
} else {
return 0;
}
}
function getWithdrawBasePenalty(uint256 amount) public view returns (uint256 penalty) {
require(amount <= _BASE_BALANCE_, "DODO_BASE_BALANCE_NOT_ENOUGH");
if (_R_STATUS_ == Types.RStatus.ABOVE_ONE) {
uint256 spareQuote = _QUOTE_BALANCE_.sub(_TARGET_QUOTE_TOKEN_AMOUNT_);
uint256 price = getOraclePrice();
uint256 fairAmount = DecimalMath.divFloor(spareQuote, price);
uint256 targetBase = DODOMath._SolveQuadraticFunctionForTarget(
_BASE_BALANCE_,
_K_,
fairAmount
);
// if amount = _BASE_BALANCE_, div error
uint256 targetBaseWithWithdraw = DODOMath._SolveQuadraticFunctionForTarget(
_BASE_BALANCE_.sub(amount),
_K_,
fairAmount
);
return targetBase.sub(targetBaseWithWithdraw.add(amount));
} else {
return 0;
}
}
}
|
handle penalty, penalty may exceed amount settlement
|
function withdrawAllQuoteTo(address to) public preventReentrant returns (uint256) {
uint256 withdrawAmount = getLpQuoteBalance(msg.sender);
uint256 capital = getQuoteCapitalBalanceOf(msg.sender);
uint256 penalty = getWithdrawQuotePenalty(withdrawAmount);
require(penalty <= withdrawAmount, "PENALTY_EXCEED");
_TARGET_QUOTE_TOKEN_AMOUNT_ = _TARGET_QUOTE_TOKEN_AMOUNT_.sub(withdrawAmount);
_burnQuoteCapital(msg.sender, capital);
_quoteTokenTransferOut(to, withdrawAmount.sub(penalty));
_donateQuoteToken(penalty);
emit Withdraw(msg.sender, to, false, withdrawAmount, capital);
emit ChargePenalty(msg.sender, false, penalty);
return withdrawAmount.sub(penalty);
}
| 5,469,006 |
pragma solidity 0.8.7;
// SPDX-License-Identifier: MIT
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeEIP20.sol";
import "./Ownable.sol";
import "./Pausable.sol";
import "./Lockable.sol";
/**
* @title StakePool
* @notice Implements a Ownable, Pausable, Lockable, ReentrancyGuard
*/
contract StakePool is Ownable, Pausable, Lockable, ReentrancyGuard {
using SafeMath for uint256;
using SafeEIP20 for IEIP20;
// We usually require to know who are all the stakeholders.
address[] internal stakeholders;
string[] internal poollist;
uint256 internal currentTimestamp = block.timestamp;
struct Stake {
uint256 amount; // The stake amount
uint256 duration; // The duration in weeks of how long the stake should be locked from unstaking
address referral; // The affiliate address
string pool; // The selected pool
uint256 reward; // The staking reward earned
uint256 reward_paid; // The staking reward paid out so far
uint256 reward_count; // The total amount of times a reward has been distributed
uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn
uint256 bonus; // The referral bonus earned
uint256 bonus_paid; // The referral bonus paid out so far
uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn
uint256 bonus_updated_at; // The last time a bonus is updated
uint256 reward_updated_at; // The last time a staking reward is updated
uint256 bonus_last_withdraw_at; // The last time a bonus is withrawn
uint256 reward_last_withdraw_at; // The last time a staking reward is withrawn
uint256 last_withdraw_at; // The last time a stake is withrawn
uint256 created_at; // Timestamp of when stake was created
uint256 updated_at; // Timestamp of when stake was last modified
bool valid; // If a stake is valid or not
}
struct Pool {
string name; // The name of the pool, should be a single word in lowercase
address staking_token; // The staking token address
address reward_token; // The staking reward token address
address bonus_token; // The bonus token address
uint256 duration_in_weeks; // The duration in weeks of the pool
uint256 reward_percentage; // The reward percentage of the pool
uint256 minimum_stake; // The minimum amount a stakeholder can stake
uint256 reward_halving; // Will halve reward every 2 year untill the 6th year if activated
uint256 referral_bonus_percentage; // The referral bonus percentage of the pool
uint256 reward_claimable_after_duration; // The duration in weeks after which a reward can be withdrawn
uint256 bonus_claimable_after_duration; // The duration in weeks after which a bonus can be withdrawn
address default_referral; // The default referral address of the pool
uint256 created_at; // Timestamp of when pool was created
uint256 updated_at; // Timestamp of when pool was last modified
bool valid; // If a pool is valid or not
}
//The stakes for each stakeholder.
mapping(address => Stake) internal stakes;
//The pools for each poollist.
mapping(string => Pool) internal pools;
mapping(address => uint256) private _balances;
uint256 private _totalSupply;
uint256 public balance;
constructor() {
}
receive() payable external {
balance += msg.value;
emit TransferReceived(_msgSender(), msg.value);
}
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/* ========== STAKES METHODS ----------
/**
* @notice A method for a stakeholder to create a stake.
* @param amount The size of the stake to be created.
* @param _pool The pool to stake in.
* @param _affiliate An affiliate address to benefit from the stake.
*/
function createStake(uint256 amount, string memory _pool, address _affiliate) external nonReentrant whenNotPaused whenNotLocked {
require(amount > 0, "Insufficient stake amount");
Stake storage stake = stakes[_msgSender()];
if (!stake.valid) {
_isValidPool(_pool);
Pool memory pool = pools[_pool];
require(pool.valid, "Invalid pool");
require(amount >= pool.minimum_stake, "Stake is below minimum allowed stake");
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount);
addStakeholder(_msgSender());
stake.amount = stake.amount.add(amount);
stake.pool = _pool;
stake.duration = pool.duration_in_weeks;
stake.reward_claimable_after_duration = pool.reward_claimable_after_duration;
stake.bonus_claimable_after_duration = pool.bonus_claimable_after_duration;
stake.created_at = currentTimestamp;
stake.updated_at = currentTimestamp;
stake.valid = true;
stake.reward = stake.reward.add(0);
stake.reward_count = 0;
stake.bonus = stake.bonus.add(0);
address _referral_address = pool.default_referral;
//check if the referral is a stakeholder and also if _msgSender is not the referral
(bool _isReferralStakeholder,) = isStakeholder(_affiliate);
if (_isReferralStakeholder && _msgSender() != _affiliate){
_referral_address = _affiliate;
}
uint256 referral_bonus = amount / (100 * (10 ** 18));
uint256 affiliate_bonus = referral_bonus.mul(pool.referral_bonus_percentage);
stake.referral = _referral_address;
Stake storage referral_stake = stakes[_referral_address];
referral_stake.bonus = referral_stake.bonus.add(affiliate_bonus);
emit Staked(_msgSender(), amount, pool.name);
}else{
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
_totalSupply = _totalSupply.add(amount);
_balances[_msgSender()] = _balances[_msgSender()].add(amount);
IEIP20(pool.staking_token).safeTransferFrom(_msgSender(), address(this), amount);
stake.amount = stake.amount.add(amount);
stake.updated_at = currentTimestamp;
emit Staked(_msgSender(), amount, pool.name);
}
}
/**
* @notice A method for a stakeholder to remove a stake.
* @param amount The size of the stake to be removed.
*/
function withdraw(uint256 amount) public nonReentrant whenNotPaused whenNotLocked {
require(amount > 0, "Cannot withdraw 0");
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
require(_isExpired(stake.created_at, stake.duration), "You can't withdraw untill the stake duration is over.");
require(stake.amount >= amount, "Insufficient amount of stakes");
stake.amount = stake.amount.sub(amount);
if (stake.amount == 0) removeStakeholder(_msgSender());
_totalSupply = _totalSupply.sub(amount);
_balances[_msgSender()] = _balances[_msgSender()].sub(amount);
IEIP20(pool.staking_token).safeTransfer(_msgSender(), amount);
emit Withdrawn(_msgSender(), amount, stake.pool);
}
/**
* @notice A method to retrieve the stake for a stakeholder.
* @param _stakeholder The stakeholder to retrieve the stake for.
* @return uint256 The amount of wei staked.
*/
function stakeOf(address _stakeholder) public view returns (uint256, string memory) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "No stake found.");
return (stake.amount,stake.pool);
}
/**
* @notice A method to the aggregated stakes from all stakeholders.
* @return uint256 The aggregated stakes from all stakeholders.
*/
function totalStakes() public view returns (uint256) {
uint256 _totalStakes = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
Stake memory stake = stakes[stakeholders[s]];
_totalStakes = _totalStakes.add(stake.amount);
}
return _totalStakes;
}
/**
* @notice A method to check if an address is a stakeholder.
* @param _address The address to verify.
* @return bool, uint256 Whether the address is a stakeholder,
* and if so its position in the stakeholders array.
*/
function isStakeholder(address _address) public view returns (bool, uint256) {
for (uint256 s = 0; s < stakeholders.length; s += 1) {
if (_address == stakeholders[s]) return (true, s);
}
return (false, 0);
}
function exit() external {
withdraw(_balances[_msgSender()]);
getReward();
getBonus();
}
/* ========== REWARD METHODS ========== */
/**
* @notice A method to allow a stakeholder to check his rewards.
* @param _stakeholder The stakeholder to check rewards for.
*/
function rewardOf(address _stakeholder) public view returns (uint256) {
Stake memory stake = stakes[_stakeholder];
return stake.reward;
}
/**
* @notice A method to the aggregated rewards from all stakeholders.
* @return uint256 The aggregated rewards from all stakeholders.
*/
function totalRewards() public view returns (uint256) {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake memory stake = stakes[stakeholder];
_totalRewards = _totalRewards.add(stake.reward);
}
return _totalRewards;
}
function calculateTotalHalvedReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 reward = stake.amount / (100 * (10 ** 18));
uint256 total_reward = reward.mul(pool.reward_percentage);
uint256 total_halved_reward = total_reward;
if(pool.reward_halving > 0){
if (block.timestamp >= pool.created_at + 104 weeks) {
total_halved_reward = total_reward/2;
if(block.timestamp >= pool.created_at + 208 weeks){
total_halved_reward = total_reward/4;
if(block.timestamp >= pool.created_at + 312 weeks){
total_halved_reward = total_reward;
}
}
}
}
return total_halved_reward;
}
/**
* @notice A simple method that calculates the total rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateTotalReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
return calculateTotalHalvedReward(_stakeholder);
}
/**
* @notice A simple method that calculates the weekly rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateWeeklyReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 total_reward = calculateTotalReward(_stakeholder);
uint256 weekly_reward = total_reward / pool.duration_in_weeks;
return weekly_reward;
}
/**
* @notice A simple method that calculates the daily rewards for each stakeholder.
* @param _stakeholder The stakeholder to calculate rewards for.
*/
function calculateDailyReward(address _stakeholder) public view returns (uint256) {
require(_stakeholder != address(0), "Invalid stakeholder");
Stake memory stake = stakes[_stakeholder];
require(stake.valid, "Stake not found");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 weekly_reward = calculateWeeklyReward(_stakeholder);
uint256 daily_reward = weekly_reward / 7;
return daily_reward;
}
/**
* @notice A method to distribute total rewards to all stakeholders.
*/
function distributeTotalRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _reward = calculateTotalReward(stakeholder);
uint256 _next_reward_in_days = 7;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
if (_reward > stake.reward) {
if (stake.reward_count < _max_reward_count) {
stake.reward = _reward;
stake.reward_count = stake.reward_count.add(_max_reward_count);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit TotalRewardDistributed(_totalRewards);
}
/**
* @notice A method to distribute weekly rewards to all stakeholders.
*/
function distributeWeeklyRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _total_reward = calculateTotalReward(stakeholder);
uint256 _reward = calculateWeeklyReward(stakeholder);
uint256 _next_reward_in_days = 7;
uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
//check if staking period for stakeholder has not expired
if (!_isExpired(stake.created_at, stake.duration)) {
if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) {
stake.reward = stake.reward.add(_reward);
stake.reward_count = stake.reward_count.add(_next_reward_in_days);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit WeeklyRewardDistributed(_totalRewards);
}
/**
* @notice A method to distribute daily rewards to all stakeholders.
*/
function distributeDailyRewards() public payable onlyOwner {
uint256 _totalRewards = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake storage stake = stakes[stakeholder];
if(stake.valid){
uint256 _total_reward = calculateTotalReward(stakeholder);
uint256 _reward = calculateDailyReward(stakeholder);
uint256 _next_reward_in_days = 1;
uint256 _check_reward_count_exceeded = stake.reward_count + _next_reward_in_days;
uint256 _max_reward_count = stake.duration.mul(_next_reward_in_days);
//check if staking period for stakeholder has not expired
if (!_isExpired(stake.created_at, stake.duration)) {
if (stake.reward_count < _max_reward_count && _check_reward_count_exceeded <= _max_reward_count && _isExpiredInDays(stake.reward_updated_at, _next_reward_in_days) && _total_reward > stake.reward) {
stake.reward = stake.reward.add(_reward);
stake.reward_count = stake.reward_count.add(_next_reward_in_days);
stake.reward_updated_at = currentTimestamp;
_totalRewards = _totalRewards.add(_reward);
}
}
}
}
emit DailyRewardDistributed(_totalRewards);
}
/**
* @notice A method to allow a stakeholder to withdraw his rewards.
*/
function getReward() public nonReentrant whenNotPaused whenNotLocked {
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
require(_isExpired(stake.created_at, stake.reward_claimable_after_duration), "Can't withdraw reward until the holding duration is over.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 _reward = stake.reward;
if (_reward > 0) {
IEIP20(pool.reward_token).safeTransfer(_msgSender(), _reward);
stake.reward = 0; //reset amount
stake.reward_count = 0; //reset count
stake.reward_last_withdraw_at = currentTimestamp;
stake.reward_paid = stake.reward_paid.add(_reward);
emit RewardPaid(_msgSender(), _reward);
}
}
/* ========== REFERRAL BONUS METHODS ========== */
/**
* @notice A method to allow a stakeholder to check his bonus.
* @param _stakeholder The stakeholder to check bonus for.
*/
function bonusOf(address _stakeholder) public view returns (uint256) {
Stake memory stake = stakes[_stakeholder];
return stake.bonus;
}
/**
* @notice A method to the aggregated bonuses from all stakeholders.
* @return uint256 The aggregated bonuses from all stakeholders.
*/
function totalBonuses() public view returns (uint256) {
uint256 _totalBonuses = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
address stakeholder = stakeholders[s];
Stake memory stake = stakes[stakeholder];
_totalBonuses = _totalBonuses.add(stake.bonus);
}
return _totalBonuses;
}
/**
* @notice A method to allow a stakeholder to withdraw his bonus.
*/
function getBonus() public nonReentrant whenNotPaused whenNotLocked {
Stake storage stake = stakes[_msgSender()];
require(stake.valid, "No stake found.");
require(_isExpired(stake.created_at, stake.bonus_claimable_after_duration), "Can't withdraw reward until the holding duration is over.");
Pool memory pool = pools[stake.pool];
require(pool.valid, "Invalid pool");
uint256 _bonus = stake.bonus;
if (_bonus > 0) {
IEIP20(pool.bonus_token).safeTransfer(_msgSender(), _bonus);
stake.bonus = 0; //reset amount
stake.bonus_last_withdraw_at = currentTimestamp;
stake.bonus_paid = stake.bonus_paid.add(_bonus);
emit BonusPaid(_msgSender(), _bonus);
}
}
/* ========== POOL METHODS ========== */
/**
* @notice A method for a contract owner to create a staking pool.
* @param _name The name of the pool to be created.
* @param _minimum_stake The minimum a stakeholder can stake.
* @param _duration The duration in weeks of the pool to be created.
* @param _reward_percentage The total reward percentage of the pool to be created
* @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate
* @param _referral_bonus_percentage The referral bonus percentage of the pool to be created
* @param _default_referral The default affiliate address if none is set
* @param _reward_claimable_after When the reward will be claimable after specified weeks
* @param _bonus_claimable_after When the bonus will be claimable after specified weeks
* @param _staking_token The staking token contract address
* @param _reward_token The reward token contract address
* @param _bonus_token The bonus token contract address
*/
function createPool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner {
require(_duration > 0, "Duration in weeks can't be zero");
require(_minimum_stake > 0, "Minimum stake can't be zero");
require(_reward_percentage > 0, "Total reward percentage can't be zero");
Pool storage pool = pools[_name];
if (!pool.valid) {
_addPool(_name);
pool.name = _name;
pool.minimum_stake = _minimum_stake;
pool.duration_in_weeks = _duration;
pool.reward_percentage = _reward_percentage;
pool.reward_halving = (_reward_halving > 0)? 1 : 0;
pool.referral_bonus_percentage = _referral_bonus_percentage;
pool.default_referral = _default_referral;
pool.reward_claimable_after_duration = _reward_claimable_after;
pool.bonus_claimable_after_duration = _bonus_claimable_after;
pool.staking_token = _staking_token;
pool.reward_token = _reward_token;
pool.bonus_token = _bonus_token;
pool.created_at = currentTimestamp;
pool.valid = true;
}
emit PoolAdded(pool.name, _duration);
}
/**
* @notice A method for a contract owner to update a staking pool.
* @param _name The name of the pool to be updated.
* @param _minimum_stake The minimum a stakeholder can stake.
* @param _duration The duration in weeks of the pool to be created.
* @param _reward_percentage The reward percentage of the pool to be created
* @param _reward_halving Whether to activate reward halving or not. 1 to activate | 0 to deactivate
* @param _referral_bonus_percentage The referral bonus percentage of the pool to be created
* @param _default_referral The default affiliate address if none is set
* @param _reward_claimable_after When the reward will be claimable after specified weeks
* @param _bonus_claimable_after When the bonus will be claimable after specified weeks
* @param _staking_token The staking token contract address
* @param _reward_token The reward token contract address
* @param _bonus_token The bonus token contract address
*/
function updatePool(string memory _name, uint256 _minimum_stake, uint256 _duration, uint256 _reward_percentage, uint256 _reward_halving, uint256 _referral_bonus_percentage, address _default_referral, uint256 _reward_claimable_after, uint256 _bonus_claimable_after, address _staking_token, address _reward_token, address _bonus_token) public onlyOwner {
require(_duration > 0, "Duration in weeks can't be zero");
require(_minimum_stake > 0, "Minimum stake can't be zero");
require(_reward_percentage > 0, "Total reward percentage can't be zero");
Pool storage pool = pools[_name];
require(pool.valid, "No pool found.");
pool.name = _name;
pool.minimum_stake = _minimum_stake;
pool.duration_in_weeks = _duration;
pool.reward_percentage = _reward_percentage;
pool.reward_halving = (_reward_halving > 0)? 1 : 0;
pool.referral_bonus_percentage = _referral_bonus_percentage;
pool.default_referral = _default_referral;
pool.reward_claimable_after_duration = _reward_claimable_after;
pool.bonus_claimable_after_duration = _bonus_claimable_after;
pool.staking_token = _staking_token;
pool.reward_token = _reward_token;
pool.bonus_token = _bonus_token;
pool.updated_at = currentTimestamp;
emit PoolUpdated(pool.name, _duration);
}
/**
* @notice A method for a contract owner to remove a staking pool.
* @param _name The name of the pool to be removed.
*/
function removePool(string memory _name) public onlyOwner {
Pool storage pool = pools[_name];
require(pool.valid, "No pool found.");
(bool _isPool, uint256 s) = isPool(_name);
if (_isPool) {
//revert stakeholders stakes before removing the pool
for (uint256 i = 0; i < stakeholders.length; i += 1) {
address _stakeholder = stakeholders[i];
Stake storage stake = stakes[_stakeholder];
uint256 _stake = stake.amount;
stake.amount = stake.amount.sub(_stake);
if (stake.amount == 0) removeStakeholder(_stakeholder);
_totalSupply = _totalSupply.sub(_stake);
_balances[_stakeholder] = _balances[_stakeholder].sub(_stake);
IEIP20(pool.staking_token).safeTransfer(_stakeholder, _stake);
}
delete pools[_name];
poollist[s] = poollist[poollist.length - 1];
poollist.pop();
emit PoolDeleted(pool.name);
}
}
/**
* @notice A method to retrieve the pool with the name.
* @param _name The pool to retrieve
*/
function poolOf(string memory _name) public view returns (string memory, uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, address, address){
Pool memory pool = pools[_name];
require(pool.valid, "No pool found.");
return (pool.name, pool.minimum_stake, pool.duration_in_weeks, pool.reward_percentage, pool.reward_halving,pool.referral_bonus_percentage, pool.reward_claimable_after_duration, pool.bonus_claimable_after_duration, pool.staking_token,pool.reward_token,pool.bonus_token);
}
function poolStakes(string memory _pool) public view returns (uint256) {
uint256 _totalStakes = 0;
for (uint256 s = 0; s < stakeholders.length; s += 1) {
Stake memory stake = stakes[stakeholders[s]];
if(_compareStrings(stake.pool,_pool)){
_totalStakes = _totalStakes.add(stake.amount);
}
}
return _totalStakes;
}
/**
* @notice A method to check if a pool exist.
* @param _name The name to verify.
* @return bool, uint256 Whether the name exist,
* and if so its position in the poollist array.
*/
function isPool(string memory _name) public view returns (bool, uint256) {
for (uint256 s = 0; s < poollist.length; s += 1) {
if (_compareStrings(_name,poollist[s])) return (true, s);
}
return (false, 0);
}
/* ========== UTILS METHODS ========== */
function withdrawNative(uint amount, address payable destAddr) public onlyOwner {
require(amount <= balance, "Insufficient funds");
destAddr.transfer(amount);
balance -= amount;
emit TransferSent(_msgSender(), destAddr, amount);
}
function transferToken(address token, address to, uint256 amount) public onlyOwner {
uint256 EIP20balance = IEIP20(token).balanceOf(address(this));
require(amount <= EIP20balance, "balance is low");
IEIP20(token).safeTransfer(to, amount);
emit TransferSent(_msgSender(), to, amount);
}
function balanceOfToken(address token) public view returns (uint256) {
uint256 tokenBal = IEIP20(token).balanceOf(address(this));
return tokenBal;
}
function balanceOfNative() public view returns (uint256) {
uint256 nativeBal = address(this).balance;
return nativeBal;
}
/* ========== INTERNAL METHODS ========== */
/**
* @notice A method to add a stakeholder.
* @param _stakeholder The stakeholder to add.
*/
function addStakeholder(address _stakeholder) internal {
(bool _isStakeholder,) = isStakeholder(_stakeholder);
if (!_isStakeholder) stakeholders.push(_stakeholder);
}
/**
* @notice A method to remove a stakeholder.
* @param _stakeholder The stakeholder to remove.
*/
function removeStakeholder(address _stakeholder) internal {
(bool _isStakeholder, uint256 s) = isStakeholder(_stakeholder);
if (_isStakeholder) {
stakeholders[s] = stakeholders[stakeholders.length - 1];
stakeholders.pop();
Stake storage stake = stakes[_stakeholder];
stake.valid = false;
}
}
/**
* @notice A method to add a pool.
* @param _name The name to add.
*/
function _addPool(string memory _name) internal {
(bool _isPool,) = isPool(_name);
if (!_isPool) poollist.push(_name);
}
function _isValidPool (string memory _pool) internal view {
(bool _isPool, ) = isPool(_pool);
require(_isPool, "Invalid stake pool");
}
function _compareStrings(string memory _a, string memory _b) internal pure returns (bool) {
return (keccak256(bytes(_a)) == keccak256(bytes(_b)));
}
function _toLower(string memory str) internal pure returns (string memory) {
bytes memory bStr = bytes(str);
bytes memory bLower = new bytes(bStr.length);
for (uint i = 0; i < bStr.length; i++) {
// Uppercase character...
if ((uint8(bStr[i]) >= 65) && (uint8(bStr[i]) <= 90)) {
// So we add 32 to make it lowercase
bLower[i] = bytes1(uint8(bStr[i]) + 32);
} else {
bLower[i] = bStr[i];
}
}
return string(bLower);
}
function _isExpired(uint256 _time, uint256 _duration) internal view returns(bool){
if (block.timestamp >= _time + _duration * 1 weeks) {
return true;
} else {
return false;
}
}
function _isExpiredInDays(uint256 _time, uint256 _duration) internal view returns(bool){
if (block.timestamp >= _time + _duration * 1 days) {
return true;
} else {
return false;
}
}
/* ========== EVENTS ========== */
event Staked(address indexed sender, uint256 amount, string pool);
event Withdrawn(address indexed sender, uint256 amount, string pool);
event RewardPaid(address indexed user, uint256 reward);
event DailyRewardDistributed(uint256 reward);
event WeeklyRewardDistributed(uint256 reward);
event TotalRewardDistributed(uint256 reward);
event BonusPaid(address indexed user, uint256 bonus);
event PoolAdded(string pool, uint256 duration);
event PoolUpdated(string pool, uint256 duration);
event PoolDeleted(string pool);
event TransferReceived(address _from, uint _amount);
event TransferSent(address _from, address _destAddr, uint _amount);
}
|
A method to add a pool. _name The name to add./
|
function _addPool(string memory _name) internal {
(bool _isPool,) = isPool(_name);
if (!_isPool) poollist.push(_name);
}
| 927,721 |
/**
*Submitted for verification at Etherscan.io on 2021-11-16
*/
pragma solidity ^0.6.12;
// SPDX-License-Identifier: Creative Commons Attribution Non Commercial Share Alike 4.0 International
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address _owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// 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 ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
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, "low-lvl call fail");
}
/**
* @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, "lowlvl call with val fail");
}
/**
* @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, "low bal 4 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), "call 2 nocontract");
// 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);
}
}
}
}
contract Necro is Context, IBEP20, Ownable, ReentrancyGuard {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping(address => bool) private exclude;
mapping(address=>bool) private blackList;
mapping (address=> uint256) private lastPurchase;
uint8 private _decimals;
uint256 private _totalSupply;
uint256 private _burntamt;
uint256 public devFee = 5;
uint256 public LiquidityRate = 4;
uint256 public listingFee = 1;
uint256 public maxTxAllowed;
uint256 public LaunchTime;
string private _symbol;
string private _name;
address public redistributionWallet =0xE4Aa6e1647289EabfDeE4D032B9667929Bb44Bf1;
address public DevelopmentWallet = 0xE3b5912798de88dB513Bb9E8A66210B4b0768d80;
address public burnAddress = 0x000000000000000000000000000000000000dEaD; //burnAddress
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
constructor() ReentrancyGuard() public {
_decimals = 9;
_totalSupply = 100000000000000*10**uint256(_decimals);
_balances[msg.sender] = _totalSupply;
_name = "Necro Inu";
_symbol = "NECRO";
maxTxAllowed = 0*10**uint256(_decimals);
exclude[owner()]=true;
exclude[address(this)]=true;
exclude[redistributionWallet]=true;
exclude[burnAddress]=true;
exclude[DevelopmentWallet]=true;
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
address PairCreated = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = PairCreated;
emit Transfer(address(0), msg.sender, _totalSupply);
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view override returns (address) {
return owner();
}
/**
* @dev Returns the token decimals.
*/
function decimals() external view override returns (uint8) {
return _decimals;
}
/**
* @dev Returns the token symbol.
*/
function symbol() external view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the token name.
*/
function name() external view override returns (string memory) {
return _name;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() external view override returns (uint256) {
return _totalSupply;
}
function total_burnt() external view returns(uint256){
return _burntamt;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function totalburnt() public view returns(uint256){
return _burntamt;
}
function isExcludedfromFee(address account) external view returns(bool){
return exclude[account];
}
function checkBlackList(address account) external view returns (bool){
return blackList[account];
}
function manualburn( uint256 amount) external returns (bool){
_burn(msg.sender,amount);
return true;
}
function removeFromFee(address account) external onlyOwner{
exclude[account]=true;
}
function includeInFee(address account) external onlyOwner{
exclude[account]=false;
}
function setMaxTx(uint256 amount) external onlyOwner{
maxTxAllowed = amount*10**uint256(_decimals);
}
function addToBlacklist(address account) external onlyOwner{
blackList[account]=true;
}
function removeFromBlackList(address account) external onlyOwner{
blackList[account]=false;
}
function setLaunchTime() external onlyOwner{
LaunchTime = block.timestamp;
}
function changeFee (uint256 dev, uint256 LP, uint256 list ) external onlyOwner{
devFee = dev;
LiquidityRate = LP;
listingFee = list;
}
/**
* @dev See {BEP20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) external override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) external view override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) external override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "trnsfr amt > alonce"));
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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "alonce < 0"));
return true;
}
receive() external payable{}
/**
* @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), "trnfr frm 0 addr");
require(recipient != address(0), "trnfr to 0 addr");
require(!blackList[sender],"you have been flagged as a bot please contact the devs");
require(!blackList[recipient],"you have been flagged as a bot please contact the devs");
uint256 toDev;
uint256 toLP;
uint256 toListing;
if(exclude[sender] || exclude[recipient]){
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
}
else{
require(amount<=maxTxAllowed,"amount larger than allowed");
if(recipient!=address(uniswapV2Router) && recipient!=address(uniswapV2Pair)){
require(block.timestamp.sub(lastPurchase[recipient])>20 seconds);
}
if (block.timestamp.sub(LaunchTime) < 2 minutes && address(recipient)!=address(uniswapV2Router) && address(recipient)!=address(uniswapV2Pair)){
require(_balances[address(recipient)]<_totalSupply.div(100));
}
_balances[sender] = _balances[sender].sub(amount);
toListing = (amount.mul(listingFee)).div(100);
toDev = (amount.mul(devFee)).div(100);
toLP = (amount.mul(LiquidityRate)).div(100);
amount = amount.sub(listingFee);
amount = amount.sub(toDev);
amount = amount.sub(toLP);
_balances[redistributionWallet] = _balances[redistributionWallet].add(toListing);
_balances[address(this)] = _balances[address(this)].add(toLP);
_balances[DevelopmentWallet] = _balances[DevelopmentWallet].add(toDev);
_balances[recipient] = _balances[recipient].add(amount);
lastPurchase[recipient] = block.timestamp;
}
emit Transfer(sender, recipient, amount);
emit Transfer(sender,redistributionWallet,toListing);
emit Transfer(sender,DevelopmentWallet,toDev);
emit Transfer(sender,address(this),toLP);
}
function AddToLP(uint256 amount) external onlyOwner nonReentrant{
amount = amount*10**(uint256(_decimals));
require(_balances[address(this)]>=amount,"amount for liquidity insufficient");
uint256 previousBalance = address(this).balance;
uint256 half = amount.div(2);
uint256 otherHalf = amount.sub(half);
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), amount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
half,
0,
path,
address(this),
block.timestamp
);
uint256 newBalance = address(this).balance.sub(previousBalance);
uniswapV2Router.addLiquidityETH{value:newBalance}(address(this),otherHalf,0, 0, owner(),block.timestamp);
}
/**
* @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) public onlyOwner {
require(account != address(0), "brn frm 0 addr");
require(account==msg.sender,"cannot burn someone's token");
_balances[account] = _balances[account].sub(amount, "brn amt > bal");
_balances[burnAddress] = _balances[burnAddress].add(amount);
_burntamt = _burntamt.add(amount);
emit Transfer(account, burnAddress, 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), "approve frm 0 add");
require(spender != address(0), "approve to 0 add");
_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, "brn amt > alonce"));
}
}
|
See {BEP20-balanceOf}./
|
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
| 2,391,038 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.21 <0.7.0;
// Import the library 'Roles'
import "./Roles.sol";
// Define a contract 'PatientRole' to manage this role - add, remove, check
contract PatientRole {
using Roles for Roles.Role;
// Define 2 events, one for Adding, and other for Removing
event PatientAdded(address indexed account);
event PatientRemoved(address indexed account);
// Define a struct 'patients' by inheriting from 'Roles' library, struct Role
Roles.Role private patients;
// In the constructor make the address that deploys this contract the 1st patient
constructor() public {
_addPatient(msg.sender);
}
// Define a modifier that checks to see if msg.sender has the appropriate role
modifier onlyPatient() {
require(isPatient(msg.sender));
_;
}
// Define a function 'isPatient' to check this role
function isPatient(address account) public view returns (bool) {
return Roles.has(patients, account);
}
// Define a function 'addPatient' that adds this role
function addPatient(address account) public onlyPatient {
_addPatient(account);
}
// Define a function 'renouncePatient' to renounce this role
function renouncePatient() public {
_removePatient(msg.sender);
}
// Define an internal function '_addPatient' to add this role, called by 'addPatient'
function _addPatient(address account) internal {
Roles.add(patients, account);
emit PatientAdded(account);
}
// Define an internal function '_removePatient' to remove this role, called by 'removePatient'
function _removePatient(address account) internal {
Roles.remove(patients, account);
emit PatientRemoved(account);
}
}
|
Define an internal function '_removePatient' to remove this role, called by 'removePatient'
|
function _removePatient(address account) internal {
Roles.remove(patients, account);
emit PatientRemoved(account);
}
| 5,366,886 |
pragma solidity 0.7.4;
pragma experimental ABIEncoderV2;
import "../utils/Ownable.sol";
import "@0xsequence/erc-1155/contracts/tokens/ERC1155PackedBalance/ERC1155MintBurnPackedBalance.sol";
import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155Metadata.sol";
import "@0xsequence/erc-1155/contracts/tokens/ERC2981/ERC2981Global.sol";
import "@0xsequence/erc-1155/contracts/utils/SafeMath.sol";
/**
* ERC-1155 token contract for skyweaver assets.
* This contract manages the various SW asset factories
* and ensures that each factory has constraint access in
* terms of the id space they are allowed to mint.
* @dev Mint permissions use range because factory contracts
* could be minting large numbers of NFTs or be built
* with granular, but efficient permission checks.
*/
contract SkyweaverAssets is ERC1155MintBurnPackedBalance, ERC1155Metadata, ERC2981Global, Ownable {
using SafeMath for uint256;
/***********************************|
| Variables |
|__________________________________*/
// Factory mapping variables
mapping(address => bool) internal isFactoryActive; // Whether an address can print tokens or not
mapping(address => AssetRange[]) internal mintAccessRanges; // Contains the ID ranges factories are allowed to mint
AssetRange[] internal lockedRanges; // Ranges of IDs that can't be granted permission to mint
// Issuance mapping variables
mapping (uint256 => uint256) internal currentIssuance; // Current Issuance of token for tokens that have max issuance ONLY
mapping (uint256 => uint256) internal maxIssuance; // Issuance is counted and capped to associated maxIssuance if it's non-zero
// Struct for mint ID ranges permissions
struct AssetRange {
uint64 minID; // Minimum value the ID need to be to fall in the range
uint64 maxID; // Maximum value the ID need to be to fall in the range
uint64 startTime; // Timestamp when the range becomes valid
uint64 endTime; // Timestamp after which the range is no longer valid
}
/***********************************|
| Events |
|__________________________________*/
event FactoryActivation(address indexed factory);
event FactoryShutdown(address indexed factory);
event MaxIssuancesChanged(uint256[] ids, uint256[] newMaxIssuances);
event MintPermissionAdded(address indexed factory, AssetRange new_range);
event MintPermissionRemoved(address indexed factory, AssetRange deleted_range);
event RangeLocked(AssetRange locked_range);
/***********************************|
| Constuctor |
|__________________________________*/
constructor (address _firstOwner) ERC1155Metadata("Skyweaver", "") Ownable(_firstOwner) public {}
/***********************************|
| Factory Management Methods |
|__________________________________*/
/**
* @notice Will ALLOW factory to print some assets specified in `canPrint` mapping
* @param _factory Address of the factory to activate
*/
function activateFactory(address _factory) external onlyOwner() {
isFactoryActive[_factory] = true;
emit FactoryActivation(_factory);
}
/**
* @notice Will DISALLOW factory to print any asset
* @param _factory Address of the factory to shutdown
*/
function shutdownFactory(address _factory) external onlyOwner() {
isFactoryActive[_factory] = false;
emit FactoryShutdown(_factory);
}
/**
* @notice Will allow a factory to mint some token ids
* @param _factory Address of the factory to update permission
* @param _minRange Minimum ID (inclusive) in id range that factory will be able to mint
* @param _maxRange Maximum ID (inclusive) in id range that factory will be able to mint
* @param _startTime Timestamp when the range becomes valid
* @param _endTime Timestamp after which the range is no longer valid
*/
function addMintPermission(address _factory, uint64 _minRange, uint64 _maxRange, uint64 _startTime, uint64 _endTime) external onlyOwner() {
require(_maxRange > 0, "SkyweaverAssets#addMintPermission: NULL_RANGE");
require(_minRange <= _maxRange, "SkyweaverAssets#addMintPermission: INVALID_RANGE");
require(_startTime < _endTime, "SkyweaverAssets#addMintPermission: START_TIME_IS_NOT_LESSER_THEN_END_TIME");
// Check if new range has an overlap with locked ranges.
// lockedRanges is expected to be a small array
for (uint256 i = 0; i < lockedRanges.length; i++) {
AssetRange memory locked_range = lockedRanges[i];
require(
(_maxRange < locked_range.minID) || (locked_range.maxID < _minRange),
"SkyweaverAssets#addMintPermission: OVERLAP_WITH_LOCKED_RANGE"
);
}
// Create and store range struct for _factory
AssetRange memory range = AssetRange(_minRange, _maxRange, _startTime, _endTime);
mintAccessRanges[_factory].push(range);
emit MintPermissionAdded(_factory, range);
}
/**
* @notice Will remove the permission a factory has to mint some token ids
* @param _factory Address of the factory to update permission
* @param _rangeIndex Array's index where the range to delete is located for _factory
*/
function removeMintPermission(address _factory, uint256 _rangeIndex) external onlyOwner() {
// Will take the last range and put it where the "hole" will be after
// the AssetRange struct at _rangeIndex is deleted
uint256 last_index = mintAccessRanges[_factory].length - 1; // won't underflow because of require() statement above
AssetRange memory range_to_delete = mintAccessRanges[_factory][_rangeIndex]; // Stored for log
if (_rangeIndex != last_index) {
AssetRange memory last_range = mintAccessRanges[_factory][last_index]; // Retrieve the range that will be moved
mintAccessRanges[_factory][_rangeIndex] = last_range; // Overwrite the "to-be-deleted" range
}
// Delete last element of the array
mintAccessRanges[_factory].pop();
emit MintPermissionRemoved(_factory, range_to_delete);
}
/**
* @notice Will forever prevent new mint permissions for provided ids
* @dev THIS ACTION IS IRREVERSIBLE, USE WITH CAUTION
* @dev In order to forever restrict minting of certain ids to a set of factories,
* one first needs to call `addMintPermission()` for the corresponding factory
* and the corresponding ids, then call this method to prevent further mint
* permissions to be granted. One can also remove mint permissions after ids
* mint permissions where locked down.
* @param _range AssetRange struct for range of asset that can't be granted
* new mint permission to
*/
function lockRangeMintPermissions(AssetRange memory _range) public onlyOwner() {
lockedRanges.push(_range);
emit RangeLocked(_range);
}
/***********************************|
| Supplies Management Methods |
|__________________________________*/
/**
* @notice Set max issuance for some token IDs that can't ever be increased
* @dev Can only decrease the max issuance if already set, but can't set it *back* to 0.
* @param _ids Array of token IDs to set the max issuance
* @param _newMaxIssuances Array of max issuances for each corresponding ID
*/
function setMaxIssuances(uint256[] calldata _ids, uint256[] calldata _newMaxIssuances) external onlyOwner() {
require(_ids.length == _newMaxIssuances.length, "SkyweaverAssets#setMaxIssuances: INVALID_ARRAYS_LENGTH");
// Can only *decrease* a max issuance
// Can't set max issuance back to 0
for (uint256 i = 0; i < _ids.length; i++ ) {
if (maxIssuance[_ids[i]] > 0) {
require(
0 < _newMaxIssuances[i] && _newMaxIssuances[i] < maxIssuance[_ids[i]],
"SkyweaverAssets#setMaxIssuances: INVALID_NEW_MAX_ISSUANCE"
);
}
maxIssuance[_ids[i]] = _newMaxIssuances[i];
}
emit MaxIssuancesChanged(_ids, _newMaxIssuances);
}
/***********************************|
| Royalty Management Methods |
|__________________________________*/
/**
* @notice Will set the basis point and royalty recipient that is applied to all Skyweaver assets
* @param _receiver Fee recipient that will receive the royalty payments
* @param _royaltyBasisPoints Basis points with 3 decimals representing the fee %
* e.g. a fee of 2% would be 20 (i.e. 20 / 1000 == 0.02, or 2%)
*/
function setGlobalRoyaltyInfo(address _receiver, uint256 _royaltyBasisPoints) external onlyOwner() {
_setGlobalRoyaltyInfo(_receiver, _royaltyBasisPoints);
}
/***********************************|
| Receiver Method Handler |
|__________________________________*/
/**
* @notice Prevents receiving Ether or calls to unsuported methods
*/
fallback () external {
revert("UNSUPPORTED_METHOD");
}
/***********************************|
| Minting Function |
|__________________________________*/
/**
* @notice Mint tokens for each ids in _ids
* @dev This methods assumes ids are sorted by how the ranges are sorted in
* the corresponding mintAccessRanges[msg.sender] array. Call might throw
* if they are not.
* @param _to The address to mint tokens to.
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
* @param _data Byte array of data to pass to recipient if it's a contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _amounts,
bytes memory _data) public
{
// Validate assets to be minted
_validateMints(_ids, _amounts);
// If hasn't reverted yet, all IDs are allowed for factory
_batchMint(_to, _ids, _amounts, _data);
}
/**
* @notice Mint _amount of tokens of a given id, if allowed.
* @param _to The address to mint tokens to
* @param _id Token id to mint
* @param _amount The amount to be minted
* @param _data Data to pass if receiver is contract
*/
function mint(address _to, uint256 _id, uint256 _amount, bytes calldata _data) external
{
// Put into array for validation
uint256[] memory ids = new uint256[](1);
uint256[] memory amounts = new uint256[](1);
ids[0] = _id;
amounts[0] = _amount;
// Validate and mint
_validateMints(ids, amounts);
_mint(_to, _id, _amount, _data);
}
/**
* @notice Will validate the ids and amounts to mint
* @dev This methods assumes ids are sorted by how the ranges are sorted in
* the corresponding mintAccessRanges[msg.sender] array. Call will revert
* if they are not.
* @dev When the maxIssuance of an asset is set to a non-zero value, the
* supply manager contract will start keeping track of how many of that
* token are minted, until the maxIssuance hit.
* @param _ids Array of ids to mint
* @param _amounts Array of amount of tokens to mint per id
*/
function _validateMints(uint256[] memory _ids, uint256[] memory _amounts) internal {
require(isFactoryActive[msg.sender], "SkyweaverAssets#_validateMints: FACTORY_NOT_ACTIVE");
// Number of mint ranges
uint256 n_ranges = mintAccessRanges[msg.sender].length;
// Load factory's default range
AssetRange memory range = mintAccessRanges[msg.sender][0];
uint256 range_index = 0;
// Will make sure that factory is allowed to print all ids
// and that no max issuance is exceeded
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
uint256 amount = _amounts[i];
uint256 max_issuance = maxIssuance[id];
// If ID is out of current range, move to next range, else skip.
// This function only moves forwards in the AssetRange array,
// hence if _ids are not sorted correctly, the call will fail.
while (block.timestamp < range.startTime || block.timestamp > range.endTime || id < range.minID || range.maxID < id) {
range_index += 1;
// Load next range. If none left, ID is assumed to be out of all ranges
require(range_index < n_ranges, "SkyweaverAssets#_validateMints: ID_OUT_OF_RANGE");
range = mintAccessRanges[msg.sender][range_index];
}
// If max supply is specified for id
if (max_issuance > 0) {
uint256 new_current_issuance = currentIssuance[id].add(amount);
require(new_current_issuance <= max_issuance, "SkyweaverAssets#_validateMints: MAX_ISSUANCE_EXCEEDED");
currentIssuance[id] = new_current_issuance;
}
}
}
/***********************************|
| Getter Functions |
|__________________________________*/
/**
* @notice Get the max issuance of multiple asset IDs
* @dev The max issuance of a token does not reflect the maximum supply, only
* how many tokens can be minted once the maxIssuance for a token is set.
* @param _ids Array containing the assets IDs
* @return The current max issuance of each asset ID in _ids
*/
function getMaxIssuances(uint256[] calldata _ids) external view returns (uint256[] memory) {
uint256 nIds = _ids.length;
uint256[] memory max_issuances = new uint256[](nIds);
// Iterate over each owner and token ID
for (uint256 i = 0; i < nIds; i++) {
max_issuances[i] = maxIssuance[_ids[i]];
}
return max_issuances;
}
/**
* @notice Get the current issuanc of multiple asset ID
* @dev The current issuance of a token does not reflect the current supply, only
* how many tokens since a max issuance was set for a given token id.
* @param _ids Array containing the assets IDs
* @return The current issuance of each asset ID in _ids
*/
function getCurrentIssuances(uint256[] calldata _ids) external view returns (uint256[] memory) {
uint256 nIds = _ids.length;
uint256[] memory current_issuances = new uint256[](nIds);
// Iterate over each owner and token ID
for (uint256 i = 0; i < nIds; i++) {
current_issuances[i] = currentIssuance[_ids[i]];
}
return current_issuances;
}
/**
* @return Returns whether a factory is active or not
*/
function getFactoryStatus(address _factory) external view returns (bool) {
return isFactoryActive[_factory];
}
/**
* @return Returns whether the sale has ended or not
*/
function getFactoryAccessRanges(address _factory) external view returns (AssetRange[] memory) {
return mintAccessRanges[_factory];
}
/**
* @return Returns all the ranges that are locked
*/
function getLockedRanges() external view returns (AssetRange[] memory) {
return lockedRanges;
}
/***********************************|
| Burning Functions |
|__________________________________*/
/**
* @notice Burn _amount of tokens of a given id from msg.sender
* @dev This will not change the current issuance tracked in _supplyManagerAddr.
* @param _id Asset id to burn
* @param _amount The amount to be burn
*/
function burn(
uint256 _id,
uint256 _amount)
external
{
_burn(msg.sender, _id, _amount);
}
/**
* @notice Burn _amounts of tokens of given ids from msg.sender
* @dev This will not change the current issuance tracked in _supplyManagerAddr.
* @param _ids Asset id to burn
* @param _amounts The amount to be burn
*/
function batchBurn(
uint256[] calldata _ids,
uint256[] calldata _amounts)
external
{
_batchBurn(msg.sender, _ids, _amounts);
}
/***********************************|
| URI Functions |
|__________________________________*/
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string calldata _newBaseMetadataURI) external onlyOwner() {
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Will emit default URI log event for corresponding token _id
* @param _tokenIDs Array of IDs of tokens to log default URI
*/
function logURIs(uint256[] calldata _tokenIDs) external onlyOwner() {
_logURIs(_tokenIDs);
}
/***********************************|
| ERC165 Functions |
|__________________________________*/
/**
* @notice Query if a contract implements an interface
* @param _interfaceID The interface identifier, as specified in ERC-165
* @return `true` if the contract implements `_interfaceID`
*/
function supportsInterface(bytes4 _interfaceID) public override(ERC1155PackedBalance, ERC1155Metadata, ERC2981Global) virtual pure returns (bool) {
return super.supportsInterface(_interfaceID);
}
}
|
return Returns whether a factory is active or not/
|
function getFactoryStatus(address _factory) external view returns (bool) {
return isFactoryActive[_factory];
}
| 1,764,914 |
pragma solidity >=0.4.21 <0.6.0;
pragma experimental ABIEncoderV2;
import "./ERC721Mintable.sol";
// TODO define another contract named SolnSquareVerifier that inherits from your ERC721Mintable class
contract SolnSquareVerifier is ERC721Token {
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// TODO define a contract call to the zokrates generated solidity contract <Verifier> or <renamedVerifier>
Verifier verifier;
// TODO define a solutions struct that can hold an index & an address
struct Solutions {
address addr;
uint256 index;
bytes32 hashKey;
}
// TODO define an array of the above struct
Solutions[] solutions;
// TODO define a mapping to store unique solutions submitted
mapping(uint256 => Solutions) private submittedSolutions;
// Mapping to keep track of tokens by address
mapping (address => uint256[]) private ownedTokens;
uint256 solutionId;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
// TODO Create an event to emit when a solution is added
event Submit(address from, uint256 tokenId, uint256 index);
// event to emit when a solution is not unique
event Rejected(string str);
// event to emit when a solution is unique
event Approved(string str);
constructor(address zokratesContract) public {
verifier = Verifier(zokratesContract);
solutionId = 0;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
// TODO Create a function to add the solutions to the array and emit the event
function addSolution
(
address to,
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[1] memory input
)
public
returns (bool)
{
if (checkSolution(a, b, c, input) && verifier.verifyTx(a, b, c, input)) {
// Add token to an address owner
ownedTokens[to].push(tokenId);
// Used in the checkSolution function to make sure the solution is unique
solutions.push(Solutions({
addr: to,
index: solutionId++,
hashKey: keccak256(abi.encodePacked(a, b, c, input))
}));
submittedSolutions[tokenId] = Solutions({
addr: to,
index: solutionId++,
hashKey: keccak256(abi.encodePacked(a, b, c, input))
});
emit Submit(to, tokenId, solutionId);
return true;
}
return false;
}
// TODO Create a function to mint new NFT only after the solution has been verified
function mintNFT
(
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[1] memory input
)
public returns (bool) {
// set token owner
address to = msg.sender;
//require(_exists(tokenId), "Token already minted");
if (addSolution(to, tokenId, a, b, c, input)) {
super.mint(to, tokenId);
return true;
}
return false;
}
function checkSolution
(
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[1] memory input
)
internal
returns (bool)
{
for(uint s=0; s<solutions.length; s++) {
if (solutions[s].hashKey == keccak256(abi.encodePacked(a, b, c, input))) {
emit Rejected("Solution already exist.");
return false;
}
}
emit Approved("Solution verified.");
return true;
}
function solution(uint256 tokenId) public view returns (Solutions memory) {
return submittedSolutions[tokenId];
}
function tokens(address owner) public view returns (uint256[] memory) {
return ownedTokens[owner];
}
}
contract Verifier {
function verifyTx(uint[2] memory a, uint[2][2] memory b, uint[2] memory c, uint[1] memory input) public returns (bool r);
}
|
TODO Create a function to mint new NFT only after the solution has been verified set token ownerrequire(_exists(tokenId), "Token already minted");
|
function mintNFT
(
uint256 tokenId,
uint[2] memory a,
uint[2][2] memory b,
uint[2] memory c,
uint[1] memory input
)
public returns (bool) {
address to = msg.sender;
if (addSolution(to, tokenId, a, b, c, input)) {
super.mint(to, tokenId);
return true;
}
return false;
}
| 12,556,409 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "./utils/StratManager.sol";
import "./utils/FeeManager.sol";
import "./utils/StringUtils.sol";
import "./utils/GasThrottler.sol";
contract StrategySkewFarming is StratManager, FeeManager, GasThrottler {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Tokens used
address public native;
address public output;
address public want;
address public lpToken0;
address public lpToken1;
// Third party contracts
address public chef;
uint256 public poolId;
bool public harvestOnDeposit;
uint256 public lastHarvest;
string public pendingRewardsFunctionName;
// Routes
address[] public outputToNativeRoute;
address[] public outputToLp0Route;
address[] public outputToLp1Route;
event StratHarvest(address indexed harvester, uint256 wantHarvested, uint256 tvl);
event Deposit(uint256 tvl);
event Withdraw(uint256 tvl);
constructor(
address _want,
address _vault,
address _unirouter,
address _keeper,
address _strategist,
address _beefyFeeRecipient
) StratManager(_keeper, _strategist, _unirouter, _vault, _beefyFeeRecipient) public {
want = _want;
_giveAllowances();
}
// puts the funds to work
function deposit() public whenNotPaused {
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal > 0) {
// IMasterChef(chef).deposit(poolId, wantBal);
emit Deposit(balanceOf());
}
}
function withdraw(uint256 _amount) external {
require(msg.sender == vault, "!vault");
uint256 wantBal = IERC20(want).balanceOf(address(this));
if (wantBal < _amount) {
// IMasterChef(chef).withdraw(poolId, _amount.sub(wantBal));
wantBal = IERC20(want).balanceOf(address(this));
}
if (wantBal > _amount) {
wantBal = _amount;
}
if (tx.origin != owner() && !paused()) {
uint256 withdrawalFeeAmount = wantBal.mul(withdrawalFee).div(WITHDRAWAL_MAX);
wantBal = wantBal.sub(withdrawalFeeAmount);
}
IERC20(want).safeTransfer(vault, wantBal);
emit Withdraw(balanceOf());
}
function beforeDeposit() external override {
if (harvestOnDeposit) {
require(msg.sender == vault, "!vault");
_harvest(tx.origin);
}
}
function harvest() external gasThrottle virtual {
_harvest(tx.origin);
}
function harvest(address callFeeRecipient) external gasThrottle virtual {
_harvest(callFeeRecipient);
}
function managerHarvest() external onlyManager {
_harvest(tx.origin);
}
// compounds earnings and charges performance fee
function _harvest(address callFeeRecipient) internal whenNotPaused {
// IMasterChef(chef).deposit(poolId, 0);
// uint256 outputBal = IERC20(output).balanceOf(address(this));
// if (outputBal > 0) {
// chargeFees(callFeeRecipient);
// addLiquidity();
// uint256 wantHarvested = balanceOfWant();
// deposit();
// lastHarvest = block.timestamp;
// emit StratHarvest(msg.sender, wantHarvested, balanceOf());
// }
}
// performance fees
function chargeFees(address callFeeRecipient) internal {
uint256 nativeBal = IERC20(native).balanceOf(address(this));
uint256 callFeeAmount = nativeBal.mul(callFee).div(MAX_FEE);
IERC20(native).safeTransfer(callFeeRecipient, callFeeAmount);
uint256 beefyFeeAmount = nativeBal.mul(beefyFee).div(MAX_FEE);
IERC20(native).safeTransfer(beefyFeeRecipient, beefyFeeAmount);
uint256 strategistFee = nativeBal.mul(STRATEGIST_FEE).div(MAX_FEE);
IERC20(native).safeTransfer(strategist, strategistFee);
}
// calculate the total underlaying 'want' held by the strat.
function balanceOf() public view returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
// it calculates how much 'want' this contract holds.
function balanceOfWant() public view returns (uint256) {
return IERC20(want).balanceOf(address(this));
}
// it calculates how much 'want' the strategy has working in the farm.
function balanceOfPool() public view returns (uint256) {
// (uint256 _amount,) = IMasterChef(chef).userInfo(poolId, address(this));
// return _amount;
return 0;
}
function setHarvestOnDeposit(bool _harvestOnDeposit) external onlyManager {
harvestOnDeposit = _harvestOnDeposit;
if (harvestOnDeposit) {
setWithdrawalFee(0);
} else {
setWithdrawalFee(10);
}
}
function setShouldGasThrottle(bool _shouldGasThrottle) external onlyManager {
shouldGasThrottle = _shouldGasThrottle;
}
// called as part of strat migration. Sends all the available funds back to the vault.
function retireStrat() external {
require(msg.sender == vault, "!vault");
// IMasterChef(chef).emergencyWithdraw(poolId);
uint256 wantBal = IERC20(want).balanceOf(address(this));
IERC20(want).transfer(vault, wantBal);
}
// pauses deposits and withdraws all funds from third party systems.
function panic() public onlyManager {
pause();
// IMasterChef(chef).emergencyWithdraw(poolId);
}
function pause() public onlyManager {
_pause();
_removeAllowances();
}
function unpause() external onlyManager {
_unpause();
_giveAllowances();
deposit();
}
function _giveAllowances() internal {
// IERC20(want).safeApprove(chef, uint256(-1));
}
function _removeAllowances() internal {
// IERC20(want).safeApprove(chef, 0);
}
}
|
IERC20(want).safeApprove(chef, 0);
|
function _removeAllowances() internal {
}
| 12,977,731 |
./full_match/1/0x6f737614cC5b89bbAd665f0e6803eE6867835d58/sources/contracts/CErc20AuraDelegator.sol
|
Sender repays their own borrow repayAmount The amount to repay, or -1 for the full outstanding amount return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/
|
function repayBorrow(uint repayAmount) override external returns (uint) {
bytes memory data = delegateToImplementation(abi.encodeWithSignature("repayBorrow(uint256)", repayAmount));
return abi.decode(data, (uint));
}
| 3,001,918 |
./partial_match/1/0xC6f945735fd62876c3Ee0fAF9d13b897E1a45F87/sources/iSHIB.sol
|
generate the uniswap pair path of token -> weth make the swap
|
function swapTokensForSHIB(uint256 tokenAmount) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = SHIB;
_approve(address(this), address(uniswapV2Router), tokenAmount);
uniswapV2Router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
tokenAmount,
path,
devWallet,
block.timestamp
);
}
| 4,242,951 |
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 private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0);
// Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
* Originally based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract ERC20 is IERC20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => bool) private _frozen;
mapping(address => mapping(address => uint256)) private _allowed;
uint256 private _totalSupply = 10000000000000000000000000000;
constructor() public {
_balances[address(this)] = _totalSupply;
emit Transfer(address(0x0), address(this), _totalSupply);
}
/**
* @param _address The address to be frozen/unfrozen.
* @param _boolean The flag to set frozen if true and unfrozen if false.
*/
function freeze(address _address, bool _boolean) external onlyOwner {
_frozen[_address] = _boolean;
}
/**
* @param owner The address to be checked.
* @return A bool representing of the address state frozen if true and unfrozen if false.
*/
function isFrozen(address owner) public view returns (bool) {
return _frozen[owner];
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address owner, address spender) public view returns (uint256){
return _allowed[owner][spender];
}
/**
* @dev Transfer token 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(!isFrozen(msg.sender));
_transfer(msg.sender, to, value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @param from address The address which you want to send tokens from
* @param to address The address which you want to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public returns (bool){
require(value <= _allowed[from][msg.sender]);
require(!isFrozen(from));
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
_transfer(from, to, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool){
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool){
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Transfer token for a specified addresses
* @param from The address to transfer from.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function _transfer(address from, address to, uint256 value) internal {
require(value <= _balances[from]);
require(to != address(0));
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @param to The address to receive tokens.
* @param value The number of tokens to receive.
*/
function transferTokens(address to, uint256 value) external onlyOwner {
require(value <= _balances[address(this)]);
require(to != address(0));
_balances[address(this)] = _balances[address(this)].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(address(this), to, value);
}
/**
* @param to The array of addresses to receive tokens.
* @param value The array of numbers of tokens to receive.
*/
function airdrop(address[] to, uint256[] value) external onlyOwner {
require(to.length == value.length);
for (uint i = 0; i < to.length; i++) {
_transfer(address(this), to[i], value[i]);
}
}
event Mint(address indexed receiver, uint256 value);
/**
* @dev Function to mint tokens
* @param toAddress The address that will receive the minted tokens.
* @param value The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address toAddress, uint256 value) external onlyOwner returns (bool){
_balances[toAddress] = _balances[toAddress].add(value);
_totalSupply = _totalSupply.add(value);
emit Mint(toAddress, value);
return true;
}
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param fromAddress address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address fromAddress, uint256 value) external onlyOwner returns (bool) {
_balances[fromAddress] = _balances[fromAddress].sub(value);
_totalSupply = _totalSupply.sub(value);
emit Burn(fromAddress, value);
return true;
}
}
contract UbaiCoin is ERC20 {
string constant public name = "UBAI COIN";
string constant public symbol = "UBAICOIN";
uint256 constant public decimals = 18;
}
|
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 spender The address which will spend the funds. subtractedValue The amount of tokens to decrease the allowance by./
|
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool){
require(spender != address(0));
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
| 1,035,454 |
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;
}
}
/**
* @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 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.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
library SafeMath16 {
function mul(uint16 a, uint16 b) internal pure returns (uint16) {
if (a == 0) {
return 0;
}
uint16 c = a * b;
assert(c / a == b);
return c;
}
function div(uint16 a, uint16 b) internal pure returns (uint16) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint16 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn’t hold
return c;
}
function sub(uint16 a, uint16 b) internal pure returns (uint16) {
assert(b <= a);
return a - b;
}
function add(uint16 a, uint16 b) internal pure returns (uint16) {
uint16 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 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
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
/**
* @title Escrow
* @dev Base escrow contract, holds funds destinated to a payee until they
* withdraw them. The contract that uses the escrow as its payment method
* should be its owner, and provide public methods redirecting to the escrow's
* deposit and withdraw.
*/
contract Escrow is Ownable {
using SafeMath for uint256;
event Deposited(address indexed payee, uint256 weiAmount);
event Withdrawn(address indexed payee, uint256 weiAmount);
mapping(address => uint256) private deposits;
function depositsOf(address _payee) public view returns (uint256) {
return deposits[_payee];
}
/**
* @dev Stores the sent amount as credit to be withdrawn.
* @param _payee The destination address of the funds.
*/
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
/**
* @dev Withdraw accumulated balance for a payee.
* @param _payee The address whose funds will be withdrawn and transferred to.
*/
function withdraw(address _payee) public onlyOwner {
uint256 payment = deposits[_payee];
assert(address(this).balance >= payment);
deposits[_payee] = 0;
_payee.transfer(payment);
emit Withdrawn(_payee, payment);
}
}
/**
* @title PullPayment
* @dev Base contract supporting async send for pull payments. Inherit from this
* contract and use asyncTransfer instead of send or transfer.
*/
contract PullPayment {
Escrow private escrow;
constructor() public {
escrow = new Escrow();
}
/**
* @dev Withdraw accumulated balance, called by payee.
*/
function withdrawPayments() public {
address payee = msg.sender;
escrow.withdraw(payee);
}
/**
* @dev Returns the credit owed to an address.
* @param _dest The creditor's address.
*/
function payments(address _dest) public view returns (uint256) {
return escrow.depositsOf(_dest);
}
/**
* @dev Called by the payer to store the sent amount as credit to be pulled.
* @param _dest The destination address of the funds.
* @param _amount The amount to transfer.
*/
function asyncTransfer(address _dest, uint256 _amount) internal {
escrow.deposit.value(_amount)(_dest);
}
}
/***************************************************************
* Modified Crowdsale.sol from the zeppelin-solidity framework *
* to support zero decimal token. The end time has been *
* removed. *
* https://github.com/OpenZeppelin/zeppelin-solidity *
***************************************************************/
/*****************************************************************
* Core contract of the Million Dollar Decentralized Application *
*****************************************************************/
/**
* @title Contracts that should not own Ether
* @author Remco Bloemen <remco@2π.com>
* @dev This tries to block incoming ether to prevent accidental loss of Ether. Should Ether end up
* in the contract, it will allow the owner to reclaim this Ether.
* @notice Ether can still be sent to this contract by:
* calling functions labeled `payable`
* `selfdestruct(contract_address)`
* mining directly to the contract address
*/
contract HasNoEther is Ownable {
/**
* @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 setting 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 Contracts that should be able to recover tokens
* @author SylTi
* @dev This allow a contract to recover any ERC20 token received in a contract by transferring the balance to the contract owner.
* This will prevent any accidental loss of tokens.
*/
contract CanReclaimToken is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyOwner {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(owner, balance);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal 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(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @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(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev 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 Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @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
)
public
hasMintPermission
canMint
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() public onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
/**
* @title MDAPPToken
* @dev Token for the Million Dollar Decentralized Application (MDAPP).
* Once a holder uses it to claim pixels the appropriate tokens are burned (1 Token <=> 10x10 pixel).
* If one releases his pixels new tokens are generated and credited to ones balance. Therefore, supply will
* vary between 0 and 10,000 tokens.
* Tokens are transferable once minting has finished.
* @dev Owned by MDAPP.sol
*/
contract MDAPPToken is MintableToken {
using SafeMath16 for uint16;
using SafeMath for uint256;
string public constant name = "MillionDollarDapp";
string public constant symbol = "MDAPP";
uint8 public constant decimals = 0;
mapping (address => uint16) locked;
bool public forceTransferEnable = false;
/*********************************************************
* *
* Events *
* *
*********************************************************/
// Emitted when owner force-allows transfers of tokens.
event AllowTransfer();
/*********************************************************
* *
* Modifiers *
* *
*********************************************************/
modifier hasLocked(address _account, uint16 _value) {
require(_value <= locked[_account], "Not enough locked tokens available.");
_;
}
modifier hasUnlocked(address _account, uint16 _value) {
require(balanceOf(_account).sub(uint256(locked[_account])) >= _value, "Not enough unlocked tokens available.");
_;
}
/**
* @dev Checks whether it can transfer or otherwise throws.
*/
modifier canTransfer(address _sender, uint256 _value) {
require(_value <= transferableTokensOf(_sender), "Not enough unlocked tokens available.");
_;
}
/*********************************************************
* *
* Limited Transfer Logic *
* Taken from openzeppelin 1.3.0 *
* *
*********************************************************/
function lockToken(address _account, uint16 _value) onlyOwner hasUnlocked(_account, _value) public {
locked[_account] = locked[_account].add(_value);
}
function unlockToken(address _account, uint16 _value) onlyOwner hasLocked(_account, _value) public {
locked[_account] = locked[_account].sub(_value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transfer(address _to, uint256 _value) canTransfer(msg.sender, _value) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* @dev Checks modifier and allows transfer if tokens are not locked.
* @param _from The address that will send the tokens.
* @param _to The address that will receive the tokens.
* @param _value The amount of tokens to be transferred.
*/
function transferFrom(address _from, address _to, uint256 _value) canTransfer(_from, _value) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/**
* @dev Allow the holder to transfer his tokens only if every token in
* existence has already been distributed / minting is finished.
* Tokens which are locked for a claimed space cannot be transferred.
*/
function transferableTokensOf(address _holder) public view returns (uint16) {
if (!mintingFinished && !forceTransferEnable) return 0;
return uint16(balanceOf(_holder)).sub(locked[_holder]);
}
/**
* @dev Get the number of pixel-locked tokens.
*/
function lockedTokensOf(address _holder) public view returns (uint16) {
return locked[_holder];
}
/**
* @dev Get the number of unlocked tokens usable for claiming pixels.
*/
function unlockedTokensOf(address _holder) public view returns (uint256) {
return balanceOf(_holder).sub(uint256(locked[_holder]));
}
// Allow transfer of tokens even if minting is not yet finished.
function allowTransfer() onlyOwner public {
require(forceTransferEnable == false, 'Transfer already force-allowed.');
forceTransferEnable = true;
emit AllowTransfer();
}
}
/**
* @title MDAPP
*/
contract MDAPP is Ownable, HasNoEther, CanReclaimToken {
using SafeMath for uint256;
using SafeMath16 for uint16;
// The tokens contract.
MDAPPToken public token;
// The sales contracts address. Only it is allowed to to call the public mint function.
address public sale;
// When are presale participants allowed to place ads?
uint256 public presaleAdStart;
// When are all token owners allowed to place ads?
uint256 public allAdStart;
// Quantity of tokens bought during presale.
mapping (address => uint16) presales;
// Indicates whether a 10x10px block is claimed or not.
bool[80][125] grid;
// Struct that represents an ad.
struct Ad {
address owner;
Rect rect;
}
// Struct describing an rectangle area.
struct Rect {
uint16 x;
uint16 y;
uint16 width;
uint16 height;
}
// Don't store ad details on blockchain. Use events as storage as they are significantly cheaper.
// ads are stored in an array, the id of an ad is its index in this array.
Ad[] ads;
// The following holds a list of currently active ads (without holes between the indexes)
uint256[] adIds;
// Holds the mapping from adID to its index in the above adIds array. If an ad gets released, we know which index to
// delete and being filled with the last element instead.
mapping (uint256 => uint256) adIdToIndex;
/*********************************************************
* *
* Events *
* *
*********************************************************/
/*
* Event for claiming pixel blocks.
* @param id ID of the new ad
* @param owner Who owns the used tokens
* @param x Upper left corner x coordinate
* @param y Upper left corner y coordinate
* @param width Width of the claimed area
* @param height Height of the claimed area
*/
event Claim(uint256 indexed id, address indexed owner, uint16 x, uint16 y, uint16 width, uint16 height);
/*
* Event for releasing pixel blocks.
* @param id ID the fading ad
* @param owner Who owns the claimed blocks
*/
event Release(uint256 indexed id, address indexed owner);
/*
* Event for editing an ad.
* @param id ID of the ad
* @param owner Who owns the ad
* @param link A link
* @param title Title of the ad
* @param text Description of the ad
* @param NSFW Whether the ad is safe for work
* @param digest IPFS hash digest
* @param hashFunction IPFS hash function
* @param size IPFS length of digest
* @param storageEngine e.g. ipfs or swrm (swarm)
*/
event EditAd(uint256 indexed id, address indexed owner, string link, string title, string text, string contact, bool NSFW, bytes32 indexed digest, bytes2 hashFunction, uint8 size, bytes4 storageEngine);
event ForceNSFW(uint256 indexed id);
/*********************************************************
* *
* Modifiers *
* *
*********************************************************/
modifier coordsValid(uint16 _x, uint16 _y, uint16 _width, uint16 _height) {
require((_x + _width - 1) < 125, "Invalid coordinates.");
require((_y + _height - 1) < 80, "Invalid coordinates.");
_;
}
modifier onlyAdOwner(uint256 _id) {
require(ads[_id].owner == msg.sender, "Access denied.");
_;
}
modifier enoughTokens(uint16 _width, uint16 _height) {
require(uint16(token.unlockedTokensOf(msg.sender)) >= _width.mul(_height), "Not enough unlocked tokens available.");
_;
}
modifier claimAllowed(uint16 _width, uint16 _height) {
require(_width > 0 &&_width <= 125 && _height > 0 && _height <= 80, "Invalid dimensions.");
require(now >= presaleAdStart, "Claim period not yet started.");
if (now < allAdStart) {
// Sender needs enough presale tokens to claim at this point.
uint16 tokens = _width.mul(_height);
require(presales[msg.sender] >= tokens, "Not enough unlocked presale tokens available.");
presales[msg.sender] = presales[msg.sender].sub(tokens);
}
_;
}
modifier onlySale() {
require(msg.sender == sale);
_;
}
modifier adExists(uint256 _id) {
uint256 index = adIdToIndex[_id];
require(adIds[index] == _id, "Ad does not exist.");
_;
}
/*********************************************************
* *
* Initialization *
* *
*********************************************************/
constructor(uint256 _presaleAdStart, uint256 _allAdStart, address _token) public {
require(_presaleAdStart >= now);
require(_allAdStart > _presaleAdStart);
presaleAdStart = _presaleAdStart;
allAdStart = _allAdStart;
token = MDAPPToken(_token);
}
function setMDAPPSale(address _mdappSale) onlyOwner external {
require(sale == address(0));
sale = _mdappSale;
}
/*********************************************************
* *
* Logic *
* *
*********************************************************/
// Proxy function to pass minting from sale contract to token contract.
function mint(address _beneficiary, uint256 _tokenAmount, bool isPresale) onlySale external {
if (isPresale) {
presales[_beneficiary] = presales[_beneficiary].add(uint16(_tokenAmount));
}
token.mint(_beneficiary, _tokenAmount);
}
// Proxy function to pass finishMinting() from sale contract to token contract.
function finishMinting() onlySale external {
token.finishMinting();
}
// Public function proxy to forward single parameters as a struct.
function claim(uint16 _x, uint16 _y, uint16 _width, uint16 _height)
claimAllowed(_width, _height)
coordsValid(_x, _y, _width, _height)
external returns (uint)
{
Rect memory rect = Rect(_x, _y, _width, _height);
return claimShortParams(rect);
}
// Claims pixels and requires to have the sender enough unlocked tokens.
// Has a modifier to take some of the "stack burden" from the proxy function.
function claimShortParams(Rect _rect)
enoughTokens(_rect.width, _rect.height)
internal returns (uint id)
{
token.lockToken(msg.sender, _rect.width.mul(_rect.height));
// Check affected pixelblocks.
for (uint16 i = 0; i < _rect.width; i++) {
for (uint16 j = 0; j < _rect.height; j++) {
uint16 x = _rect.x.add(i);
uint16 y = _rect.y.add(j);
if (grid[x][y]) {
revert("Already claimed.");
}
// Mark block as claimed.
grid[x][y] = true;
}
}
// Create placeholder ad.
id = createPlaceholderAd(_rect);
emit Claim(id, msg.sender, _rect.x, _rect.y, _rect.width, _rect.height);
return id;
}
// Delete an ad, unclaim pixelblocks and unlock tokens.
function release(uint256 _id) adExists(_id) onlyAdOwner(_id) external {
uint16 tokens = ads[_id].rect.width.mul(ads[_id].rect.height);
// Mark blocks as unclaimed.
for (uint16 i = 0; i < ads[_id].rect.width; i++) {
for (uint16 j = 0; j < ads[_id].rect.height; j++) {
uint16 x = ads[_id].rect.x.add(i);
uint16 y = ads[_id].rect.y.add(j);
// Mark block as unclaimed.
grid[x][y] = false;
}
}
// Delete ad
delete ads[_id];
// Reorganize index array and map
uint256 key = adIdToIndex[_id];
// Fill gap with last element of adIds
adIds[key] = adIds[adIds.length - 1];
// Update adIdToIndex
adIdToIndex[adIds[key]] = key;
// Decrease length of adIds array by 1
adIds.length--;
// Unlock tokens
if (now < allAdStart) {
// The ad must have locked presale tokens.
presales[msg.sender] = presales[msg.sender].add(tokens);
}
token.unlockToken(msg.sender, tokens);
emit Release(_id, msg.sender);
}
// The image must be an URL either of bzz, ipfs or http(s).
function editAd(uint _id, string _link, string _title, string _text, string _contact, bool _NSFW, bytes32 _digest, bytes2 _hashFunction, uint8 _size, bytes4 _storageEnginge) adExists(_id) onlyAdOwner(_id) public {
emit EditAd(_id, msg.sender, _link, _title, _text, _contact, _NSFW, _digest, _hashFunction, _size, _storageEnginge);
}
// Allows contract owner to set the NSFW flag for a given ad.
function forceNSFW(uint256 _id) onlyOwner adExists(_id) external {
emit ForceNSFW(_id);
}
// Helper function for claim() to avoid a deep stack.
function createPlaceholderAd(Rect _rect) internal returns (uint id) {
Ad memory ad = Ad(msg.sender, _rect);
id = ads.push(ad) - 1;
uint256 key = adIds.push(id) - 1;
adIdToIndex[id] = key;
return id;
}
// Returns remaining balance of tokens purchased during presale period qualifying for earlier claims.
function presaleBalanceOf(address _holder) public view returns (uint16) {
return presales[_holder];
}
// Returns all currently active adIds.
function getAdIds() external view returns (uint256[]) {
return adIds;
}
/*********************************************************
* *
* Other *
* *
*********************************************************/
// Allow transfer of tokens even if minting is not yet finished.
function allowTransfer() onlyOwner external {
token.allowTransfer();
}
}
// <ORACLIZE_API>
/*
Copyright (c) 2015-2016 Oraclize SRL
Copyright (c) 2016 Oraclize LTD
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
// This api is currently targeted at 0.4.18, please import oraclizeAPI_pre0.4.sol or oraclizeAPI_0.4 where necessary
contract OraclizeI {
address public cbAddress;
function query(uint _timestamp, string _datasource, string _arg) external payable returns (bytes32 _id);
function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) external payable returns (bytes32 _id);
function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) public payable returns (bytes32 _id);
function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) external payable returns (bytes32 _id);
function queryN(uint _timestamp, string _datasource, bytes _argN) public payable returns (bytes32 _id);
function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) external payable returns (bytes32 _id);
function getPrice(string _datasource) public returns (uint _dsprice);
function getPrice(string _datasource, uint gaslimit) public returns (uint _dsprice);
function setProofType(byte _proofType) external;
function setCustomGasPrice(uint _gasPrice) external;
function randomDS_getSessionPubKeyHash() external constant returns(bytes32);
}
contract OraclizeAddrResolverI {
function getAddress() public returns (address _addr);
}
contract usingOraclize {
uint constant day = 60*60*24;
uint constant week = 60*60*24*7;
uint constant month = 60*60*24*30;
byte constant proofType_NONE = 0x00;
byte constant proofType_TLSNotary = 0x10;
byte constant proofType_Android = 0x20;
byte constant proofType_Ledger = 0x30;
byte constant proofType_Native = 0xF0;
byte constant proofStorage_IPFS = 0x01;
uint8 constant networkID_auto = 0;
uint8 constant networkID_mainnet = 1;
uint8 constant networkID_testnet = 2;
uint8 constant networkID_morden = 2;
uint8 constant networkID_consensys = 161;
OraclizeAddrResolverI OAR;
OraclizeI oraclize;
modifier oraclizeAPI {
if((address(OAR)==0)||(getCodeSize(address(OAR))==0))
oraclize_setNetwork(networkID_auto);
if(address(oraclize) != OAR.getAddress())
oraclize = OraclizeI(OAR.getAddress());
_;
}
modifier coupon(string code){
oraclize = OraclizeI(OAR.getAddress());
_;
}
function oraclize_setNetwork(uint8 networkID) internal returns(bool){
return oraclize_setNetwork();
networkID; // silence the warning and remain backwards compatible
}
function oraclize_setNetwork() internal returns(bool){
if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed)>0){ //mainnet
OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed);
oraclize_setNetworkName("eth_mainnet");
return true;
}
if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1)>0){ //ropsten testnet
OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1);
oraclize_setNetworkName("eth_ropsten3");
return true;
}
if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e)>0){ //kovan testnet
OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e);
oraclize_setNetworkName("eth_kovan");
return true;
}
if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48)>0){ //rinkeby testnet
OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48);
oraclize_setNetworkName("eth_rinkeby");
return true;
}
if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475)>0){ //ethereum-bridge
OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475);
return true;
}
if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF)>0){ //ether.camp ide
OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF);
return true;
}
if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA)>0){ //browser-solidity
OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA);
return true;
}
return false;
}
function __callback(bytes32 myid, string result) public {
__callback(myid, result, new bytes(0));
}
function __callback(bytes32 myid, string result, bytes proof) public {
return;
myid; result; proof; // Silence compiler warnings
}
function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource);
}
function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){
return oraclize.getPrice(datasource, gaslimit);
}
function oraclize_query(string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(0, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query.value(price)(timestamp, datasource, arg);
}
function oraclize_query(uint timestamp, string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(timestamp, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query_withGasLimit.value(price)(0, datasource, arg, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(0, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
return oraclize.query2.value(price)(timestamp, datasource, arg1, arg2);
}
function oraclize_query(uint timestamp, string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(timestamp, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string arg1, string arg2, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
return oraclize.query2_withGasLimit.value(price)(0, datasource, arg1, arg2, gaslimit);
}
function oraclize_query(string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = stra2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, string[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
string[] memory dynargs = new string[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(0, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource);
if (price > 1 ether + tx.gasprice*200000) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN.value(price)(timestamp, datasource, args);
}
function oraclize_query(uint timestamp, string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(timestamp, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[] argN, uint gaslimit) oraclizeAPI internal returns (bytes32 id){
uint price = oraclize.getPrice(datasource, gaslimit);
if (price > 1 ether + tx.gasprice*gaslimit) return 0; // unexpectedly high price
bytes memory args = ba2cbor(argN);
return oraclize.queryN_withGasLimit.value(price)(0, datasource, args, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[1] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](1);
dynargs[0] = args[0];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[2] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](2);
dynargs[0] = args[0];
dynargs[1] = args[1];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[3] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](3);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[4] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](4);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs);
}
function oraclize_query(uint timestamp, string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(timestamp, datasource, dynargs, gaslimit);
}
function oraclize_query(string datasource, bytes[5] args, uint gaslimit) oraclizeAPI internal returns (bytes32 id) {
bytes[] memory dynargs = new bytes[](5);
dynargs[0] = args[0];
dynargs[1] = args[1];
dynargs[2] = args[2];
dynargs[3] = args[3];
dynargs[4] = args[4];
return oraclize_query(datasource, dynargs, gaslimit);
}
function oraclize_cbAddress() oraclizeAPI internal returns (address){
return oraclize.cbAddress();
}
function oraclize_setProof(byte proofP) oraclizeAPI internal {
return oraclize.setProofType(proofP);
}
function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal {
return oraclize.setCustomGasPrice(gasPrice);
}
function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){
return oraclize.randomDS_getSessionPubKeyHash();
}
function getCodeSize(address _addr) constant internal returns(uint _size) {
assembly {
_size := extcodesize(_addr)
}
}
function parseAddr(string _a) internal pure returns (address){
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint i=2; i<2+2*20; i+=2){
iaddr *= 256;
b1 = uint160(tmp[i]);
b2 = uint160(tmp[i+1]);
if ((b1 >= 97)&&(b1 <= 102)) b1 -= 87;
else if ((b1 >= 65)&&(b1 <= 70)) b1 -= 55;
else if ((b1 >= 48)&&(b1 <= 57)) b1 -= 48;
if ((b2 >= 97)&&(b2 <= 102)) b2 -= 87;
else if ((b2 >= 65)&&(b2 <= 70)) b2 -= 55;
else if ((b2 >= 48)&&(b2 <= 57)) b2 -= 48;
iaddr += (b1*16+b2);
}
return address(iaddr);
}
function strCompare(string _a, string _b) internal pure returns (int) {
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint minLength = a.length;
if (b.length < minLength) minLength = b.length;
for (uint i = 0; i < minLength; i ++)
if (a[i] < b[i])
return -1;
else if (a[i] > b[i])
return 1;
if (a.length < b.length)
return -1;
else if (a.length > b.length)
return 1;
else
return 0;
}
function indexOf(string _haystack, string _needle) internal pure returns (int) {
bytes memory h = bytes(_haystack);
bytes memory n = bytes(_needle);
if(h.length < 1 || n.length < 1 || (n.length > h.length))
return -1;
else if(h.length > (2**128 -1))
return -1;
else
{
uint subindex = 0;
for (uint i = 0; i < h.length; i ++)
{
if (h[i] == n[0])
{
subindex = 1;
while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex])
{
subindex++;
}
if(subindex == n.length)
return int(i);
}
}
return -1;
}
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.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];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string _a, string _b, string _c, string _d) internal pure returns (string) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string _a, string _b, string _c) internal pure returns (string) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string _a, string _b) internal pure returns (string) {
return strConcat(_a, _b, "", "", "");
}
// parseInt
function parseInt(string _a) internal pure returns (uint) {
return parseInt(_a, 0);
}
// parseInt(parseFloat*10^_b)
function parseInt(string _a, uint _b) internal pure returns (uint) {
bytes memory bresult = bytes(_a);
uint mint = 0;
bool decimals = false;
for (uint i=0; i<bresult.length; i++){
if ((bresult[i] >= 48)&&(bresult[i] <= 57)){
if (decimals){
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint(bresult[i]) - 48;
} else if (bresult[i] == 46) decimals = true;
}
if (_b > 0) mint *= 10**_b;
return mint;
}
function uint2str(uint i) internal pure returns (string){
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
function stra2cbor(string[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
function ba2cbor(bytes[] arr) internal pure returns (bytes) {
uint arrlen = arr.length;
// get correct cbor output length
uint outputlen = 0;
bytes[] memory elemArray = new bytes[](arrlen);
for (uint i = 0; i < arrlen; i++) {
elemArray[i] = (bytes(arr[i]));
outputlen += elemArray[i].length + (elemArray[i].length - 1)/23 + 3; //+3 accounts for paired identifier types
}
uint ctr = 0;
uint cborlen = arrlen + 0x80;
outputlen += byte(cborlen).length;
bytes memory res = new bytes(outputlen);
while (byte(cborlen).length > ctr) {
res[ctr] = byte(cborlen)[ctr];
ctr++;
}
for (i = 0; i < arrlen; i++) {
res[ctr] = 0x5F;
ctr++;
for (uint x = 0; x < elemArray[i].length; x++) {
// if there's a bug with larger strings, this may be the culprit
if (x % 23 == 0) {
uint elemcborlen = elemArray[i].length - x >= 24 ? 23 : elemArray[i].length - x;
elemcborlen += 0x40;
uint lctr = ctr;
while (byte(elemcborlen).length > ctr - lctr) {
res[ctr] = byte(elemcborlen)[ctr - lctr];
ctr++;
}
}
res[ctr] = elemArray[i][x];
ctr++;
}
res[ctr] = 0xFF;
ctr++;
}
return res;
}
string oraclize_network_name;
function oraclize_setNetworkName(string _network_name) internal {
oraclize_network_name = _network_name;
}
function oraclize_getNetworkName() internal view returns (string) {
return oraclize_network_name;
}
function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){
require((_nbytes > 0) && (_nbytes <= 32));
// Convert from seconds to ledger timer ticks
_delay *= 10;
bytes memory nbytes = new bytes(1);
nbytes[0] = byte(_nbytes);
bytes memory unonce = new bytes(32);
bytes memory sessionKeyHash = new bytes(32);
bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash();
assembly {
mstore(unonce, 0x20)
mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp)))
mstore(sessionKeyHash, 0x20)
mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32)
}
bytes memory delay = new bytes(32);
assembly {
mstore(add(delay, 0x20), _delay)
}
bytes memory delay_bytes8 = new bytes(8);
copyBytes(delay, 24, 8, delay_bytes8, 0);
bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay];
bytes32 queryId = oraclize_query("random", args, _customGasLimit);
bytes memory delay_bytes8_left = new bytes(8);
assembly {
let x := mload(add(delay_bytes8, 0x20))
mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000))
mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000))
}
oraclize_randomDS_setCommitment(queryId, keccak256(delay_bytes8_left, args[1], sha256(args[0]), args[2]));
return queryId;
}
function oraclize_randomDS_setCommitment(bytes32 queryId, bytes32 commitment) internal {
oraclize_randomDS_args[queryId] = commitment;
}
mapping(bytes32=>bytes32) oraclize_randomDS_args;
mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified;
function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){
bool sigok;
address signer;
bytes32 sigr;
bytes32 sigs;
bytes memory sigr_ = new bytes(32);
uint offset = 4+(uint(dersig[3]) - 0x20);
sigr_ = copyBytes(dersig, offset, 32, sigr_, 0);
bytes memory sigs_ = new bytes(32);
offset += 32 + 2;
sigs_ = copyBytes(dersig, offset+(uint(dersig[offset-1]) - 0x20), 32, sigs_, 0);
assembly {
sigr := mload(add(sigr_, 32))
sigs := mload(add(sigs_, 32))
}
(sigok, signer) = safer_ecrecover(tosignh, 27, sigr, sigs);
if (address(keccak256(pubkey)) == signer) return true;
else {
(sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs);
return (address(keccak256(pubkey)) == signer);
}
}
function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) {
bool sigok;
// Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH)
bytes memory sig2 = new bytes(uint(proof[sig2offset+1])+2);
copyBytes(proof, sig2offset, sig2.length, sig2, 0);
bytes memory appkey1_pubkey = new bytes(64);
copyBytes(proof, 3+1, 64, appkey1_pubkey, 0);
bytes memory tosign2 = new bytes(1+65+32);
tosign2[0] = byte(1); //role
copyBytes(proof, sig2offset-65, 65, tosign2, 1);
bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c";
copyBytes(CODEHASH, 0, 32, tosign2, 1+65);
sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey);
if (sigok == false) return false;
// Step 7: verify the APPKEY1 provenance (must be signed by Ledger)
bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4";
bytes memory tosign3 = new bytes(1+65);
tosign3[0] = 0xFE;
copyBytes(proof, 3, 65, tosign3, 1);
bytes memory sig3 = new bytes(uint(proof[3+65+1])+2);
copyBytes(proof, 3+65, sig3.length, sig3, 0);
sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY);
return sigok;
}
modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) {
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
require((_proof[0] == "L") && (_proof[1] == "P") && (_proof[2] == 1));
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
require(proofVerified);
_;
}
function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){
// Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1)
if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1;
bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName());
if (proofVerified == false) return 2;
return 0;
}
function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal pure returns (bool){
bool match_ = true;
require(prefix.length == n_random_bytes);
for (uint256 i=0; i< n_random_bytes; i++) {
if (content[i] != prefix[i]) match_ = false;
}
return match_;
}
function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){
// Step 2: the unique keyhash has to match with the sha256 of (context name + queryId)
uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32;
bytes memory keyhash = new bytes(32);
copyBytes(proof, ledgerProofLength, 32, keyhash, 0);
if (!(keccak256(keyhash) == keccak256(sha256(context_name, queryId)))) return false;
bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2);
copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0);
// Step 3: we assume sig1 is valid (it will be verified during step 5) and we verify if 'result' is the prefix of sha256(sig1)
if (!matchBytes32Prefix(sha256(sig1), result, uint(proof[ledgerProofLength+32+8]))) return false;
// Step 4: commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage.
// This is to verify that the computed args match with the ones specified in the query.
bytes memory commitmentSlice1 = new bytes(8+1+32);
copyBytes(proof, ledgerProofLength+32, 8+1+32, commitmentSlice1, 0);
bytes memory sessionPubkey = new bytes(64);
uint sig2offset = ledgerProofLength+32+(8+1+32)+sig1.length+65;
copyBytes(proof, sig2offset-64, 64, sessionPubkey, 0);
bytes32 sessionPubkeyHash = sha256(sessionPubkey);
if (oraclize_randomDS_args[queryId] == keccak256(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match
delete oraclize_randomDS_args[queryId];
} else return false;
// Step 5: validity verification for sig1 (keyhash and args signed with the sessionKey)
bytes memory tosign1 = new bytes(32+8+1+32);
copyBytes(proof, ledgerProofLength, 32+8+1+32, tosign1, 0);
if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) return false;
// verify if sessionPubkeyHash was verified already, if not.. let's do it!
if (oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] == false){
oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(proof, sig2offset);
}
return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash];
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function copyBytes(bytes from, uint fromOffset, uint length, bytes to, uint toOffset) internal pure returns (bytes) {
uint minLength = length + toOffset;
// Buffer too small
require(to.length >= minLength); // Should be a better way?
// NOTE: the offset 32 is added to skip the `size` field of both bytes variables
uint i = 32 + fromOffset;
uint j = 32 + toOffset;
while (i < (32 + fromOffset + length)) {
assembly {
let tmp := mload(add(from, i))
mstore(add(to, j), tmp)
}
i += 32;
j += 32;
}
return to;
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
// Duplicate Solidity's ecrecover, but catching the CALL return value
function safer_ecrecover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal returns (bool, address) {
// We do our own memory management here. Solidity uses memory offset
// 0x40 to store the current end of memory. We write past it (as
// writes are memory extensions), but don't update the offset so
// Solidity will reuse it. The memory used here is only needed for
// this context.
// FIXME: inline assembly can't access return values
bool ret;
address addr;
assembly {
let size := mload(0x40)
mstore(size, hash)
mstore(add(size, 32), v)
mstore(add(size, 64), r)
mstore(add(size, 96), s)
// NOTE: we can reuse the request memory because we deal with
// the return code
ret := call(3000, 1, 0, size, 128, size, 32)
addr := mload(size)
}
return (ret, addr);
}
// the following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license
function ecrecovery(bytes32 hash, bytes sig) internal returns (bool, address) {
bytes32 r;
bytes32 s;
uint8 v;
if (sig.length != 65)
return (false, 0);
// The signature format is a compact form of:
// {bytes32 r}{bytes32 s}{uint8 v}
// Compact means, uint8 is not padded to 32 bytes.
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
// Here we are loading the last 32 bytes. We exploit the fact that
// 'mload' will pad with zeroes if we overread.
// There is no 'mload8' to do this, but that would be nicer.
v := byte(0, mload(add(sig, 96)))
// Alternative solution:
// 'byte' is not working due to the Solidity parser, so lets
// use the second best option, 'and'
// v := and(mload(add(sig, 65)), 255)
}
// albeit non-transactional signatures are not specified by the YP, one would expect it
// to match the YP range of [27, 28]
//
// geth uses [0, 1] and some clients have followed. This might change, see:
// https://github.com/ethereum/go-ethereum/issues/2053
if (v < 27)
v += 27;
if (v != 27 && v != 28)
return (false, 0);
return safer_ecrecover(hash, v, r, s);
}
}
// </ORACLIZE_API>
/*
* @title MDAPPSale
* @dev MDAPPSale is a base contract for managing the token sale.
* MDAPPSale has got a start timestamp, from where buyers can make
* token purchases and the contract will assign them tokens based
* on a ETH per token rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract MDAPPSale is Ownable, PullPayment, usingOraclize {
//contract MDAPPSale is Ownable, PullPayment {
using SafeMath for uint256;
using SafeMath16 for uint16;
// The MDAPP core contract
MDAPP public mdapp;
// Start timestamp for presale (inclusive)
uint256 public startTimePresale;
// End timestamp for presale
uint256 public endTimePresale;
// Start timestamp sale
uint256 public startTimeSale;
// Address where funds are collected
address public wallet;
// Amount of raised money in wei. Only for stats. Don't use for calculations.
uint256 public weiRaised;
// Sold out / sale active?
bool public soldOut = false;
// Max supply
uint16 public constant maxSupply = 10000;
// Initial supply
uint16 public supply = 0;
// Oracle active?
bool public oracleActive = false;
// Delay between autonomous oraclize requests
uint256 public oracleInterval;
// Gas price for oraclize callback transaction
uint256 public oracleGasPrice = 7000000000;
// Gas limit for oraclize callback transaction
// Unused gas is returned to oraclize.
uint256 public oracleGasLimit = 105000;
// When was the ethusd rate updated the last time?
uint256 public oracleLastUpdate = 1;
// Alternative: json(https://api.kraken.com/0/public/Ticker?pair=ETHUSD).result.XETHZUSD.c.0
string public oracleQueryString = 'json(https://api.gdax.com/products/ETH-USD/ticker).price';
// USD Cent value of 1 ether
uint256 public ethusd;
uint256 ethusdLast;
/*********************************************************
* *
* Events *
* *
*********************************************************/
/*
* Event for token purchase logging.
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param tokens amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint16 tokens);
event Recruited(address indexed purchaser, address indexed beneficiary, address indexed recruiter, uint256 value, uint256 share, uint16 tokens);
// Received ETH via fallback function
event Receive(address sender, uint256 value);
event BountyGranted(address indexed beneficiary, uint16 tokens, string reason);
event LogPriceUpdated(uint256 price);
event OracleFundsWithdraw(uint256 value);
event OracleGasPriceChange(uint256 value);
event OracleGasLimitChange(uint256 value);
event OracleIntervalChange(uint256 value);
event OracleQueryStringChange(string value);
event ETHUSDSet(uint256 value);
/*********************************************************
* *
* Initial deployment *
* *
*********************************************************/
constructor(uint256 _startTimePre, uint256 _endTimePre, uint256 _startTimeSale, address _wallet, uint256 _ethusd, uint _oracleInterval, address _mdapp) public {
require(_startTimePre >= now);
require(_endTimePre > _startTimePre);
require(_startTimeSale >= _endTimePre);
require(_wallet != 0x0);
require(_ethusd > 0);
require(_mdapp != 0x0);
ethusd = _ethusd;
ethusdLast = ethusd;
oracleInterval = _oracleInterval;
startTimePresale = _startTimePre;
endTimePresale = _endTimePre;
startTimeSale = _startTimeSale;
wallet = _wallet;
mdapp = MDAPP(_mdapp);
oraclize_setCustomGasPrice(oracleGasPrice);
}
/*********************************************************
* *
* Price calculation and oracle handling *
* *
*********************************************************/
/**
* @dev Request ETHUSD rate from oraclize
* @param _delay in seconds when the request should be scheduled from now on
*/
function requestEthUsd(uint _delay) internal { // Internal call:
if (oracleActive && !soldOut) {
if (oraclize_getPrice("URL") > address(this).balance) {
oracleActive = false;
} else {
if (_delay == 0) {
oraclize_query("URL", oracleQueryString, oracleGasLimit);
} else {
oraclize_query(_delay, "URL", oracleQueryString, oracleGasLimit);
}
}
}
}
/**
* @dev Called by oraclize.
*/
function __callback(bytes32 myid, string result) public {
if (msg.sender != oraclize_cbAddress()) revert();
ethusdLast = ethusd;
ethusd = parseInt(result, 2);
oracleLastUpdate = now;
emit LogPriceUpdated(ethusd);
requestEthUsd(oracleInterval);
}
// Activate ethusd oracle
function activateOracle() onlyOwner external payable {
oracleActive = true;
requestEthUsd(0);
}
function setOracleGasPrice(uint256 _gasPrice) onlyOwner external {
require(_gasPrice > 0, "Gas price must be a positive number.");
oraclize_setCustomGasPrice(_gasPrice);
oracleGasPrice = _gasPrice;
emit OracleGasPriceChange(_gasPrice);
}
function setOracleGasLimit(uint256 _gasLimit) onlyOwner external {
require(_gasLimit > 0, "Gas limit must be a positive number.");
oracleGasLimit = _gasLimit;
emit OracleGasLimitChange(_gasLimit);
}
function setOracleInterval(uint256 _interval) onlyOwner external {
require(_interval > 0, "Interval must be > 0");
oracleInterval = _interval;
emit OracleIntervalChange(_interval);
}
function setOracleQueryString(string _queryString) onlyOwner external {
oracleQueryString = _queryString;
emit OracleQueryStringChange(_queryString);
}
/**
* Only needed to be independent from Oraclize - just for the worst case they stop their service.
*/
function setEthUsd(uint256 _ethusd) onlyOwner external {
require(_ethusd > 0, "ETHUSD must be > 0");
ethusd = _ethusd;
emit ETHUSDSet(_ethusd);
}
/**
* @dev Withdraw remaining oracle funds.
*/
function withdrawOracleFunds() onlyOwner external {
oracleActive = false;
emit OracleFundsWithdraw(address(this).balance);
owner.transfer(address(this).balance);
}
/*********************************************************
* *
* Token and pixel purchase *
* *
*********************************************************/
// Primary token purchase function.
function buyTokens(address _beneficiary, uint16 _tokenAmount, address _recruiter) external payable {
require(_beneficiary != address(0), "Invalid beneficiary.");
require(_tokenAmount > 0, "Token amount bust be a positive integer.");
require(validPurchase(), "Either no active sale or zero ETH sent.");
require(_recruiter != _beneficiary && _recruiter != msg.sender, "Recruiter must not be purchaser or beneficiary.");
assert(ethusd > 0);
// Each pixel costs $1 and 1 token represents 10x10 pixel => x100. ETHUSD comes in Cent => x100 once more
// 10**18 * 10**2 * 10**2 = 10**22
uint256 rate = uint256(10 ** 22).div(ethusd);
// Calculate how much the tokens cost.
// Overpayed purchases don't receive a return.
uint256 cost = uint256(_tokenAmount).mul(rate);
// Accept previous exchange rate if it changed within the last 2 minutes to improve UX during high network load.
if (cost > msg.value) {
if (now - oracleLastUpdate <= 120) {
assert(ethusdLast > 0);
rate = uint256(10 ** 22).div(ethusdLast);
cost = uint256(_tokenAmount).mul(rate);
}
}
require(msg.value >= cost, "Not enough ETH sent.");
// Update supply.
supply += _tokenAmount;
require(supply <= maxSupply, "Not enough tokens available.");
if (_recruiter == address(0)) {
weiRaised = weiRaised.add(msg.value);
asyncTransfer(wallet, msg.value);
} else {
// Purchaser has been recruited. Grant the recruiter 10%.
uint256 tenPercent = msg.value.div(10);
uint256 ninetyPercent = msg.value.sub(tenPercent);
weiRaised = weiRaised.add(ninetyPercent);
asyncTransfer(wallet, ninetyPercent);
asyncTransfer(_recruiter, tenPercent);
emit Recruited(msg.sender, _beneficiary, _recruiter, msg.value, tenPercent, _tokenAmount);
}
// Mint tokens.
bool isPresale = endTimePresale >= now ? true : false;
mdapp.mint(_beneficiary, _tokenAmount, isPresale);
emit TokenPurchase(msg.sender, _beneficiary, msg.value, _tokenAmount);
// Stop minting once we reach max supply.
if (supply == maxSupply) {
soldOut = true;
mdapp.finishMinting();
}
}
function grantBounty(address _beneficiary, uint16 _tokenAmount, string _reason) onlyOwner external {
require(_beneficiary != address(0), "Invalid beneficiary.");
require(_tokenAmount > 0, "Token amount bust be a positive integer.");
// Update supply.
supply += _tokenAmount;
require(supply <= maxSupply, "Not enough tokens available.");
// Mint tokens.
bool isPresale = endTimePresale >= now ? true : false;
mdapp.mint(_beneficiary, _tokenAmount, isPresale);
// Stop minting once we reach max supply.
if (supply == maxSupply) {
soldOut = true;
mdapp.finishMinting();
}
emit BountyGranted(_beneficiary, _tokenAmount, _reason);
}
// Fallback function. Load contract with ETH to use oraclize.
function() public payable {
emit Receive(msg.sender, msg.value);
}
/*********************************************************
* *
* Helpers *
* *
*********************************************************/
// @return true if the transaction can buy tokens
function validPurchase() internal view returns (bool) {
bool withinPeriod = (now >= startTimeSale) || ((now >= startTimePresale) && (now < endTimePresale));
bool nonZeroPurchase = msg.value > 0;
return withinPeriod && nonZeroPurchase && !soldOut;
}
}
|
Stores the sent amount as credit to be withdrawn. _payee The destination address of the funds./
|
function deposit(address _payee) public onlyOwner payable {
uint256 amount = msg.value;
deposits[_payee] = deposits[_payee].add(amount);
emit Deposited(_payee, amount);
}
| 1,000,258 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "./libs/IUniRouter02.sol";
import "./libs/IWETH.sol";
interface IToken {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
}
contract BrewlabsStaking is Ownable, ReentrancyGuard {
using SafeERC20 for IERC20;
// Whether it is initialized
bool public isInitialized;
uint256 public duration = 365; // 365 days
// Whether a limit is set for users
bool public hasUserLimit;
// The pool limit (0 if none)
uint256 public poolLimitPerUser;
// The block number when staking starts.
uint256 public startBlock;
// The block number when staking ends.
uint256 public bonusEndBlock;
// tokens created per block.
uint256 public rewardPerBlock;
// The block number of the last pool update
uint256 public lastRewardBlock;
// swap router and path, slipPage
uint256 public slippageFactor = 800; // 20% default slippage tolerance
uint256 public constant slippageFactorUL = 995;
address public uniRouterAddress;
address[] public reflectionToStakedPath;
address[] public earnedToStakedPath;
// The deposit & withdraw fee
uint256 public constant MAX_FEE = 2000;
uint256 public depositFee;
uint256 public withdrawFee;
address public walletA;
address public buyBackWallet = 0xE1f1dd010BBC2860F81c8F90Ea4E38dB949BB16F;
uint256 public performanceFee = 0.00089 ether;
// The precision factor
uint256 public PRECISION_FACTOR;
uint256 public PRECISION_FACTOR_REFLECTION;
// The staked token
IERC20 public stakingToken;
// The earned token
IERC20 public earnedToken;
// The dividend token of staking token
address public dividendToken;
bool public hasDividend;
// Accrued token per share
uint256 public accTokenPerShare;
uint256 public accDividendPerShare;
uint256 public totalStaked;
uint256 private totalEarned;
uint256 private totalReflections;
uint256 private reflectionDebt;
// Info of each user that stakes tokens (stakingToken)
mapping(address => UserInfo) public userInfo;
struct UserInfo {
uint256 amount; // How many staked tokens the user has provided
uint256 rewardDebt; // Reward debt
uint256 reflectionDebt; // Reflection debt
}
event Deposit(address indexed user, uint256 amount);
event Withdraw(address indexed user, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event AdminTokenRecovered(address tokenRecovered, uint256 amount);
event NewStartAndEndBlocks(uint256 startBlock, uint256 endBlock);
event NewRewardPerBlock(uint256 rewardPerBlock);
event RewardsStop(uint256 blockNumber);
event UpdatePoolLimit(uint256 poolLimitPerUser, bool hasLimit);
event ServiceInfoUpadted(address _addr, uint256 _fee);
event WalletAUpdated(address _addr);
event DurationUpdated(uint256 _duration);
event SetSettings(
uint256 _depositFee,
uint256 _withdrawFee,
uint256 _slippageFactor,
address _uniRouter,
address[] _path0,
address[] _path1
);
constructor() {}
/*
* @notice Initialize the contract
* @param _stakingToken: staked token address
* @param _earnedToken: earned token address
* @param _dividendToken: reflection token address
* @param _rewardPerBlock: reward per block (in earnedToken)
* @param _depositFee: deposit fee
* @param _withdrawFee: withdraw fee
* @param _uniRouter: uniswap router address for swap tokens
* @param _earnedToStakedPath: swap path to compound (earned -> staking path)
* @param _reflectionToStakedPath: swap path to compound (reflection -> staking path)
*/
function initialize(
IERC20 _stakingToken,
IERC20 _earnedToken,
address _dividendToken,
uint256 _rewardPerBlock,
uint256 _depositFee,
uint256 _withdrawFee,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath,
bool _hasDividend
) external onlyOwner {
require(!isInitialized, "Already initialized");
// Make this contract initialized
isInitialized = true;
stakingToken = _stakingToken;
earnedToken = _earnedToken;
dividendToken = _dividendToken;
hasDividend = _hasDividend;
rewardPerBlock = _rewardPerBlock;
require(_depositFee < MAX_FEE, "Invalid deposit fee");
require(_withdrawFee < MAX_FEE, "Invalid withdraw fee");
depositFee = _depositFee;
withdrawFee = _withdrawFee;
walletA = msg.sender;
uint256 decimalsRewardToken = uint256(IToken(address(earnedToken)).decimals());
require(decimalsRewardToken < 30, "Must be inferior to 30");
PRECISION_FACTOR = uint256(10**(40 - decimalsRewardToken));
uint256 decimalsdividendToken = 18;
if(address(dividendToken) != address(0x0)) {
decimalsdividendToken = uint256(IToken(address(dividendToken)).decimals());
require(decimalsdividendToken < 30, "Must be inferior to 30");
}
PRECISION_FACTOR_REFLECTION = uint256(10**(40 - decimalsdividendToken));
uniRouterAddress = _uniRouter;
earnedToStakedPath = _earnedToStakedPath;
reflectionToStakedPath = _reflectionToStakedPath;
}
/*
* @notice Deposit staked tokens and collect reward tokens (if any)
* @param _amount: amount to withdraw (in earnedToken)
*/
function deposit(uint256 _amount) external nonReentrant {
require(startBlock > 0 && startBlock < block.number, "Staking hasn't started yet");
require(_amount > 0, "Amount should be greator than 0");
UserInfo storage user = userInfo[msg.sender];
if (hasUserLimit) {
require(
_amount + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
_updatePool();
if (user.amount > 0) {
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0 && hasDividend) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
stakingToken.safeTransferFrom(
address(msg.sender),
address(this),
_amount
);
uint256 afterAmount = stakingToken.balanceOf(address(this));
uint256 realAmount = afterAmount - beforeAmount;
if (depositFee > 0) {
uint256 fee = realAmount * depositFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
user.amount = user.amount + realAmount;
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
totalStaked = totalStaked + realAmount;
emit Deposit(msg.sender, realAmount);
}
/*
* @notice Withdraw staked tokens and collect reward tokens
* @param _amount: amount to withdraw (in earnedToken)
*/
function withdraw(uint256 _amount) external nonReentrant {
require(_amount > 0, "Amount should be greator than 0");
UserInfo storage user = userInfo[msg.sender];
require(user.amount >= _amount, "Amount to withdraw too high");
_updatePool();
if(user.amount > 0) {
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0 && hasDividend) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
}
uint256 realAmount = _amount;
if (user.amount < _amount) {
realAmount = user.amount;
}
user.amount = user.amount - realAmount;
totalStaked = totalStaked - realAmount;
if (withdrawFee > 0) {
uint256 fee = realAmount * withdrawFee / 10000;
stakingToken.safeTransfer(walletA, fee);
realAmount = realAmount - fee;
}
stakingToken.safeTransfer(address(msg.sender), realAmount);
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
emit Withdraw(msg.sender, _amount);
}
function claimReward() external payable nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
earnedToken.safeTransfer(address(msg.sender), pending);
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
}
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
}
function claimDividend() external payable nonReentrant {
require(hasDividend == true, "No reflections");
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pendingReflection = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(msg.sender).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer(address(msg.sender), pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
function compoundReward() external payable nonReentrant {
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
if (pending > 0) {
require(availableRewardTokens() >= pending, "Insufficient reward tokens");
if(totalEarned > pending) {
totalEarned = totalEarned - pending;
} else {
totalEarned = 0;
}
if(address(stakingToken) != address(earnedToken)) {
uint256 beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(pending, earnedToStakedPath, address(this));
uint256 afterAmount = stakingToken.balanceOf(address(this));
pending = afterAmount - beforeAmount;
}
if (hasUserLimit) {
require(
pending + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
totalStaked = totalStaked + pending;
user.amount = user.amount + pending;
user.reflectionDebt = user.reflectionDebt + pending * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
emit Deposit(msg.sender, pending);
}
user.rewardDebt = user.amount * accTokenPerShare / PRECISION_FACTOR;
}
function compoundDividend() external payable nonReentrant {
require(hasDividend == true, "No reflections");
UserInfo storage user = userInfo[msg.sender];
_transferPerformanceFee();
_updatePool();
if (user.amount == 0) return;
uint256 pending = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
if (pending > 0) {
totalReflections = totalReflections - pending;
if(address(stakingToken) != address(dividendToken)) {
if(address(dividendToken) == address(0x0)) {
address wethAddress = IUniRouter02(uniRouterAddress).WETH();
IWETH(wethAddress).deposit{ value: pending }();
}
uint256 beforeAmount = stakingToken.balanceOf(address(this));
_safeSwap(pending, reflectionToStakedPath, address(this));
uint256 afterAmount = stakingToken.balanceOf(address(this));
pending = afterAmount - beforeAmount;
}
if (hasUserLimit) {
require(
pending + user.amount <= poolLimitPerUser,
"User amount above limit"
);
}
totalStaked = totalStaked + pending;
user.amount = user.amount + pending;
user.rewardDebt = user.rewardDebt + pending * accTokenPerShare / PRECISION_FACTOR;
emit Deposit(msg.sender, pending);
}
user.reflectionDebt = user.amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
function _transferPerformanceFee() internal {
require(msg.value >= performanceFee, 'should pay small gas to compound or harvest');
payable(buyBackWallet).transfer(performanceFee);
if(msg.value > performanceFee) {
payable(msg.sender).transfer(msg.value - performanceFee);
}
}
/*
* @notice Withdraw staked tokens without caring about rewards
* @dev Needs to be for emergency.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.reflectionDebt = 0;
if (amountToTransfer > 0) {
stakingToken.safeTransfer(address(msg.sender), amountToTransfer);
totalStaked = totalStaked - amountToTransfer;
}
emit EmergencyWithdraw(msg.sender, user.amount);
}
/**
* @notice Available amount of reward token
*/
function availableRewardTokens() public view returns (uint256) {
if(address(earnedToken) == address(dividendToken)) return totalEarned;
uint256 _amount = earnedToken.balanceOf(address(this));
if (address(earnedToken) == address(stakingToken)) {
if (_amount < totalStaked) return 0;
return _amount - totalStaked;
}
return _amount;
}
/**
* @notice Available amount of reflection token
*/
function availableDividendTokens() public view returns (uint256) {
if(address(dividendToken) == address(0x0)) {
return address(this).balance;
}
uint256 _amount = IERC20(dividendToken).balanceOf(address(this));
if(address(dividendToken) == address(earnedToken)) {
if(_amount < totalEarned) return 0;
_amount = _amount - totalEarned;
}
if(address(dividendToken) == address(stakingToken)) {
if(_amount < totalStaked) return 0;
_amount = _amount - totalStaked;
}
return _amount;
}
/*
* @notice View function to see pending reward on frontend.
* @param _user: user address
* @return Pending reward for a given user
*/
function pendingReward(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
uint256 adjustedTokenPerShare = accTokenPerShare;
if (block.number > lastRewardBlock && totalStaked != 0 && lastRewardBlock > 0) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 cakeReward = multiplier * rewardPerBlock;
adjustedTokenPerShare = accTokenPerShare + (
cakeReward * PRECISION_FACTOR / totalStaked
);
}
return user.amount * adjustedTokenPerShare / PRECISION_FACTOR - user.rewardDebt;
}
function pendingDividends(address _user) external view returns (uint256) {
UserInfo storage user = userInfo[_user];
if(totalStaked == 0) return 0;
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
uint256 adjustedReflectionPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
uint256 pendingReflection =
user.amount * adjustedReflectionPerShare / PRECISION_FACTOR_REFLECTION - user.reflectionDebt;
return pendingReflection;
}
/************************
** Admin Methods
*************************/
function harvest() external onlyOwner {
_updatePool();
uint256 _amount = stakingToken.balanceOf(address(this));
_amount = _amount - totalStaked;
uint256 pendingReflection = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION - reflectionDebt;
if(pendingReflection > 0) {
if(address(dividendToken) == address(0x0)) {
payable(walletA).transfer(pendingReflection);
} else {
IERC20(dividendToken).safeTransfer( walletA, pendingReflection);
}
totalReflections = totalReflections - pendingReflection;
}
reflectionDebt = _amount * accDividendPerShare / PRECISION_FACTOR_REFLECTION;
}
/*
* @notice Deposit reward token
* @dev Only call by owner. Needs to be for deposit of reward token when reflection token is same with reward token.
*/
function depositRewards(uint _amount) external onlyOwner nonReentrant {
require(_amount > 0, "invalid amount");
uint256 beforeAmt = earnedToken.balanceOf(address(this));
earnedToken.safeTransferFrom(msg.sender, address(this), _amount);
uint256 afterAmt = earnedToken.balanceOf(address(this));
totalEarned = totalEarned + afterAmt - beforeAmt;
}
/*
* @notice Withdraw reward token
* @dev Only callable by owner. Needs to be for emergency.
*/
function emergencyRewardWithdraw(uint256 _amount) external onlyOwner {
require( block.number > bonusEndBlock, "Pool is running");
require(availableRewardTokens() >= _amount, "Insufficient reward tokens");
if(_amount == 0) _amount = availableRewardTokens();
earnedToken.safeTransfer(address(msg.sender), _amount);
if (totalEarned > 0) {
if (_amount > totalEarned) {
totalEarned = 0;
} else {
totalEarned = totalEarned - _amount;
}
}
}
/**
* @notice It allows the admin to recover wrong tokens sent to the contract
* @param _tokenAddress: the address of the token to withdraw
* @param _tokenAmount: the number of tokens to withdraw
* @dev This function is only callable by admin.
*/
function recoverWrongTokens(address _tokenAddress, uint256 _tokenAmount)
external
onlyOwner
{
require(
_tokenAddress != address(earnedToken),
"Cannot be reward token"
);
if(_tokenAddress == address(stakingToken)) {
uint256 tokenBal = stakingToken.balanceOf(address(this));
require(_tokenAmount <= tokenBal - totalStaked, "Insufficient balance");
}
if(_tokenAddress == address(0x0)) {
payable(msg.sender).transfer(_tokenAmount);
} else {
IERC20(_tokenAddress).safeTransfer(address(msg.sender), _tokenAmount);
}
emit AdminTokenRecovered(_tokenAddress, _tokenAmount);
}
function startReward() external onlyOwner {
require(startBlock == 0, "Pool was already started");
startBlock = block.number + 100;
bonusEndBlock = startBlock + duration * 6426;
lastRewardBlock = startBlock;
emit NewStartAndEndBlocks(startBlock, bonusEndBlock);
}
function stopReward() external onlyOwner {
bonusEndBlock = block.number;
emit RewardsStop(bonusEndBlock);
}
/*
* @notice Update pool limit per user
* @dev Only callable by owner.
* @param _hasUserLimit: whether the limit remains forced
* @param _poolLimitPerUser: new pool limit per user
*/
function updatePoolLimitPerUser( bool _hasUserLimit, uint256 _poolLimitPerUser) external onlyOwner {
if (_hasUserLimit) {
require(
_poolLimitPerUser > poolLimitPerUser,
"New limit must be higher"
);
poolLimitPerUser = _poolLimitPerUser;
} else {
poolLimitPerUser = 0;
}
hasUserLimit = _hasUserLimit;
emit UpdatePoolLimit(poolLimitPerUser, hasUserLimit);
}
/*
* @notice Update reward per block
* @dev Only callable by owner.
* @param _rewardPerBlock: the reward per block
*/
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
// require(block.number < startBlock, "Pool was already started");
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
function setServiceInfo(address _buyBackWallet, uint256 _fee) external {
require(msg.sender == buyBackWallet, "setServiceInfo: FORBIDDEN");
require(_buyBackWallet != address(0x0), "Invalid address");
require(_fee < 0.05 ether, "fee cannot exceed 0.05 ether");
buyBackWallet = _buyBackWallet;
performanceFee = _fee;
emit ServiceInfoUpadted(_buyBackWallet, _fee);
}
function updateWalletA(address _walletA) external onlyOwner {
require(_walletA != address(0x0) || _walletA != walletA, "Invalid address");
walletA = _walletA;
emit WalletAUpdated(_walletA);
}
function setDuration(uint256 _duration) external onlyOwner {
require(_duration >= 30, "lower limit reached");
duration = _duration;
if(startBlock > 0) {
bonusEndBlock = startBlock + duration * 6426;
require(bonusEndBlock > block.number, "invalid duration");
}
emit DurationUpdated(_duration);
}
function setSettings(
uint256 _depositFee,
uint256 _withdrawFee,
uint256 _slippageFactor,
address _uniRouter,
address[] memory _earnedToStakedPath,
address[] memory _reflectionToStakedPath
) external onlyOwner {
require(_depositFee < MAX_FEE, "Invalid deposit fee");
require(_withdrawFee < MAX_FEE, "Invalid withdraw fee");
require(_slippageFactor <= slippageFactorUL, "_slippageFactor too high");
depositFee = _depositFee;
withdrawFee = _withdrawFee;
slippageFactor = _slippageFactor;
uniRouterAddress = _uniRouter;
reflectionToStakedPath = _reflectionToStakedPath;
earnedToStakedPath = _earnedToStakedPath;
emit SetSettings(_depositFee, _withdrawFee, _slippageFactor, _uniRouter, _earnedToStakedPath, _reflectionToStakedPath);
}
/************************
** Internal Methods
*************************/
/*
* @notice Update reward variables of the given pool to be up-to-date.
*/
function _updatePool() internal {
// calc reflection rate
if(totalStaked > 0 && hasDividend) {
uint256 reflectionAmount = availableDividendTokens();
uint256 sTokenBal = stakingToken.balanceOf(address(this));
if(address(stakingToken) == dividendToken) {
sTokenBal = sTokenBal - reflectionAmount;
}
accDividendPerShare = accDividendPerShare + (
(reflectionAmount - totalReflections) * PRECISION_FACTOR_REFLECTION / sTokenBal
);
totalReflections = reflectionAmount;
}
if (block.number <= lastRewardBlock || lastRewardBlock == 0) {
return;
}
if (totalStaked == 0) {
lastRewardBlock = block.number;
return;
}
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 _reward = multiplier * rewardPerBlock;
accTokenPerShare = accTokenPerShare + (
_reward * PRECISION_FACTOR / totalStaked
);
lastRewardBlock = block.number;
}
/*
* @notice Return reward multiplier over the given _from to _to block.
* @param _from: block to start
* @param _to: block to finish
*/
function _getMultiplier(uint256 _from, uint256 _to)
internal
view
returns (uint256)
{
if (_to <= bonusEndBlock) {
return _to - _from;
} else if (_from >= bonusEndBlock) {
return 0;
} else {
return bonusEndBlock - _from;
}
}
function _safeSwap(
uint256 _amountIn,
address[] memory _path,
address _to
) internal {
uint256[] memory amounts = IUniRouter02(uniRouterAddress).getAmountsOut(_amountIn, _path);
uint256 amountOut = amounts[amounts.length - 1];
IERC20(_path[0]).safeApprove(uniRouterAddress, _amountIn);
IUniRouter02(uniRouterAddress).swapExactTokensForTokensSupportingFeeOnTransferTokens(
_amountIn,
amountOut * slippageFactor / 1000,
_path,
_to,
block.timestamp + 600
);
}
receive() external payable {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IUniRouter01.sol";
interface IUniRouter02 is IUniRouter01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// 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/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IUniRouter01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
|
Withdraw staked tokens without caring about rewards Needs to be for emergency./
|
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
uint256 amountToTransfer = user.amount;
user.amount = 0;
user.rewardDebt = 0;
user.reflectionDebt = 0;
if (amountToTransfer > 0) {
stakingToken.safeTransfer(address(msg.sender), amountToTransfer);
totalStaked = totalStaked - amountToTransfer;
}
emit EmergencyWithdraw(msg.sender, user.amount);
}
| 14,648,893 |
./full_match/11155111/0x3f9C6646CCFa4597C45761B3e9a1Da0cF00253D5/sources/src/Drips.sol
|
Generates an asset ID for the ERC-20 token erc20 The ERC-20 token return assetId The asset ID
|
function _assetId(IERC20 erc20) internal pure returns (uint256 assetId) {
return uint160(address(erc20));
}
| 3,824,024 |
pragma solidity ^0.6.0;
interface TokenInterface {
function approve(address, uint) external;
function transfer(address, uint) external;
function deposit() external payable;
function withdraw(uint) external;
function balanceOf(address) external view returns (uint);
}
interface ManagerLike {
function cdpCan(address, uint, address) external view returns (uint);
function ilks(uint) external view returns (bytes32);
function last(address) external view returns (uint);
function count(address) external view returns (uint);
function owns(uint) external view returns (address);
function urns(uint) external view returns (address);
function vat() external view returns (address);
function open(bytes32, address) external returns (uint);
function give(uint, address) external;
function frob(uint, int, int) external;
function flux(uint, address, uint) external;
function move(uint, address, uint) external;
}
interface VatLike {
function can(address, address) external view returns (uint);
function ilks(bytes32) external view returns (uint, uint, uint, uint, uint);
function dai(address) external view returns (uint);
function urns(bytes32, address) external view returns (uint, uint);
function frob(
bytes32,
address,
address,
address,
int,
int
) external;
function hope(address) external;
function move(address, address, uint) external;
function gem(bytes32, address) external view returns (uint);
}
interface TokenJoinInterface {
function dec() external returns (uint);
function gem() external returns (TokenInterface);
function join(address, uint) external payable;
function exit(address, uint) external;
}
interface DaiJoinInterface {
function vat() external returns (VatLike);
function dai() external returns (TokenInterface);
function join(address, uint) external payable;
function exit(address, uint) external;
}
interface JugLike {
function drip(bytes32) external returns (uint);
}
interface PotLike {
function pie(address) external view returns (uint);
function drip() external returns (uint);
function join(uint) external;
function exit(uint) external;
}
interface MemoryInterface {
function getUint(uint _id) external returns (uint _num);
function setUint(uint _id, uint _val) external;
}
interface InstaMapping {
function gemJoinMapping(bytes32) external view returns (address);
}
interface EventInterface {
function emitEvent(uint _connectorType, uint _connectorID, bytes32 _eventCode, bytes calldata _eventData) external;
}
interface AccountInterface {
function isAuth(address _user) external view returns (bool);
}
contract DSMath {
uint256 constant RAY = 10 ** 27;
uint constant WAD = 10 ** 18;
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "math-not-safe");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-overflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
function wmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function wdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, WAD), y / 2) / y;
}
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, RAY), y / 2) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
function toRad(uint wad) internal pure returns (uint rad) {
rad = mul(wad, 10 ** 27);
}
function convertTo18(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10 ** (18 - _dec));
}
function convert18ToDec(uint _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10 ** (18 - _dec));
}
}
contract Helpers is DSMath {
/**
* @dev Return ETH Address.
*/
function getAddressETH() internal pure returns (address) {
return 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
/**
* @dev Return WETH Address.
*/
function getAddressWETH() internal pure returns (address) {
return 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
}
/**
* @dev Return InstAaMemory Address.
*/
function getMemoryAddr() internal pure returns (address) {
return 0x8a5419CfC711B2343c17a6ABf4B2bAFaBb06957F;
}
/**
* @dev Return InstaEvent Address.
*/
function getEventAddr() internal pure returns (address) {
return 0x2af7ea6Cb911035f3eb1ED895Cb6692C39ecbA97;
}
/**
* @dev Get Uint value from InstaMemory Contract.
*/
function getUint(uint getId, uint val) internal returns (uint returnVal) {
returnVal = getId == 0 ? val : MemoryInterface(getMemoryAddr()).getUint(getId);
}
/**
* @dev Set Uint value in InstaMemory Contract.
*/
function setUint(uint setId, uint val) internal {
if (setId != 0) MemoryInterface(getMemoryAddr()).setUint(setId, val);
}
/**
* @dev Connector Details
*/
function connectorID() public pure returns(uint _type, uint _id) {
(_type, _id) = (1, 61);
}
}
contract MakerMCDAddresses is Helpers {
/**
* @dev Return Maker MCD Manager Address.
*/
function getMcdManager() internal pure returns (address) {
return 0x5ef30b9986345249bc32d8928B7ee64DE9435E39;
}
/**
* @dev Return Maker MCD DAI Address.
*/
function getMcdDai() internal pure returns (address) {
return 0x6B175474E89094C44Da98b954EedeAC495271d0F;
}
/**
* @dev Return Maker MCD DAI_Join Address.
*/
function getMcdDaiJoin() internal pure returns (address) {
return 0x9759A6Ac90977b93B58547b4A71c78317f391A28;
}
/**
* @dev Return Maker MCD Jug Address.
*/
function getMcdJug() internal pure returns (address) {
return 0x19c0976f590D67707E62397C87829d896Dc0f1F1;
}
/**
* @dev Return Maker MCD Pot Address.
*/
function getMcdPot() internal pure returns (address) {
return 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7;
}
}
contract MakerHelpers is MakerMCDAddresses {
/**
* @dev Return InstaMapping Address.
*/
function getMappingAddr() internal pure returns (address) {
return 0xe81F70Cc7C0D46e12d70efc60607F16bbD617E88;
}
/**
* @dev Return Close Vault Address.
*/
function getGiveAddress() internal pure returns (address) {
return 0x4dD58550eb15190a5B3DfAE28BB14EeC181fC267;
}
/**
* @dev Get Vault's ilk.
*/
function getVaultData(ManagerLike managerContract, uint vault) internal view returns (bytes32 ilk, address urn) {
ilk = managerContract.ilks(vault);
urn = managerContract.urns(vault);
}
/**
* @dev Gem Join address is ETH type collateral.
*/
function isEth(address tknAddr) internal pure returns (bool) {
return tknAddr == getAddressWETH() ? true : false;
}
/**
* @dev Get Vault Debt Amount.
*/
function _getVaultDebt(
address vat,
bytes32 ilk,
address urn
) internal view returns (uint wad) {
(, uint rate,,,) = VatLike(vat).ilks(ilk);
(, uint art) = VatLike(vat).urns(ilk, urn);
uint dai = VatLike(vat).dai(urn);
uint rad = sub(mul(art, rate), dai);
wad = rad / RAY;
wad = mul(wad, RAY) < rad ? wad + 1 : wad;
}
/**
* @dev Get Borrow Amount.
*/
function _getBorrowAmt(
address vat,
address urn,
bytes32 ilk,
uint amt
) internal returns (int dart)
{
address jug = getMcdJug();
uint rate = JugLike(jug).drip(ilk);
uint dai = VatLike(vat).dai(urn);
if (dai < mul(amt, RAY)) {
dart = toInt(sub(mul(amt, RAY), dai) / rate);
dart = mul(uint(dart), rate) < mul(amt, RAY) ? dart + 1 : dart;
}
}
/**
* @dev Get Payback Amount.
*/
function _getWipeAmt(
address vat,
uint amt,
address urn,
bytes32 ilk
) internal view returns (int dart)
{
(, uint rate,,,) = VatLike(vat).ilks(ilk);
(, uint art) = VatLike(vat).urns(ilk, urn);
dart = toInt(amt / rate);
dart = uint(dart) <= art ? - dart : - toInt(art);
}
/**
* @dev Convert String to bytes32.
*/
function stringToBytes32(string memory str) internal pure returns (bytes32 result) {
require(bytes(str).length != 0, "string-empty");
// solium-disable-next-line security/no-inline-assembly
assembly {
result := mload(add(str, 32))
}
}
/**
* @dev Get vault ID. If `vault` is 0, get last opened vault.
*/
function getVault(ManagerLike managerContract, uint vault) internal view returns (uint _vault) {
if (vault == 0) {
require(managerContract.count(address(this)) > 0, "no-vault-opened");
_vault = managerContract.last(address(this));
} else {
_vault = vault;
}
}
}
contract BasicResolver is MakerHelpers {
event LogOpen(uint256 indexed vault, bytes32 indexed ilk);
event LogClose(uint256 indexed vault, bytes32 indexed ilk);
event LogTransfer(uint256 indexed vault, bytes32 indexed ilk, address newOwner);
event LogDeposit(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogWithdraw(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogBorrow(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogPayback(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
/**
* @dev Open Vault
* @param colType Type of Collateral.(eg: 'ETH-A')
*/
function open(string calldata colType) external payable returns (uint vault) {
bytes32 ilk = stringToBytes32(colType);
require(InstaMapping(getMappingAddr()).gemJoinMapping(ilk) != address(0), "wrong-col-type");
vault = ManagerLike(getMcdManager()).open(ilk, address(this));
emit LogOpen(vault, ilk);
}
/**
* @dev Close Vault
* @param vault Vault ID to close.
*/
function close(uint vault) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
(uint ink, uint art) = VatLike(managerContract.vat()).urns(ilk, urn);
require(ink == 0 && art == 0, "vault-has-assets");
require(managerContract.owns(_vault) == address(this), "not-owner");
managerContract.give(_vault, getGiveAddress());
emit LogClose(_vault, ilk);
}
/**
* @dev Deposit ETH/ERC20_Token Collateral.
* @param vault Vault ID.
* @param amt token amount to deposit.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function deposit(
uint vault,
uint amt,
uint getId,
uint setId
) external payable
{
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk);
TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr);
TokenInterface tokenContract = tokenJoinContract.gem();
if (isEth(address(tokenContract))) {
_amt = _amt == uint(-1) ? address(this).balance : _amt;
tokenContract.deposit{value: _amt}();
} else {
_amt = _amt == uint(-1) ? tokenContract.balanceOf(address(this)) : _amt;
}
tokenContract.approve(address(colAddr), _amt);
tokenJoinContract.join(address(this), _amt);
VatLike(managerContract.vat()).frob(
ilk,
urn,
address(this),
address(this),
toInt(convertTo18(tokenJoinContract.dec(), _amt)),
0
);
setUint(setId, _amt);
emit LogDeposit(vault, ilk, _amt, getId, setId);
}
/**
* @dev Withdraw ETH/ERC20_Token Collateral.
* @param vault Vault ID.
* @param amt token amount to withdraw.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdraw(
uint vault,
uint amt,
uint getId,
uint setId
) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk);
TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr);
uint _amt18;
if (_amt == uint(-1)) {
(_amt18,) = VatLike(managerContract.vat()).urns(ilk, urn);
_amt = convert18ToDec(tokenJoinContract.dec(), _amt18);
} else {
_amt18 = convertTo18(tokenJoinContract.dec(), _amt);
}
managerContract.frob(
_vault,
-toInt(_amt18),
0
);
managerContract.flux(
_vault,
address(this),
_amt18
);
TokenInterface tokenContract = tokenJoinContract.gem();
if (isEth(address(tokenContract))) {
tokenJoinContract.exit(address(this), _amt);
tokenContract.withdraw(_amt);
} else {
tokenJoinContract.exit(address(this), _amt);
}
setUint(setId, _amt);
emit LogWithdraw(_vault, ilk, _amt, getId, setId);
}
/**
* @dev Borrow DAI.
* @param vault Vault ID.
* @param amt token amount to borrow.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function borrow(
uint vault,
uint amt,
uint getId,
uint setId
) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address daiJoin = getMcdDaiJoin();
VatLike vatContract = VatLike(managerContract.vat());
managerContract.frob(
_vault,
0,
_getBorrowAmt(
address(vatContract),
urn,
ilk,
_amt
)
);
managerContract.move(
_vault,
address(this),
toRad(_amt)
);
if (vatContract.can(address(this), address(daiJoin)) == 0) {
vatContract.hope(daiJoin);
}
DaiJoinInterface(daiJoin).exit(address(this), _amt);
setUint(setId, _amt);
emit LogBorrow(vault, ilk, _amt, getId, setId);
}
/**
* @dev Payback borrowed DAI.
* @param vault Vault ID.
* @param amt token amount to payback.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function payback(
uint vault,
uint amt,
uint getId,
uint setId
) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address vat = managerContract.vat();
uint _maxDebt = _getVaultDebt(vat, ilk, urn);
_amt = _amt == uint(-1) ? _maxDebt : _amt;
require(_maxDebt >= _amt, "paying-excess-debt");
DaiJoinInterface daiJoinContract = DaiJoinInterface(getMcdDaiJoin());
daiJoinContract.dai().approve(getMcdDaiJoin(), _amt);
daiJoinContract.join(urn, _amt);
managerContract.frob(
_vault,
0,
_getWipeAmt(
vat,
VatLike(vat).dai(urn),
urn,
ilk
)
);
setUint(setId, _amt);
emit LogPayback(_vault, ilk, _amt, getId, setId);
}
}
contract BasicExtraResolver is BasicResolver {
event LogWithdrawLiquidated(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
event LogExitDai(uint256 indexed vault, bytes32 indexed ilk, uint256 tokenAmt, uint256 getId, uint256 setId);
/**
* @dev Withdraw leftover ETH/ERC20_Token after Liquidation.
* @param vault Vault ID.
* @param amt token amount to Withdraw.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdrawLiquidated(
uint vault,
uint amt,
uint getId,
uint setId
)
external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
(bytes32 ilk, address urn) = getVaultData(managerContract, vault);
address colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk);
TokenJoinInterface tokenJoinContract = TokenJoinInterface(colAddr);
uint _amt18;
if (_amt == uint(-1)) {
_amt18 = VatLike(managerContract.vat()).gem(ilk, urn);
_amt = convert18ToDec(tokenJoinContract.dec(), _amt18);
} else {
_amt18 = convertTo18(tokenJoinContract.dec(), _amt);
}
managerContract.flux(
vault,
address(this),
_amt18
);
TokenInterface tokenContract = tokenJoinContract.gem();
tokenJoinContract.exit(address(this), _amt);
if (isEth(address(tokenContract))) {
tokenContract.withdraw(_amt);
}
setUint(setId, _amt);
emit LogWithdrawLiquidated(vault, ilk, _amt, getId, setId);
}
struct MakerData {
uint _vault;
address colAddr;
address daiJoin;
TokenJoinInterface tokenJoinContract;
VatLike vatContract;
TokenInterface tokenContract;
}
/**
* @dev Deposit ETH/ERC20_Token Collateral and Borrow DAI.
* @param vault Vault ID.
* @param depositAmt token deposit amount to Withdraw.
* @param borrowAmt token borrow amount to Withdraw.
* @param getIdDeposit Get deposit token amount at this ID from `InstaMemory` Contract.
* @param getIdBorrow Get borrow token amount at this ID from `InstaMemory` Contract.
* @param setIdDeposit Set deposit token amount at this ID in `InstaMemory` Contract.
* @param setIdBorrow Set borrow token amount at this ID in `InstaMemory` Contract.
*/
function depositAndBorrow(
uint vault,
uint depositAmt,
uint borrowAmt,
uint getIdDeposit,
uint getIdBorrow,
uint setIdDeposit,
uint setIdBorrow
) external payable
{
ManagerLike managerContract = ManagerLike(getMcdManager());
MakerData memory makerData;
uint _amtDeposit = getUint(getIdDeposit, depositAmt);
uint _amtBorrow = getUint(getIdBorrow, borrowAmt);
makerData._vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, makerData._vault);
makerData.colAddr = InstaMapping(getMappingAddr()).gemJoinMapping(ilk);
makerData.tokenJoinContract = TokenJoinInterface(makerData.colAddr);
makerData.vatContract = VatLike(managerContract.vat());
makerData.daiJoin = getMcdDaiJoin();
makerData.tokenContract = makerData.tokenJoinContract.gem();
if (isEth(address(makerData.tokenContract))) {
_amtDeposit = _amtDeposit == uint(-1) ? address(this).balance : _amtDeposit;
makerData.tokenContract.deposit{value: _amtDeposit}();
} else {
_amtDeposit = _amtDeposit == uint(-1) ? makerData.tokenContract.balanceOf(address(this)) : _amtDeposit;
}
makerData.tokenContract.approve(address(makerData.colAddr), _amtDeposit);
makerData.tokenJoinContract.join(urn, _amtDeposit);
managerContract.frob(
makerData._vault,
toInt(convertTo18(makerData.tokenJoinContract.dec(), _amtDeposit)),
_getBorrowAmt(
address(makerData.vatContract),
urn,
ilk,
_amtBorrow
)
);
managerContract.move(
makerData._vault,
address(this),
toRad(_amtBorrow)
);
if (makerData.vatContract.can(address(this), address(makerData.daiJoin)) == 0) {
makerData.vatContract.hope(makerData.daiJoin);
}
DaiJoinInterface(makerData.daiJoin).exit(address(this), _amtBorrow);
setUint(setIdDeposit, _amtDeposit);
setUint(setIdBorrow, _amtBorrow);
emit LogDeposit(makerData._vault, ilk, _amtDeposit, getIdDeposit, setIdDeposit);
emit LogBorrow(makerData._vault, ilk, _amtBorrow, getIdBorrow, setIdBorrow);
}
/**
* @dev Exit DAI from urn.
* @param vault Vault ID.
* @param amt token amount to exit.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function exitDai(
uint vault,
uint amt,
uint getId,
uint setId
) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address daiJoin = getMcdDaiJoin();
VatLike vatContract = VatLike(managerContract.vat());
if(_amt == uint(-1)) {
_amt = vatContract.dai(urn);
_amt = _amt / 10 ** 27;
}
managerContract.move(
_vault,
address(this),
toRad(_amt)
);
if (vatContract.can(address(this), address(daiJoin)) == 0) {
vatContract.hope(daiJoin);
}
DaiJoinInterface(daiJoin).exit(address(this), _amt);
setUint(setId, _amt);
emit LogExitDai(_vault, ilk, _amt, getId, setId);
}
}
contract DsrResolver is BasicExtraResolver {
event LogDepositDai(uint256 tokenAmt, uint256 getId, uint256 setId);
event LogWithdrawDai(uint256 tokenAmt, uint256 getId, uint256 setId);
/**
* @dev Deposit DAI in DSR.
* @param amt DAI amount to deposit.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function depositDai(
uint amt,
uint getId,
uint setId
) external payable {
uint _amt = getUint(getId, amt);
address pot = getMcdPot();
address daiJoin = getMcdDaiJoin();
DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin);
_amt = _amt == uint(-1) ?
daiJoinContract.dai().balanceOf(address(this)) :
_amt;
VatLike vat = daiJoinContract.vat();
PotLike potContract = PotLike(pot);
uint chi = potContract.drip();
daiJoinContract.dai().approve(daiJoin, _amt);
daiJoinContract.join(address(this), _amt);
if (vat.can(address(this), address(pot)) == 0) {
vat.hope(pot);
}
potContract.join(mul(_amt, RAY) / chi);
setUint(setId, _amt);
emit LogDepositDai(_amt, getId, setId);
}
/**
* @dev Withdraw DAI from DSR.
* @param amt DAI amount to withdraw.
* @param getId Get token amount at this ID from `InstaMemory` Contract.
* @param setId Set token amount at this ID in `InstaMemory` Contract.
*/
function withdrawDai(
uint amt,
uint getId,
uint setId
) external payable {
address daiJoin = getMcdDaiJoin();
uint _amt = getUint(getId, amt);
DaiJoinInterface daiJoinContract = DaiJoinInterface(daiJoin);
VatLike vat = daiJoinContract.vat();
PotLike potContract = PotLike(getMcdPot());
uint chi = potContract.drip();
uint pie;
if (_amt == uint(-1)) {
pie = potContract.pie(address(this));
_amt = mul(chi, pie) / RAY;
} else {
pie = mul(_amt, RAY) / chi;
}
potContract.exit(pie);
uint bal = vat.dai(address(this));
if (vat.can(address(this), address(daiJoin)) == 0) {
vat.hope(daiJoin);
}
daiJoinContract.exit(
address(this),
bal >= mul(_amt, RAY) ? _amt : bal / RAY
);
setUint(setId, _amt);
emit LogWithdrawDai(_amt, getId, setId);
}
}
contract ConnectMaker is DsrResolver {
string public constant name = "MakerDao-v1.4";
}
|
Payback borrowed DAI. vault Vault ID. amt token amount to payback. getId Get token amount at this ID from `InstaMemory` Contract. setId Set token amount at this ID in `InstaMemory` Contract./
|
function payback(
uint vault,
uint amt,
uint getId,
uint setId
) external payable {
ManagerLike managerContract = ManagerLike(getMcdManager());
uint _amt = getUint(getId, amt);
uint _vault = getVault(managerContract, vault);
(bytes32 ilk, address urn) = getVaultData(managerContract, _vault);
address vat = managerContract.vat();
uint _maxDebt = _getVaultDebt(vat, ilk, urn);
_amt = _amt == uint(-1) ? _maxDebt : _amt;
require(_maxDebt >= _amt, "paying-excess-debt");
DaiJoinInterface daiJoinContract = DaiJoinInterface(getMcdDaiJoin());
daiJoinContract.dai().approve(getMcdDaiJoin(), _amt);
daiJoinContract.join(urn, _amt);
managerContract.frob(
_vault,
0,
_getWipeAmt(
vat,
VatLike(vat).dai(urn),
urn,
ilk
)
);
setUint(setId, _amt);
emit LogPayback(_vault, ilk, _amt, getId, setId);
}
| 892,422 |
//SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
import "./TransferUtils.sol";
import "./interfaces/IStakeUtils.sol";
/// @title Contract that implements staking functionality
abstract contract StakeUtils is TransferUtils, IStakeUtils {
string private constant ERROR_NOT_ENOUGH_FUNDS = "API3DAO.StakeUtils: User don't have enough token to stake/unstake the provided amount";
string private constant ERROR_NOT_ENOUGH_SHARES = "API3DAO.StakeUtils: User don't have enough pool shares to unstake the provided amount";
string private constant ERROR_UNSTAKE_TIMING = "API3DAO.StakeUtils: Scheduled unstake has not matured yet";
string private constant ERROR_STAKING_ADDRESS = "API3DAO.StakeUtils: It is only possible to stake to yourself";
string private constant ERROR_ALREADY_SCHEDULED = "API3DAO.StakeUtils: User has already scheduled an unstake";
string private constant ERROR_NO_SCHEDULED = "API3DAO.StakeUtils: User has no scheduled unstake to execute";
/// @notice Called to stake tokens to receive pools in the share
/// @param amount Amount of tokens to stake
function stake(uint256 amount)
public
override
{
payReward();
User storage user = users[msg.sender];
require(user.unstaked >= amount, ERROR_NOT_ENOUGH_FUNDS);
user.unstaked = user.unstaked - amount;
uint256 totalSharesNow = totalShares();
uint256 sharesToMint = totalSharesNow * amount / totalStake;
uint256 userSharesNow = userShares(msg.sender);
user.shares.push(Checkpoint({
fromBlock: block.number,
value: userSharesNow + sharesToMint
}));
uint256 totalSharesAfter = totalSharesNow + sharesToMint;
updateTotalShares(totalSharesAfter);
totalStake = totalStake + amount;
updateDelegatedVotingPower(msg.sender, sharesToMint, true);
emit Staked(
msg.sender,
amount,
totalSharesAfter
);
}
/// @notice Convenience method to deposit and stake in a single transaction
/// @dev Due to the `deposit()` interface, `userAddress` can only be the
/// caller
/// @param source Token transfer source
/// @param amount Amount to be deposited and staked
function depositAndStake(
address source,
uint256 amount
)
external
override
{
deposit(source, amount, msg.sender);
stake(amount);
}
/// @notice Called by the user to schedule unstaking of their tokens
/// @dev While scheduling an unstake, `shares` get deducted from the user,
/// meaning that they will not receive rewards or voting power for them any
/// longer.
/// At unstaking-time, the user unstakes either the amount of tokens
/// `shares` corresponds to at scheduling-time, or the amount of tokens
/// `shares` corresponds to at unstaking-time, whichever is smaller. This
/// corresponds to tokens being scheduled to be unstaked not receiving any
/// rewards, but being subject to claim payouts.
/// In the instance that a claim has been paid out before an unstaking is
/// executed, the user may potentially receive rewards during
/// `unstakeWaitPeriod` (but not if there has not been a claim payout) but
/// the amount of tokens that they can unstake will not be able to exceed
/// the amount they scheduled the unstaking for.
/// @param shares Amount of shares to be burned to unstake tokens
function scheduleUnstake(uint256 shares)
external
override
{
payReward();
uint256 userSharesNow = userShares(msg.sender);
require(
userSharesNow >= shares,
ERROR_NOT_ENOUGH_SHARES
);
User storage user = users[msg.sender];
require(user.unstakeScheduledFor == 0, ERROR_ALREADY_SCHEDULED);
uint256 amount = shares * totalStake / totalShares();
user.unstakeScheduledFor = block.timestamp + unstakeWaitPeriod;
user.unstakeAmount = amount;
user.unstakeShares = shares;
user.shares.push(Checkpoint({
fromBlock: block.number,
value: userSharesNow - shares
}));
updateDelegatedVotingPower(msg.sender, shares, false);
emit ScheduledUnstake(
msg.sender,
shares,
amount,
user.unstakeScheduledFor
);
}
/// @notice Called to execute a pre-scheduled unstake
/// @dev Anyone can execute a mature scheduled unstake
/// @param userAddress Address of the user whose scheduled unstaking will
/// be executed
/// @return Amount of tokens that are unstaked
function unstake(address userAddress)
public
override
returns(uint256)
{
payReward();
User storage user = users[userAddress];
require(user.unstakeScheduledFor != 0, ERROR_NO_SCHEDULED);
require(user.unstakeScheduledFor < block.timestamp, ERROR_UNSTAKE_TIMING);
uint256 totalShares = totalShares();
uint256 unstakeAmountAtSchedulingTime = user.unstakeAmount;
uint256 unstakeAmountByShares = user.unstakeShares * totalStake / totalShares;
uint256 unstakeAmount = unstakeAmountAtSchedulingTime > unstakeAmountByShares
? unstakeAmountByShares
: unstakeAmountAtSchedulingTime;
unstakeAmount = unstakeAmount < totalStake ? unstakeAmount : totalStake - 1;
user.unstaked = user.unstaked + unstakeAmount;
updateTotalShares(totalShares - user.unstakeShares);
totalStake = totalStake - unstakeAmount;
user.unstakeShares = 0;
user.unstakeAmount = 0;
user.unstakeScheduledFor = 0;
emit Unstaked(
userAddress,
unstakeAmount
);
return unstakeAmount;
}
/// @notice Convenience method to execute an unstake and withdraw in a
/// single transaction
/// @dev Note that withdraw may revert because the user may have less than
/// `unstaked` tokens that are withdrawable
/// @param destination Token transfer destination
function unstakeAndWithdraw(address destination)
external
override
{
uint256 unstaked = unstake(msg.sender);
withdraw(destination, unstaked);
}
}
|
Convenience method to deposit and stake in a single transaction Due to the `deposit()` interface, `userAddress` can only be the caller source Token transfer source amount Amount to be deposited and staked
|
function depositAndStake(
address source,
uint256 amount
)
external
override
{
deposit(source, amount, msg.sender);
stake(amount);
}
| 6,398,367 |
pragma solidity ^0.5.6;
import "./QuestCoinLoom.sol";
import "./QuestLootLoom.sol";
import "./Verifier.sol";
contract QuestController {
// Quest Register section
address owner;
address ERC20contract;
address ERC721contract;
QuestCoinLoom qt;
QuestLootLoom ql;
constructor(address ERC20input, address ERC721input) public {
owner = msg.sender;
ERC20contract = ERC20input;
ERC721contract = ERC721input;
// instantiate ERC20 & ERC721 contracts
qt = QuestCoinLoom(ERC20contract);
ql = QuestLootLoom(ERC721contract);
}
modifier onlyOwner {
require(
msg.sender == owner,
"Only the contract owner can use this function"
);
_;
}
struct QuestEntry {
address creator;
string identifier;
address verifierAddress;
uint256 questPrice;
string questObjectURLonIPFS;
string cirDefURLonIPFS;
string provingKeyURLonIPFS;
}
mapping(bytes32 => QuestEntry) public questRegister;
mapping(address => string) private _playerQuestInProgress;
event paymentForQuest(
address payer,
address recipient,
string identifierForQuest
);
event victory(address player, string questName, uint256 tokenID);
event incorrectPath(address player, string questName);
function getHash(string memory questName) public pure returns (bytes32) {
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
return questNameHash;
}
function addEntry(
string memory questName,
address creatorInput,
string memory identifierInput,
address verifierInput,
uint256 priceInput,
string memory questObjectURLinput,
string memory cirDefURLinput,
string memory provingKeyURLinput
) public {
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
//require(questRegister[questNameHash].creator == address(0), "This quest name already exists");
questRegister[questNameHash].creator = creatorInput;
questRegister[questNameHash].identifier = identifierInput;
questRegister[questNameHash].verifierAddress = verifierInput;
questRegister[questNameHash].questPrice = priceInput;
questRegister[questNameHash].questObjectURLonIPFS = questObjectURLinput;
questRegister[questNameHash].cirDefURLonIPFS = cirDefURLinput;
questRegister[questNameHash].provingKeyURLonIPFS = provingKeyURLinput;
}
// Game logic section
function playerPayment(string memory questName) public {
// get quest parameters and check that quest exists
address creator;
uint256 price;
string memory identifier;
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
// check that quest exists
require(
questRegister[questNameHash].creator != address(0),
"This quest doesn't exist"
);
creator = questRegister[questNameHash].creator;
price = questRegister[questNameHash].questPrice;
identifier = questRegister[questNameHash].identifier;
// check that player isn't on another quest currently
require(
bytes(_playerQuestInProgress[msg.sender]).length == 0,
"You are already playing another quest"
);
// check that player has sufficient token balance
require(qt.balanceOf(msg.sender) > price, "Insufficient token balance");
// realize payment and emit event
qt.transferFrom(msg.sender, creator, price);
_playerQuestInProgress[msg.sender] = questName;
emit paymentForQuest(msg.sender, creator, identifier);
}
function checkAndMint(
string memory questName,
uint256[2] memory a,
uint256[2] memory a_p,
uint256[2][2] memory b,
uint256[2] memory b_p,
uint256[2] memory c,
uint256[2] memory c_p,
uint256[2] memory h,
uint256[2] memory k,
uint256[1] memory input
) public {
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
// checking that player has made payment for this quest and hasn't won or abandoned yet
require(
sha256(abi.encodePacked(_playerQuestInProgress[msg.sender])) ==
sha256(abi.encodePacked(questName)),
"You are not currently playing this quest."
);
bool confirmation;
confirmation = _checkSolution(
questName,
a,
a_p,
b,
b_p,
c,
c_p,
h,
k,
input
);
if (confirmation == true) {
uint256 tokenID;
tokenID = ql.mintAndIncrement(msg.sender);
_playerQuestInProgress[msg.sender] = "";
emit victory(msg.sender, questName, tokenID);
} else {
emit incorrectPath(msg.sender, questName);
}
}
function _checkSolution(
string memory questName,
uint256[2] memory a,
uint256[2] memory a_p,
uint256[2][2] memory b,
uint256[2] memory b_p,
uint256[2] memory c,
uint256[2] memory c_p,
uint256[2] memory h,
uint256[2] memory k,
uint256[1] memory input
) private view returns (bool) {
// get quest parameters
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
address verifierAddress;
verifierAddress = questRegister[questNameHash].verifierAddress;
// check that verifier contract exists
require(verifierAddress != address(0));
Verifier v = Verifier(verifierAddress);
bool confirmation;
confirmation = v.verifyProof(a, a_p, b, b_p, c, c_p, h, k, input);
if (confirmation == true) {
return true;
} else {
return false;
}
}
function abandonCurrentQuest() public {
require(
bytes(_playerQuestInProgress[msg.sender]).length > 0,
"You are not playing any quest currently"
);
_playerQuestInProgress[msg.sender] = "";
}
}
|
checking that player has made payment for this quest and hasn't won or abandoned yet
|
function checkAndMint(
string memory questName,
uint256[2] memory a,
uint256[2] memory a_p,
uint256[2][2] memory b,
uint256[2] memory b_p,
uint256[2] memory c,
uint256[2] memory c_p,
uint256[2] memory h,
uint256[2] memory k,
uint256[1] memory input
) public {
bytes32 questNameHash;
questNameHash = sha256(abi.encodePacked(questName));
require(
sha256(abi.encodePacked(_playerQuestInProgress[msg.sender])) ==
sha256(abi.encodePacked(questName)),
"You are not currently playing this quest."
);
bool confirmation;
confirmation = _checkSolution(
questName,
a,
a_p,
b,
b_p,
c,
c_p,
h,
k,
input
);
if (confirmation == true) {
uint256 tokenID;
tokenID = ql.mintAndIncrement(msg.sender);
_playerQuestInProgress[msg.sender] = "";
emit victory(msg.sender, questName, tokenID);
emit incorrectPath(msg.sender, questName);
}
}
| 12,590,247 |
./partial_match/1/0xd81b3000D6Cad7af85E9939AfAb1243B56618EA9/sources/VFIN.sol
|
move the last item into the index being vacated_totalPartitions.length -= 1;
|
function removeDocument(bytes32 shortName) external override {
require(_isController[msg.sender], "Unauthorized");
Doc memory data = _documents[shortName];
uint256 index1 = _indexOfDocHashes[data.docHash];
bytes32 lastValue = _docHashes[_docHashes.length - 1];
_indexOfDocHashes[lastValue] = index1;
_docHashes.pop();
_indexOfDocHashes[data.docHash] = 0;
delete _documents[shortName];
emit DocumentRemoved(shortName, data.docURI, data.docHash);
}
| 4,032,055 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./lib/Initializable.sol";
/**
* @title EdenNetworkManager
* @dev Handles updates for the EdenNetwork proxy + implementation
*/
contract EdenNetworkManager is Initializable {
/// @notice EdenNetworkManager admin
address public admin;
/// @notice EdenNetworkProxy address
address public edenNetworkProxy;
/// @notice Admin modifier
modifier onlyAdmin() {
require(msg.sender == admin, "not admin");
_;
}
/// @notice New admin event
event AdminChanged(address indexed oldAdmin, address indexed newAdmin);
/// @notice New Eden Network proxy event
event EdenNetworkProxyChanged(address indexed oldEdenNetworkProxy, address indexed newEdenNetworkProxy);
/**
* @notice Construct new EdenNetworkManager contract, setting msg.sender as admin
*/
constructor() {
admin = msg.sender;
emit AdminChanged(address(0), msg.sender);
}
/**
* @notice Initialize contract
* @param _edenNetworkProxy EdenNetwork proxy contract address
* @param _admin Admin address
*/
function initialize(
address _edenNetworkProxy,
address _admin
) external initializer onlyAdmin {
emit AdminChanged(admin, _admin);
admin = _admin;
edenNetworkProxy = _edenNetworkProxy;
emit EdenNetworkProxyChanged(address(0), _edenNetworkProxy);
}
/**
* @notice Set new admin for this contract
* @dev Can only be executed by admin
* @param newAdmin new admin address
*/
function setAdmin(
address newAdmin
) external onlyAdmin {
emit AdminChanged(admin, newAdmin);
admin = newAdmin;
}
/**
* @notice Set new Eden Network proxy contract
* @dev Can only be executed by admin
* @param newEdenNetworkProxy new Eden Network proxy address
*/
function setEdenNetworkProxy(
address newEdenNetworkProxy
) external onlyAdmin {
emit EdenNetworkProxyChanged(edenNetworkProxy, newEdenNetworkProxy);
edenNetworkProxy = newEdenNetworkProxy;
}
/**
* @notice Public getter for EdenNetwork Proxy implementation contract address
*/
function getProxyImplementation() public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("implementation()")) == 0x5c60da1b
(bool success, bytes memory returndata) = edenNetworkProxy.staticcall(hex"5c60da1b");
require(success);
return abi.decode(returndata, (address));
}
/**
* @notice Public getter for EdenNetwork Proxy admin address
*/
function getProxyAdmin() public view returns (address) {
// We need to manually run the static call since the getter cannot be flagged as view
// bytes4(keccak256("admin()")) == 0xf851a440
(bool success, bytes memory returndata) = edenNetworkProxy.staticcall(hex"f851a440");
require(success);
return abi.decode(returndata, (address));
}
/**
* @notice Set new admin for EdenNetwork proxy contract
* @param newAdmin new admin address
*/
function setProxyAdmin(
address newAdmin
) external onlyAdmin {
// bytes4(keccak256("changeAdmin(address)")) = 0x8f283970
(bool success, ) = edenNetworkProxy.call(abi.encodeWithSelector(hex"8f283970", newAdmin));
require(success, "setProxyAdmin failed");
}
/**
* @notice Set new implementation for EdenNetwork proxy contract
* @param newImplementation new implementation address
*/
function upgrade(
address newImplementation
) external onlyAdmin {
// bytes4(keccak256("upgradeTo(address)")) = 0x3659cfe6
(bool success, ) = edenNetworkProxy.call(abi.encodeWithSelector(hex"3659cfe6", newImplementation));
require(success, "upgrade failed");
}
/**
* @notice Set new implementation for EdenNetwork proxy contract + call function after
* @param newImplementation new implementation address
* @param data Bytes-encoded function to call
*/
function upgradeAndCall(
address newImplementation,
bytes memory data
) external payable onlyAdmin {
// bytes4(keccak256("upgradeToAndCall(address,bytes)")) = 0x4f1ef286
(bool success, ) = edenNetworkProxy.call{value: msg.value}(abi.encodeWithSelector(hex"4f1ef286", newImplementation, data));
require(success, "upgradeAndCall failed");
}
}
// 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;
}
}
}
|
Set new implementation for EdenNetwork proxy contract newImplementation new implementation address/ bytes4(keccak256("upgradeTo(address)")) = 0x3659cfe6
|
function upgrade(
address newImplementation
) external onlyAdmin {
(bool success, ) = edenNetworkProxy.call(abi.encodeWithSelector(hex"3659cfe6", newImplementation));
require(success, "upgrade failed");
}
| 256,765 |
pragma solidity >=0.6.0;
import "./interfaces/ISmartSwapFactory.sol";
import "./lib/TransferHelper.sol";
import "./interfaces/ISmartSwapExchange.sol";
import "./lib/SmartSwapLibrary.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/IBEP20.sol";
import "./interfaces/IBNB.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract SmartSwapExchange is Ownable {
event TransferOwnership(address owner);
using SafeMath for uint256;
address public immutable factory;
address public immutable WBNB;
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "SmartSwapExchange: EXPIRED");
_;
}
constructor(address _factory, address _WBNB) public {
factory = _factory;
WBNB = _WBNB;
transferOwnership(msg.sender);
}
receive() external payable {
assert(msg.sender == WBNB); // only accept BNB via fallback from the WBNB contract
}
function transferOwnderShipTo(address to) public onlyOwner {
transferOwnership(to);
emit TransferOwnership(msg.sender);
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin
) internal virtual returns (uint256 amountA, uint256 amountB) {
// create the Pool if it doesn't exist yet
if (ISmartSwapFactory(factory).getPool(tokenA, tokenB) == address(0)) {
ISmartSwapFactory(factory).createPool(tokenA, tokenB);
}
(uint256 reserveA, uint256 reserveB) = SmartSwapLibrary.getReserves(
factory,
tokenA,
tokenB
);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint256 amountBOptimal = SmartSwapLibrary.quote(
amountADesired,
reserveA,
reserveB
);
if (amountBOptimal <= amountBDesired) {
require(
amountBOptimal >= amountBMin,
"SmartSwapExchange: INSUFFICIENT_B_AMOUNT"
);
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint256 amountAOptimal = SmartSwapLibrary.quote(
amountBDesired,
reserveB,
reserveA
);
assert(amountAOptimal <= amountADesired);
require(
amountAOptimal >= amountAMin,
"SmartSwapExchange: INSUFFICIENT_A_AMOUNT"
);
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
virtual
ensure(deadline)
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB) = _addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin
);
address pool = SmartSwapLibrary.poolFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pool, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pool, amountB);
liquidity = ISmartSwapPool(pool).mint(to);
}
function addLiquidityBNB(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountBNBMin,
address to,
uint256 deadline
)
external
virtual
payable
ensure(deadline)
returns (
uint256 amountToken,
uint256 amountBNB,
uint256 liquidity
)
{
(amountToken, amountBNB) = _addLiquidity(
token,
WBNB,
amountTokenDesired,
msg.value,
amountTokenMin,
amountBNBMin
);
address pool = SmartSwapLibrary.poolFor(factory, token, WBNB);
TransferHelper.safeTransferFrom(token, msg.sender, pool, amountToken);
IBNB(WBNB).deposit{value: amountBNB}();
assert(IBNB(WBNB).transfer(pool, amountBNB));
liquidity = ISmartSwapPool(pool).mint(to);
// refund dust BNB, if any
if (msg.value > amountBNB)
TransferHelper.safeTransferBNB(msg.sender, msg.value - amountBNB);
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
public
virtual
ensure(deadline)
returns (uint256 amountA, uint256 amountB)
{
address pool = SmartSwapLibrary.poolFor(factory, tokenA, tokenB);
ISmartSwapPool(pool).transferFrom(msg.sender, pool, liquidity); // send liquidity to Pool
(uint256 amount0, uint256 amount1) = ISmartSwapPool(pool).burn(to);
(address token0, ) = SmartSwapLibrary.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(
amountA >= amountAMin,
"SmartSwapExchange: INSUFFICIENT_A_AMOUNT"
);
require(
amountB >= amountBMin,
"SmartSwapExchange: INSUFFICIENT_B_AMOUNT"
);
}
function removeLiquidityBNB(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountBNBMin,
address to,
uint256 deadline
)
public
virtual
ensure(deadline)
returns (uint256 amountToken, uint256 amountBNB)
{
(amountToken, amountBNB) = removeLiquidity(
token,
WBNB,
liquidity,
amountTokenMin,
amountBNBMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IBNB(WBNB).withdraw(amountBNB);
TransferHelper.safeTransferBNB(to, amountBNB);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityBNBSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountBNBMin,
address to,
uint256 deadline
) public virtual ensure(deadline) returns (uint256 amountBNB) {
(, amountBNB) = removeLiquidity(
token,
WBNB,
liquidity,
amountTokenMin,
amountBNBMin,
address(this),
deadline
);
TransferHelper.safeTransfer(
token,
to,
IBEP20(token).balanceOf(address(this))
);
IBNB(WBNB).withdraw(amountBNB);
TransferHelper.safeTransferBNB(to, amountBNB);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first Pool
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SmartSwapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? SmartSwapLibrary.poolFor(factory, output, path[i + 2])
: _to;
ISmartSwapPool(SmartSwapLibrary.poolFor(factory, input, output))
.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) returns (uint256[] memory amounts) {
amounts = SmartSwapLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) returns (uint256[] memory amounts) {
amounts = SmartSwapLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"SmartSwapExchange: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, to);
}
function swapExactBNBForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
payable
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WBNB, "SmartSwapExchange: INVALID_PATH");
amounts = SmartSwapLibrary.getAmountsOut(factory, msg.value, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
IBNB(WBNB).deposit{value: amounts[0]}();
assert(
IBNB(WBNB).transfer(
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
}
function swapTokensForExactBNB(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) returns (uint256[] memory amounts) {
require(
path[path.length - 1] == WBNB,
"SmartSwapExchange: INVALID_PATH"
);
amounts = SmartSwapLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= amountInMax,
"SmartSwapExchange: EXCESSIVE_INPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IBNB(WBNB).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferBNB(to, amounts[amounts.length - 1]);
}
function swapExactTokensForBNB(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) returns (uint256[] memory amounts) {
require(
path[path.length - 1] == WBNB,
"SmartSwapExchange: INVALID_PATH"
);
amounts = SmartSwapLibrary.getAmountsOut(factory, amountIn, path);
require(
amounts[amounts.length - 1] >= amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
);
_swap(amounts, path, address(this));
IBNB(WBNB).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferBNB(to, amounts[amounts.length - 1]);
}
function swapBNBForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
)
external
virtual
payable
ensure(deadline)
returns (uint256[] memory amounts)
{
require(path[0] == WBNB, "SmartSwapExchange: INVALID_PATH");
amounts = SmartSwapLibrary.getAmountsIn(factory, amountOut, path);
require(
amounts[0] <= msg.value,
"SmartSwapExchange: EXCESSIVE_INPUT_AMOUNT"
);
IBNB(WBNB).deposit{value: amounts[0]}();
assert(
IBNB(WBNB).transfer(
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amounts[0]
)
);
_swap(amounts, path, to);
// refund dust BNB, if any
if (msg.value > amounts[0])
TransferHelper.safeTransferBNB(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first Pool
function _swapSupportingFeeOnTransferTokens(
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SmartSwapLibrary.sortTokens(input, output);
ISmartSwapPool pool = ISmartSwapPool(
SmartSwapLibrary.poolFor(factory, input, output)
);
uint256 amountInput;
uint256 amountOutput;
{
// scope to avoid stack too deep errors
(uint256 reserve0, uint256 reserve1, ) = pool.getReserves();
(uint256 reserveInput, uint256 reserveOutput) = input == token0
? (reserve0, reserve1)
: (reserve1, reserve0);
amountInput = IBEP20(input).balanceOf(address(pool)).sub(
reserveInput
);
amountOutput = SmartSwapLibrary.getAmountOut(
amountInput,
reserveInput,
reserveOutput
);
}
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOutput)
: (amountOutput, uint256(0));
address to = i < path.length - 2
? SmartSwapLibrary.poolFor(factory, output, path[i + 2])
: _to;
pool.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amountIn
);
uint256 balanceBefore = IBEP20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IBEP20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >=
amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactBNBForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual payable ensure(deadline) {
require(path[0] == WBNB, "SmartSwapExchange: INVALID_PATH");
uint256 amountIn = msg.value;
IBNB(WBNB).deposit{value: amountIn}();
assert(
IBNB(WBNB).transfer(
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amountIn
)
);
uint256 balanceBefore = IBEP20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IBEP20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >=
amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
}
function swapExactTokensForBNBSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external virtual ensure(deadline) {
require(
path[path.length - 1] == WBNB,
"SmartSwapExchange: INVALID_PATH"
);
TransferHelper.safeTransferFrom(
path[0],
msg.sender,
SmartSwapLibrary.poolFor(factory, path[0], path[1]),
amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint256 amountOut = IBEP20(WBNB).balanceOf(address(this));
require(
amountOut >= amountOutMin,
"SmartSwapExchange: INSUFFICIENT_OUTPUT_AMOUNT"
);
IBNB(WBNB).withdraw(amountOut);
TransferHelper.safeTransferBNB(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) public virtual pure returns (uint256 amountB) {
return SmartSwapLibrary.quote(amountA, reserveA, reserveB);
}
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) public virtual pure returns (uint256 amountOut) {
return SmartSwapLibrary.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) public virtual pure returns (uint256 amountIn) {
return SmartSwapLibrary.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint256 amountIn, address[] memory path)
public
virtual
view
returns (uint256[] memory amounts)
{
return SmartSwapLibrary.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint256 amountOut, address[] memory path)
public
virtual
view
returns (uint256[] memory amounts)
{
return SmartSwapLibrary.getAmountsIn(factory, amountOut, path);
}
}
|
SWAP requires the initial amount to have already been sent to the first Pool
|
function _swap(
uint256[] memory amounts,
address[] memory path,
address _to
) internal virtual {
for (uint256 i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0, ) = SmartSwapLibrary.sortTokens(input, output);
uint256 amountOut = amounts[i + 1];
(uint256 amount0Out, uint256 amount1Out) = input == token0
? (uint256(0), amountOut)
: (amountOut, uint256(0));
address to = i < path.length - 2
? SmartSwapLibrary.poolFor(factory, output, path[i + 2])
: _to;
ISmartSwapPool(SmartSwapLibrary.poolFor(factory, input, output))
.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
| 6,417,716 |
pragma solidity ^0.4.21;
/// @title PatientRecords
/// @author Nicolas Frega - <[email protected]>
/// Allows Medical Record System to maintain records of patients in their network.
/// Records can be accessed by Hospitals if and only if patient provides name.
/// Patients are rewarded with erc20 tokens for providing their name
import "./InterfacePatientRecords.sol";
import "./SpringToken.sol";
import "./TokenDestructible.sol";
import "./SafeMath.sol";
contract PatientRecords is InterfacePatientRecords, TokenDestructible {
using SafeMath for uint256;
/*
* Events
*/
event Deposit(address indexed sender, uint256 value);
event HospitalAddition(address hospital);
event HospitalRemoval(address hospital);
event PatientAddition(address patient);
event PatientRemoval(address patient);
event PatientRecordAdded(uint256 recordID, address patientAddress);
event NameAddedToRecords(uint256 recordID, address patientAddress);
event TokenRewardSet(uint256 tokenReward);
event PatientPaid(address patientAddress);
/*
* Constans
*/
uint constant public MAX_COUNT = 50;
/*
* Storage
*/
SpringToken public springToken;
mapping (address => bool) public isPatient;
mapping (address => bool) public isHospital;
mapping (uint256 => mapping (address => Records)) records;
mapping (uint256 => dateRange) dateRanges;
mapping (address => mapping (string => uint256)) mappingByName;
uint256 public recordCount = 0;
uint256 public tokenRewardAmount;
address public tokenAddress;
struct Records {
bool providedName;
string name;
address patient;
address hospital;
uint256 admissionDate;
uint256 dischargeDate;
uint256 visitReason;
}
struct dateRange {
uint256 admissionDate;
uint256 dischargeDate;
}
/*
* Modifiers
*/
modifier validParameters(uint count) {
require(count <= MAX_COUNT && count != 0);
_;
}
modifier hospitalDoesNotExist(address hospital) {
require(!isHospital[hospital]);
_;
}
modifier hospitalExist(address hospital) {
require(isHospital[hospital]);
_;
}
modifier patientDoesNotExist(address patient) {
require(!isPatient[patient]);
_;
}
modifier patientExist(address patient) {
require(isPatient[patient]);
_;
}
modifier notNull(address _address) {
require(_address != 0);
_;
}
modifier notEmpty(string name) {
bytes memory tempString = bytes(name);
require(tempString.length != 0);
_;
}
modifier onlyPatient(uint256 recordId) {
require(records[recordId][msg.sender].patient == msg.sender);
_;
}
modifier onlyHospital(uint256 recordId, address _patientAddress) {
require(records[recordId][_patientAddress].hospital == msg.sender);
_;
}
modifier recordExists(uint256 recordId, address patientAddress) {
address _hospital = records[recordId][patientAddress].hospital;
require(_hospital != 0x0);
_;
}
modifier patientProvidedName(uint256 recordId, address patient) {
require(records[recordId][patient].providedName == true);
_;
}
modifier patientNotProvidedName(uint256 recordId, address patient) {
require(records[recordId][patient].providedName == false);
_;
}
modifier higherThanZero(uint256 _uint) {
require(_uint > 0);
_;
}
/// @dev Fallback function allows to deposit ether.
function()
public
payable
{
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial hospitals and patients.
/// @param _hospitals Address array of initial hospitals.
/// @param _patients Address array of initial patients
constructor(address[] _hospitals, address[] _patients)
public
validParameters(_hospitals.length)
validParameters(_patients.length)
{
uint i;
for (i = 0; i < _hospitals.length; i++) {
require(_hospitals[i] != 0x0);
isHospital[_hospitals[i]] = true;
}
for (i = 0; i < _patients.length; i++) {
require(!isHospital[_patients[i]]);
require(_patients[i] != 0x0);
isPatient[_patients[i]] = true;
}
setSpringToken(new SpringToken());
uint256 initialReward = 1000;
setSpringTokenReward(initialReward);
}
/// @dev Allows to add a new hospital in the network.
/// @param _hospital Address of new hospital.
function addHospital(address _hospital)
public
onlyOwner
hospitalDoesNotExist(_hospital)
patientDoesNotExist(_hospital)
notNull(_hospital)
{
isHospital[_hospital] = true;
emit HospitalAddition(_hospital);
}
/// @dev Allows to remove a hospital in the network.
/// @param _hospital Address of hospital to remove.
function removeHospital(address _hospital)
public
onlyOwner
hospitalExist(_hospital)
{
isHospital[_hospital] = false;
emit HospitalRemoval(_hospital);
}
/// @dev Allows to add a new patient in the network.
/// @param _patient Address of new patient.
function addPatient(address _patient)
public
onlyOwner
patientDoesNotExist(_patient)
hospitalDoesNotExist(_patient)
notNull(_patient)
{
isPatient[_patient] = true;
emit PatientAddition(_patient);
}
/// @dev Allows to remove a patient in the network.
/// @param _patient Address of patient to remove.
function removePatient(address _patient)
public
onlyOwner
patientExist(_patient)
{
isPatient[_patient] = false;
emit PatientRemoval(_patient);
}
/// @dev Allows to add a patient record in the network.
/// @param _patientAddress address of the patient for record.
/// @param _hospital address of the hospital for record.
/// @param _admissionDate date of admission, simple uint.
/// @param _dischargeDate date of discharge, simple uint.
/// @param _visitReason internal code for reason for visit.
function addRecord (
address _patientAddress,
address _hospital,
uint256 _admissionDate,
uint256 _dischargeDate,
uint256 _visitReason)
public
onlyOwner
patientExist(_patientAddress)
hospitalExist(_hospital)
{
records[recordCount][_patientAddress].providedName = false;
records[recordCount][_patientAddress].patient = _patientAddress;
records[recordCount][_patientAddress].hospital = _hospital;
records[recordCount][_patientAddress].admissionDate = _admissionDate;
records[recordCount][_patientAddress].dischargeDate = _dischargeDate;
records[recordCount][_patientAddress].visitReason = _visitReason;
dateRanges[recordCount].admissionDate = _admissionDate;
dateRanges[recordCount].dischargeDate = _dischargeDate;
emit PatientRecordAdded(recordCount, _patientAddress);
recordCount += 1;
}
/// @dev Allows a patient to add their name to the record in the network.
/// @param _recordID ID of the patient specific record.
/// @param _name Name for the patient
function addName(uint256 _recordID, string _name)
public
patientExist(msg.sender)
onlyPatient(_recordID)
recordExists(_recordID, msg.sender)
notEmpty(_name)
patientNotProvidedName(_recordID, msg.sender)
{
records[_recordID][msg.sender].providedName = true;
records[_recordID][msg.sender].name = _name;
address hostpitalInRecord = records[_recordID][msg.sender].hospital;
mappingByName[hostpitalInRecord][_name] += 1;
payPatient(msg.sender);
emit NameAddedToRecords(_recordID, msg.sender);
}
/// @dev Allows a Hospital to retrieve the record for a patient.
/// @param _recordID ID of the patient specific record.
/// @param _patientAddress address of the patient for record.
function getRecord(uint _recordID, address _patientAddress)
public
recordExists(_recordID, _patientAddress)
patientProvidedName(_recordID, _patientAddress)
onlyHospital(_recordID, _patientAddress)
view
returns (
string _name,
address _hospital,
uint256 _admissionDate,
uint256 _dischargeDate,
uint256 _visitReason
)
{
_name = records[_recordID][_patientAddress].name;
_hospital = records[_recordID][_patientAddress].hospital;
_admissionDate = records[_recordID][_patientAddress].admissionDate;
_dischargeDate = records[_recordID][_patientAddress].dischargeDate;
_visitReason = records[_recordID][_patientAddress].visitReason;
}
/// @dev Allows a Hospital to view the number of records for a patient.
/// @param _name Name for the patient
function getRecordByName(string _name)
public
hospitalExist(msg.sender)
view
returns (uint256 numberOfRecords)
{
if (mappingByName[msg.sender][_name] != 0) {
numberOfRecords = mappingByName[msg.sender][_name];
return numberOfRecords;
}
else
return 0;
}
/// @dev Allows a Hospital to view the number of patients on a given date range.
/// @param from Starting date
/// @param to Ending date
function getCurrentPatients(uint from, uint to)
public
hospitalExist(msg.sender)
view
returns (uint _numberOfPatients)
{
uint i;
_numberOfPatients = 0;
for(i = 0; i < recordCount; i++) {
if(dateRanges[i].admissionDate >= from && dateRanges[i].dischargeDate <= to)
_numberOfPatients += 1;
}
}
/// @dev sets the amount of Spring token rewards for providing name.
/// @param _tokenReward Amount of tokens to reward patient.
function setSpringTokenReward(uint256 _tokenReward)
public
onlyOwner
higherThanZero(_tokenReward)
{
tokenRewardAmount = _tokenReward;
emit TokenRewardSet(_tokenReward);
}
/// @dev gets the balance of patient.
/// @param _patientAddress address of patient.
/// @return Returns patient balance.
function getPatientBalance(address _patientAddress)
public
onlyOwner
view
returns (uint256)
{
return springToken.balanceOf(_patientAddress);
}
/*
* Internal functions
*/
/// @dev sets the patient token reward contract.
/// @param _newspringToken Address of patient token.
function setSpringToken(address _newspringToken)
internal
onlyOwner
notNull(_newspringToken)
{
springToken = SpringToken(_newspringToken);
tokenAddress = address(springToken);
}
/// @dev pays a patient for providing their name.
/// @param _patientAddress to receive tokens.
function payPatient(address _patientAddress)
private
notNull(_patientAddress)
{
springToken.transfer(_patientAddress, tokenRewardAmount);
emit PatientPaid(_patientAddress);
}
}
|
Allows a Hospital to view the number of records for a patient. _name Name for the patient
|
function getRecordByName(string _name)
public
hospitalExist(msg.sender)
view
returns (uint256 numberOfRecords)
{
if (mappingByName[msg.sender][_name] != 0) {
numberOfRecords = mappingByName[msg.sender][_name];
return numberOfRecords;
}
else
return 0;
}
| 5,404,520 |
./partial_match/4/0x9b4aCeB68B760b035826a270ebD02DB391Ce0e65/sources/Agreement.sol
|
Tell whether an action can proceed to another state. An action can proceed if it is: - Not closed - Not currently challenged or disputed, and - Not already settled or had a dispute rule in favour of the challenger (the action will have been closed automatically) _action Action instance return True if the action can proceed, false otherwise/ If the action was already closed, return false If the action has not been challenged yet, return true
|
function _canProceed(Action storage _action) internal view returns (bool) {
if (_action.closed) {
return false;
}
uint256 challengeId = _action.lastChallengeId;
if (!_existChallenge(challengeId)) {
return true;
}
ChallengeState state = challenge.state;
return state == ChallengeState.Rejected || state == ChallengeState.Voided;
}
| 8,724,952 |
//SPDX-License-Identifier: Unlicense
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
contract AirdropPush {
using SafeERC20 for IERC20;
function distribute(
IERC20 token,
address[] calldata accounts,
uint256[] calldata amounts
) external {
require(accounts.length == amounts.length, "LENGTH_MISMATCH");
for (uint256 i = 0; i < accounts.length; i++) {
token.safeTransferFrom(msg.sender, accounts[i], amounts[i]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@0x/contracts-zero-ex/contracts/src/features/interfaces/INativeOrdersFeature.sol";
import "../interfaces/IWallet.sol";
contract ZeroExTradeWallet is IWallet, Ownable {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
INativeOrdersFeature public zeroExRouter;
address public manager;
EnumerableSet.AddressSet internal tokens;
modifier onlyManager() {
require(msg.sender == manager, "INVALID_MANAGER");
_;
}
constructor(address newRouter, address newManager) public {
require(newRouter != address(0), "INVALID_ROUTER");
require(newManager != address(0), "INVALID_MANAGER");
zeroExRouter = INativeOrdersFeature(newRouter);
manager = newManager;
}
function getTokens() external view returns (address[] memory) {
address[] memory returnData = new address[](tokens.length());
for (uint256 i = 0; i < tokens.length(); i++) {
returnData[i] = tokens.at(i);
}
return returnData;
}
// solhint-disable-next-line no-empty-blocks
function registerAllowedOrderSigner(address signer, bool allowed) external override onlyOwner {
require(signer != address(0), "INVALID_SIGNER");
zeroExRouter.registerAllowedOrderSigner(signer, allowed);
}
function deposit(address[] calldata tokensToAdd, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToAdd.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToAdd[i]).safeTransferFrom(msg.sender, address(this), amounts[i]);
// NOTE: approval must be done after transferFrom; balance is checked in the approval
_approve(IERC20(tokensToAdd[i]));
tokens.add(address(tokensToAdd[i]));
}
}
function withdraw(address[] calldata tokensToWithdraw, uint256[] calldata amounts)
external
override
onlyManager
{
uint256 tokensLength = tokensToWithdraw.length;
uint256 amountsLength = amounts.length;
require(tokensLength > 0, "EMPTY_TOKEN_LIST");
require(tokensLength == amountsLength, "LENGTH_MISMATCH");
for (uint256 i = 0; i < tokensLength; i++) {
IERC20(tokensToWithdraw[i]).safeTransfer(msg.sender, amounts[i]);
if (IERC20(tokensToWithdraw[i]).balanceOf(address(this)) == 0) {
tokens.remove(address(tokensToWithdraw[i]));
}
}
}
function _approve(IERC20 token) internal {
// Approve the zeroExRouter's allowance to max if the allowance ever drops below the balance of the token held
uint256 allowance = token.allowance(address(this), address(zeroExRouter));
if (allowance < token.balanceOf(address(this))) {
if (allowance != 0) {
token.safeApprove(address(zeroExRouter), 0);
}
token.safeApprove(address(zeroExRouter), type(uint256).max);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
import "./INativeOrdersEvents.sol";
/// @dev Feature for interacting with limit orders.
interface INativeOrdersFeature is
INativeOrdersEvents
{
/// @dev Transfers protocol fees from the `FeeCollector` pools into
/// the staking contract.
/// @param poolIds Staking pool IDs
function transferProtocolFeesForPools(bytes32[] calldata poolIds)
external;
/// @dev Fill a limit order. The taker and sender will be the caller.
/// @param order The limit order. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for up to `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token amount to fill this order with.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// the caller.
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
payable
returns (uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order for exactly `takerTokenFillAmount` taker tokens.
/// The taker will be the caller.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount How much taker token to fill this order with.
/// @return makerTokenFilledAmount How much maker token was filled.
function fillOrKillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount
)
external
returns (uint128 makerTokenFilledAmount);
/// @dev Fill a limit order. Internal variant. ETH protocol fees can be
/// attached to this call. Any unspent ETH will be refunded to
/// `msg.sender` (not `sender`).
/// @param order The limit order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @param sender The order sender.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillLimitOrder(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker,
address sender
)
external
payable
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Fill an RFQ order. Internal variant.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @param takerTokenFillAmount Maximum taker token to fill this order with.
/// @param taker The order taker.
/// @return takerTokenFilledAmount How much maker token was filled.
/// @return makerTokenFilledAmount How much maker token was filled.
function _fillRfqOrder(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature,
uint128 takerTokenFillAmount,
address taker
)
external
returns (uint128 takerTokenFilledAmount, uint128 makerTokenFilledAmount);
/// @dev Cancel a single limit order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The limit order.
function cancelLimitOrder(LibNativeOrder.LimitOrder calldata order)
external;
/// @dev Cancel a single RFQ order. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param order The RFQ order.
function cancelRfqOrder(LibNativeOrder.RfqOrder calldata order)
external;
/// @dev Mark what tx.origin addresses are allowed to fill an order that
/// specifies the message sender as its txOrigin.
/// @param origins An array of origin addresses to update.
/// @param allowed True to register, false to unregister.
function registerAllowedRfqOrigins(address[] memory origins, bool allowed)
external;
/// @dev Cancel multiple limit orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The limit orders.
function batchCancelLimitOrders(LibNativeOrder.LimitOrder[] calldata orders)
external;
/// @dev Cancel multiple RFQ orders. The caller must be the maker or a valid order signer.
/// Silently succeeds if the order has already been cancelled.
/// @param orders The RFQ orders.
function batchCancelRfqOrders(LibNativeOrder.RfqOrder[] calldata orders)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all limit orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairLimitOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrders(
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pair with a salt less
/// than the value provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerToken The maker token.
/// @param takerToken The taker token.
/// @param minValidSalt The new minimum valid salt.
function cancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06 makerToken,
IERC20TokenV06 takerToken,
uint256 minValidSalt
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be the maker. Subsequent
/// calls to this function with the same caller and pair require the
/// new salt to be >= the old salt.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrders(
IERC20TokenV06[] calldata makerTokens,
IERC20TokenV06[] calldata takerTokens,
uint256[] calldata minValidSalts
)
external;
/// @dev Cancel all RFQ orders for a given maker and pairs with salts less
/// than the values provided. The caller must be a signer registered to the maker.
/// Subsequent calls to this function with the same maker and pair require the
/// new salt to be >= the old salt.
/// @param maker The maker for which to cancel.
/// @param makerTokens The maker tokens.
/// @param takerTokens The taker tokens.
/// @param minValidSalts The new minimum valid salts.
function batchCancelPairRfqOrdersWithSigner(
address maker,
IERC20TokenV06[] memory makerTokens,
IERC20TokenV06[] memory takerTokens,
uint256[] memory minValidSalts
)
external;
/// @dev Get the order info for a limit order.
/// @param order The limit order.
/// @return orderInfo Info about the order.
function getLimitOrderInfo(LibNativeOrder.LimitOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the order info for an RFQ order.
/// @param order The RFQ order.
/// @return orderInfo Info about the order.
function getRfqOrderInfo(LibNativeOrder.RfqOrder calldata order)
external
view
returns (LibNativeOrder.OrderInfo memory orderInfo);
/// @dev Get the canonical hash of a limit order.
/// @param order The limit order.
/// @return orderHash The order hash.
function getLimitOrderHash(LibNativeOrder.LimitOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the canonical hash of an RFQ order.
/// @param order The RFQ order.
/// @return orderHash The order hash.
function getRfqOrderHash(LibNativeOrder.RfqOrder calldata order)
external
view
returns (bytes32 orderHash);
/// @dev Get the protocol fee multiplier. This should be multiplied by the
/// gas price to arrive at the required protocol fee to fill a native order.
/// @return multiplier The protocol fee multiplier.
function getProtocolFeeMultiplier()
external
view
returns (uint32 multiplier);
/// @dev Get order info, fillable amount, and signature validity for a limit order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The limit order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getLimitOrderRelevantState(
LibNativeOrder.LimitOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Get order info, fillable amount, and signature validity for an RFQ order.
/// Fillable amount is determined using balances and allowances of the maker.
/// @param order The RFQ order.
/// @param signature The order signature.
/// @return orderInfo Info about the order.
/// @return actualFillableTakerTokenAmount How much of the order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValid Whether the signature is valid.
function getRfqOrderRelevantState(
LibNativeOrder.RfqOrder calldata order,
LibSignature.Signature calldata signature
)
external
view
returns (
LibNativeOrder.OrderInfo memory orderInfo,
uint128 actualFillableTakerTokenAmount,
bool isSignatureValid
);
/// @dev Batch version of `getLimitOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getLimitOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The limit orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetLimitOrderRelevantStates(
LibNativeOrder.LimitOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Batch version of `getRfqOrderRelevantState()`, without reverting.
/// Orders that would normally cause `getRfqOrderRelevantState()`
/// to revert will have empty results.
/// @param orders The RFQ orders.
/// @param signatures The order signatures.
/// @return orderInfos Info about the orders.
/// @return actualFillableTakerTokenAmounts How much of each order is fillable
/// based on maker funds, in taker tokens.
/// @return isSignatureValids Whether each signature is valid for the order.
function batchGetRfqOrderRelevantStates(
LibNativeOrder.RfqOrder[] calldata orders,
LibSignature.Signature[] calldata signatures
)
external
view
returns (
LibNativeOrder.OrderInfo[] memory orderInfos,
uint128[] memory actualFillableTakerTokenAmounts,
bool[] memory isSignatureValids
);
/// @dev Register a signer who can sign on behalf of msg.sender
/// This allows one to sign on behalf of a contract that calls this function
/// @param signer The address from which you plan to generate signatures
/// @param allowed True to register, false to unregister.
function registerAllowedOrderSigner(
address signer,
bool allowed
)
external;
/// @dev checks if a given address is registered to sign on behalf of a maker address
/// @param maker The maker address encoded in an order (can be a contract)
/// @param signer The address that is providing a signature
function isValidOrderSigner(
address maker,
address signer
)
external
view
returns (bool isAllowed);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IWallet {
function registerAllowedOrderSigner(address signer, bool allowed) external;
function deposit(address[] calldata tokens, uint256[] calldata amounts) external;
function withdraw(address[] calldata tokens, uint256[] calldata amounts) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
interface IERC20TokenV06 {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address to, uint256 value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param from The address of the sender
/// @param to The address of the recipient
/// @param value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (bool);
/// @dev `msg.sender` approves `spender` to spend `value` tokens
/// @param spender The address of the account able to transfer the tokens
/// @param value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address spender, uint256 value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @dev Get the balance of `owner`.
/// @param owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address owner)
external
view
returns (uint256);
/// @dev Get the allowance for `spender` to spend from `owner`.
/// @param owner The address of the account owning tokens
/// @param spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address owner, address spender)
external
view
returns (uint256);
/// @dev Get the number of decimals this token has.
function decimals()
external
view
returns (uint8);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "../../errors/LibSignatureRichErrors.sol";
/// @dev A library for validating signatures.
library LibSignature {
using LibRichErrorsV06 for bytes;
// '\x19Ethereum Signed Message:\n32\x00\x00\x00\x00' in a word.
uint256 private constant ETH_SIGN_HASH_PREFIX =
0x19457468657265756d205369676e6564204d6573736167653a0a333200000000;
/// @dev Exclusive upper limit on ECDSA signatures 'R' values.
/// The valid range is given by fig (282) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_R_LIMIT =
uint256(0xfffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141);
/// @dev Exclusive upper limit on ECDSA signatures 'S' values.
/// The valid range is given by fig (283) of the yellow paper.
uint256 private constant ECDSA_SIGNATURE_S_LIMIT = ECDSA_SIGNATURE_R_LIMIT / 2 + 1;
/// @dev Allowed signature types.
enum SignatureType {
ILLEGAL,
INVALID,
EIP712,
ETHSIGN
}
/// @dev Encoded EC signature.
struct Signature {
// How to validate the signature.
SignatureType signatureType;
// EC Signature data.
uint8 v;
// EC Signature data.
bytes32 r;
// EC Signature data.
bytes32 s;
}
/// @dev Retrieve the signer of a signature.
/// Throws if the signature can't be validated.
/// @param hash The hash that was signed.
/// @param signature The signature.
/// @return recovered The recovered signer address.
function getSignerOfHash(
bytes32 hash,
Signature memory signature
)
internal
pure
returns (address recovered)
{
// Ensure this is a signature type that can be validated against a hash.
_validateHashCompatibleSignature(hash, signature);
if (signature.signatureType == SignatureType.EIP712) {
// Signed using EIP712
recovered = ecrecover(
hash,
signature.v,
signature.r,
signature.s
);
} else if (signature.signatureType == SignatureType.ETHSIGN) {
// Signed using `eth_sign`
// Need to hash `hash` with "\x19Ethereum Signed Message:\n32" prefix
// in packed encoding.
bytes32 ethSignHash;
assembly {
// Use scratch space
mstore(0, ETH_SIGN_HASH_PREFIX) // length of 28 bytes
mstore(28, hash) // length of 32 bytes
ethSignHash := keccak256(0, 60)
}
recovered = ecrecover(
ethSignHash,
signature.v,
signature.r,
signature.s
);
}
// `recovered` can be null if the signature values are out of range.
if (recovered == address(0)) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
}
/// @dev Validates that a signature is compatible with a hash signee.
/// @param hash The hash that was signed.
/// @param signature The signature.
function _validateHashCompatibleSignature(
bytes32 hash,
Signature memory signature
)
private
pure
{
// Ensure the r and s are within malleability limits.
if (uint256(signature.r) >= ECDSA_SIGNATURE_R_LIMIT ||
uint256(signature.s) >= ECDSA_SIGNATURE_S_LIMIT)
{
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.BAD_SIGNATURE_DATA,
hash
).rrevert();
}
// Always illegal signature.
if (signature.signatureType == SignatureType.ILLEGAL) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ILLEGAL,
hash
).rrevert();
}
// Always invalid.
if (signature.signatureType == SignatureType.INVALID) {
LibSignatureRichErrors.SignatureValidationError(
LibSignatureRichErrors.SignatureValidationErrorCodes.ALWAYS_INVALID,
hash
).rrevert();
}
// Solidity should check that the signature type is within enum range for us
// when abi-decoding.
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "@0x/contracts-utils/contracts/src/v06/errors/LibRichErrorsV06.sol";
import "@0x/contracts-utils/contracts/src/v06/LibSafeMathV06.sol";
import "../../errors/LibNativeOrdersRichErrors.sol";
/// @dev A library for common native order operations.
library LibNativeOrder {
using LibSafeMathV06 for uint256;
using LibRichErrorsV06 for bytes;
enum OrderStatus {
INVALID,
FILLABLE,
FILLED,
CANCELLED,
EXPIRED
}
/// @dev A standard OTC or OO limit order.
struct LimitOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
uint128 takerTokenFeeAmount;
address maker;
address taker;
address sender;
address feeRecipient;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An RFQ limit order.
struct RfqOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
bytes32 pool;
uint64 expiry;
uint256 salt;
}
/// @dev An OTC limit order.
struct OtcOrder {
IERC20TokenV06 makerToken;
IERC20TokenV06 takerToken;
uint128 makerAmount;
uint128 takerAmount;
address maker;
address taker;
address txOrigin;
uint256 expiryAndNonce; // [uint64 expiry, uint64 nonceBucket, uint128 nonce]
}
/// @dev Info on a limit or RFQ order.
struct OrderInfo {
bytes32 orderHash;
OrderStatus status;
uint128 takerTokenFilledAmount;
}
/// @dev Info on an OTC order.
struct OtcOrderInfo {
bytes32 orderHash;
OrderStatus status;
}
uint256 private constant UINT_128_MASK = (1 << 128) - 1;
uint256 private constant UINT_64_MASK = (1 << 64) - 1;
uint256 private constant ADDRESS_MASK = (1 << 160) - 1;
// The type hash for limit orders, which is:
// keccak256(abi.encodePacked(
// "LimitOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "uint128 takerTokenFeeAmount,",
// "address maker,",
// "address taker,",
// "address sender,",
// "address feeRecipient,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _LIMIT_ORDER_TYPEHASH =
0xce918627cb55462ddbb85e73de69a8b322f2bc88f4507c52fcad6d4c33c29d49;
// The type hash for RFQ orders, which is:
// keccak256(abi.encodePacked(
// "RfqOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "bytes32 pool,",
// "uint64 expiry,",
// "uint256 salt"
// ")"
// ))
uint256 private constant _RFQ_ORDER_TYPEHASH =
0xe593d3fdfa8b60e5e17a1b2204662ecbe15c23f2084b9ad5bae40359540a7da9;
// The type hash for OTC orders, which is:
// keccak256(abi.encodePacked(
// "OtcOrder(",
// "address makerToken,",
// "address takerToken,",
// "uint128 makerAmount,",
// "uint128 takerAmount,",
// "address maker,",
// "address taker,",
// "address txOrigin,",
// "uint256 expiryAndNonce"
// ")"
// ))
uint256 private constant _OTC_ORDER_TYPEHASH =
0x2f754524de756ae72459efbe1ec88c19a745639821de528ac3fb88f9e65e35c8;
/// @dev Get the struct hash of a limit order.
/// @param order The limit order.
/// @return structHash The struct hash of the order.
function getLimitOrderStructHash(LimitOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.takerTokenFeeAmount,
// order.maker,
// order.taker,
// order.sender,
// order.feeRecipient,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _LIMIT_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.takerTokenFeeAmount;
mstore(add(mem, 0xA0), and(UINT_128_MASK, mload(add(order, 0x80))))
// order.maker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.taker;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.sender;
mstore(add(mem, 0x100), and(ADDRESS_MASK, mload(add(order, 0xE0))))
// order.feeRecipient;
mstore(add(mem, 0x120), and(ADDRESS_MASK, mload(add(order, 0x100))))
// order.pool;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
// order.expiry;
mstore(add(mem, 0x160), and(UINT_64_MASK, mload(add(order, 0x140))))
// order.salt;
mstore(add(mem, 0x180), mload(add(order, 0x160)))
structHash := keccak256(mem, 0x1A0)
}
}
/// @dev Get the struct hash of a RFQ order.
/// @param order The RFQ order.
/// @return structHash The struct hash of the order.
function getRfqOrderStructHash(RfqOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.pool,
// order.expiry,
// order.salt,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _RFQ_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.pool;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
// order.expiry;
mstore(add(mem, 0x120), and(UINT_64_MASK, mload(add(order, 0x100))))
// order.salt;
mstore(add(mem, 0x140), mload(add(order, 0x120)))
structHash := keccak256(mem, 0x160)
}
}
/// @dev Get the struct hash of an OTC order.
/// @param order The OTC order.
/// @return structHash The struct hash of the order.
function getOtcOrderStructHash(OtcOrder memory order)
internal
pure
returns (bytes32 structHash)
{
// The struct hash is:
// keccak256(abi.encode(
// TYPE_HASH,
// order.makerToken,
// order.takerToken,
// order.makerAmount,
// order.takerAmount,
// order.maker,
// order.taker,
// order.txOrigin,
// order.expiryAndNonce,
// ))
assembly {
let mem := mload(0x40)
mstore(mem, _OTC_ORDER_TYPEHASH)
// order.makerToken;
mstore(add(mem, 0x20), and(ADDRESS_MASK, mload(order)))
// order.takerToken;
mstore(add(mem, 0x40), and(ADDRESS_MASK, mload(add(order, 0x20))))
// order.makerAmount;
mstore(add(mem, 0x60), and(UINT_128_MASK, mload(add(order, 0x40))))
// order.takerAmount;
mstore(add(mem, 0x80), and(UINT_128_MASK, mload(add(order, 0x60))))
// order.maker;
mstore(add(mem, 0xA0), and(ADDRESS_MASK, mload(add(order, 0x80))))
// order.taker;
mstore(add(mem, 0xC0), and(ADDRESS_MASK, mload(add(order, 0xA0))))
// order.txOrigin;
mstore(add(mem, 0xE0), and(ADDRESS_MASK, mload(add(order, 0xC0))))
// order.expiryAndNonce;
mstore(add(mem, 0x100), mload(add(order, 0xE0)))
structHash := keccak256(mem, 0x120)
}
}
/// @dev Refund any leftover protocol fees in `msg.value` to `msg.sender`.
/// @param ethProtocolFeePaid How much ETH was paid in protocol fees.
function refundExcessProtocolFeeToSender(uint256 ethProtocolFeePaid)
internal
{
if (msg.value > ethProtocolFeePaid && msg.sender != address(this)) {
uint256 refundAmount = msg.value.safeSub(ethProtocolFeePaid);
(bool success,) = msg
.sender
.call{value: refundAmount}("");
if (!success) {
LibNativeOrdersRichErrors.ProtocolFeeRefundFailed(
msg.sender,
refundAmount
).rrevert();
}
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2021 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
pragma experimental ABIEncoderV2;
import "@0x/contracts-erc20/contracts/src/v06/IERC20TokenV06.sol";
import "../libs/LibSignature.sol";
import "../libs/LibNativeOrder.sol";
/// @dev Events emitted by NativeOrdersFeature.
interface INativeOrdersEvents {
/// @dev Emitted whenever a `LimitOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param feeRecipient Fee recipient of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param protocolFeePaid How much protocol fee was paid.
/// @param pool The fee pool associated with this order.
event LimitOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address feeRecipient,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
uint128 takerTokenFeeFilledAmount,
uint256 protocolFeePaid,
bytes32 pool
);
/// @dev Emitted whenever an `RfqOrder` is filled.
/// @param orderHash The canonical hash of the order.
/// @param maker The maker of the order.
/// @param taker The taker of the order.
/// @param takerTokenFilledAmount How much taker token was filled.
/// @param makerTokenFilledAmount How much maker token was filled.
/// @param pool The fee pool associated with this order.
event RfqOrderFilled(
bytes32 orderHash,
address maker,
address taker,
address makerToken,
address takerToken,
uint128 takerTokenFilledAmount,
uint128 makerTokenFilledAmount,
bytes32 pool
);
/// @dev Emitted whenever a limit or RFQ order is cancelled.
/// @param orderHash The canonical hash of the order.
/// @param maker The order maker.
event OrderCancelled(
bytes32 orderHash,
address maker
);
/// @dev Emitted whenever Limit orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledLimitOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted whenever RFQ orders are cancelled by pair by a maker.
/// @param maker The maker of the order.
/// @param makerToken The maker token in a pair for the orders cancelled.
/// @param takerToken The taker token in a pair for the orders cancelled.
/// @param minValidSalt The new minimum valid salt an order with this pair must
/// have.
event PairCancelledRfqOrders(
address maker,
address makerToken,
address takerToken,
uint256 minValidSalt
);
/// @dev Emitted when new addresses are allowed or disallowed to fill
/// orders with a given txOrigin.
/// @param origin The address doing the allowing.
/// @param addrs The address being allowed/disallowed.
/// @param allowed Indicates whether the address should be allowed.
event RfqOrderOriginsAllowed(
address origin,
address[] addrs,
bool allowed
);
/// @dev Emitted when new order signers are registered
/// @param maker The maker address that is registering a designated signer.
/// @param signer The address that will sign on behalf of maker.
/// @param allowed Indicates whether the address should be allowed.
event OrderSignerRegistered(
address maker,
address signer,
bool allowed
);
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibRichErrorsV06 {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR = 0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(string memory message)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSignatureRichErrors {
enum SignatureValidationErrorCodes {
ALWAYS_INVALID,
INVALID_LENGTH,
UNSUPPORTED,
ILLEGAL,
WRONG_SIGNER,
BAD_SIGNATURE_DATA
}
// solhint-disable func-name-mixedcase
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash,
address signerAddress,
bytes memory signature
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32,address,bytes)")),
code,
hash,
signerAddress,
signature
);
}
function SignatureValidationError(
SignatureValidationErrorCodes code,
bytes32 hash
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("SignatureValidationError(uint8,bytes32)")),
code,
hash
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
import "./errors/LibRichErrorsV06.sol";
import "./errors/LibSafeMathRichErrorsV06.sol";
library LibSafeMathV06 {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
function safeMul128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (a == 0) {
return 0;
}
uint128 c = a * b;
if (c / a != b) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b == 0) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint128 c = a / b;
return c;
}
function safeSub128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
if (b > a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
uint128 c = a + b;
if (c < a) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256BinOpError(
LibSafeMathRichErrorsV06.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a >= b ? a : b;
}
function min128(uint128 a, uint128 b)
internal
pure
returns (uint128)
{
return a < b ? a : b;
}
function safeDowncastToUint128(uint256 a)
internal
pure
returns (uint128)
{
if (a > type(uint128).max) {
LibRichErrorsV06.rrevert(LibSafeMathRichErrorsV06.Uint256DowncastError(
LibSafeMathRichErrorsV06.DowncastErrorCodes.VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128,
a
));
}
return uint128(a);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibNativeOrdersRichErrors {
// solhint-disable func-name-mixedcase
function ProtocolFeeRefundFailed(
address receiver,
uint256 refundAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("ProtocolFeeRefundFailed(address,uint256)")),
receiver,
refundAmount
);
}
function OrderNotFillableByOriginError(
bytes32 orderHash,
address txOrigin,
address orderTxOrigin
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByOriginError(bytes32,address,address)")),
orderHash,
txOrigin,
orderTxOrigin
);
}
function OrderNotFillableError(
bytes32 orderHash,
uint8 orderStatus
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableError(bytes32,uint8)")),
orderHash,
orderStatus
);
}
function OrderNotSignedByMakerError(
bytes32 orderHash,
address signer,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByMakerError(bytes32,address,address)")),
orderHash,
signer,
maker
);
}
function OrderNotSignedByTakerError(
bytes32 orderHash,
address signer,
address taker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotSignedByTakerError(bytes32,address,address)")),
orderHash,
signer,
taker
);
}
function InvalidSignerError(
address maker,
address signer
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("InvalidSignerError(address,address)")),
maker,
signer
);
}
function OrderNotFillableBySenderError(
bytes32 orderHash,
address sender,
address orderSender
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableBySenderError(bytes32,address,address)")),
orderHash,
sender,
orderSender
);
}
function OrderNotFillableByTakerError(
bytes32 orderHash,
address taker,
address orderTaker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OrderNotFillableByTakerError(bytes32,address,address)")),
orderHash,
taker,
orderTaker
);
}
function CancelSaltTooLowError(
uint256 minValidSalt,
uint256 oldMinValidSalt
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("CancelSaltTooLowError(uint256,uint256)")),
minValidSalt,
oldMinValidSalt
);
}
function FillOrKillFailedError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("FillOrKillFailedError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
function OnlyOrderMakerAllowed(
bytes32 orderHash,
address sender,
address maker
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("OnlyOrderMakerAllowed(bytes32,address,address)")),
orderHash,
sender,
maker
);
}
function BatchFillIncompleteError(
bytes32 orderHash,
uint256 takerTokenFilledAmount,
uint256 takerTokenFillAmount
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
bytes4(keccak256("BatchFillIncompleteError(bytes32,uint256,uint256)")),
orderHash,
takerTokenFilledAmount,
takerTokenFillAmount
);
}
}
// SPDX-License-Identifier: Apache-2.0
/*
Copyright 2020 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.6.5;
library LibSafeMathRichErrorsV06 {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT128
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/IWallet.sol";
contract ZeroExController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line
IWallet public immutable WALLET;
constructor(IWallet wallet) public {
require(address(wallet) != address(0), "INVALID_WALLET");
WALLET = wallet;
}
function deploy(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
uint256 tokensLength = tokens.length;
for (uint256 i = 0; i < tokensLength; i++) {
_approve(IERC20(tokens[i]), amounts[i]);
}
WALLET.deposit(tokens, amounts);
}
function withdraw(bytes calldata data) external {
(address[] memory tokens, uint256[] memory amounts) = abi.decode(
data,
(address[], uint256[])
);
WALLET.withdraw(tokens, amounts);
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(WALLET));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(address(WALLET), type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IManager.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {AccessControlUpgradeable as AccessControl} from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
contract Manager is IManager, Initializable, AccessControl {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableSet for EnumerableSet.Bytes32Set;
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
bytes32 public constant ROLLOVER_ROLE = keccak256("ROLLOVER_ROLE");
bytes32 public constant MID_CYCLE_ROLE = keccak256("MID_CYCLE_ROLE");
uint256 public currentCycle;
uint256 public currentCycleIndex;
uint256 public cycleDuration;
bool public rolloverStarted;
mapping(bytes32 => address) public registeredControllers;
mapping(uint256 => string) public override cycleRewardsHashes;
EnumerableSet.AddressSet private pools;
EnumerableSet.Bytes32Set private controllerIds;
modifier onlyAdmin() {
require(hasRole(ADMIN_ROLE, _msgSender()), "NOT_ADMIN_ROLE");
_;
}
modifier onlyRollover() {
require(hasRole(ROLLOVER_ROLE, _msgSender()), "NOT_ROLLOVER_ROLE");
_;
}
modifier onlyMidCycle() {
require(hasRole(MID_CYCLE_ROLE, _msgSender()), "NOT_MID_CYCLE_ROLE");
_;
}
function initialize(uint256 _cycleDuration) public initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
cycleDuration = _cycleDuration;
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(ADMIN_ROLE, _msgSender());
_setupRole(ROLLOVER_ROLE, _msgSender());
_setupRole(MID_CYCLE_ROLE, _msgSender());
}
function registerController(bytes32 id, address controller) external override onlyAdmin {
require(!controllerIds.contains(id), "CONTROLLER_EXISTS");
registeredControllers[id] = controller;
controllerIds.add(id);
emit ControllerRegistered(id, controller);
}
function unRegisterController(bytes32 id) external override onlyAdmin {
require(controllerIds.contains(id), "INVALID_CONTROLLER");
emit ControllerUnregistered(id, registeredControllers[id]);
delete registeredControllers[id];
controllerIds.remove(id);
}
function registerPool(address pool) external override onlyAdmin {
require(!pools.contains(pool), "POOL_EXISTS");
pools.add(pool);
emit PoolRegistered(pool);
}
function unRegisterPool(address pool) external override onlyAdmin {
require(pools.contains(pool), "INVALID_POOL");
pools.remove(pool);
emit PoolUnregistered(pool);
}
function setCycleDuration(uint256 duration) external override onlyAdmin {
cycleDuration = duration;
emit CycleDurationSet(duration);
}
function getPools() external view override returns (address[] memory) {
address[] memory returnData = new address[](pools.length());
for (uint256 i = 0; i < pools.length(); i++) {
returnData[i] = pools.at(i);
}
return returnData;
}
function getControllers() external view override returns (bytes32[] memory) {
bytes32[] memory returnData = new bytes32[](controllerIds.length());
for (uint256 i = 0; i < controllerIds.length(); i++) {
returnData[i] = controllerIds.at(i);
}
return returnData;
}
function completeRollover(string calldata rewardsIpfsHash) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
_completeRollover(rewardsIpfsHash);
}
function executeMaintenance(MaintenanceExecution calldata params)
external
override
onlyMidCycle
{
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
}
function executeRollover(RolloverExecution calldata params) external override onlyRollover {
require(block.number > (currentCycle.add(cycleDuration)), "PREMATURE_EXECUTION");
// Transfer deployable liquidity out of the pools and into the manager
for (uint256 i = 0; i < params.poolData.length; i++) {
require(pools.contains(params.poolData[i].pool), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolData[i].pool);
IERC20 underlyingToken = pool.underlyer();
underlyingToken.safeTransferFrom(
address(pool),
address(this),
params.poolData[i].amount
);
emit LiquidityMovedToManager(params.poolData[i].pool, params.poolData[i].amount);
}
// Deploy or withdraw liquidity
for (uint256 x = 0; x < params.cycleSteps.length; x++) {
_executeControllerCommand(params.cycleSteps[x]);
}
// Transfer recovered liquidity back into the pools; leave no funds in the manager
for (uint256 y = 0; y < params.poolsForWithdraw.length; y++) {
require(pools.contains(params.poolsForWithdraw[y]), "INVALID_POOL");
ILiquidityPool pool = ILiquidityPool(params.poolsForWithdraw[y]);
IERC20 underlyingToken = pool.underlyer();
uint256 managerBalance = underlyingToken.balanceOf(address(this));
// transfer funds back to the pool if there are funds
if (managerBalance > 0) {
underlyingToken.safeTransfer(address(pool), managerBalance);
}
emit LiquidityMovedToPool(params.poolsForWithdraw[y], managerBalance);
}
if (params.complete) {
_completeRollover(params.rewardsIpfsHash);
}
}
function _executeControllerCommand(ControllerTransferData calldata transfer) private {
address controllerAddress = registeredControllers[transfer.controllerId];
require(controllerAddress != address(0), "INVALID_CONTROLLER");
controllerAddress.functionDelegateCall(transfer.data, "CYCLE_STEP_EXECUTE_FAILED");
emit DeploymentStepExecuted(transfer.controllerId, controllerAddress, transfer.data);
}
function startCycleRollover() external override onlyRollover {
rolloverStarted = true;
emit CycleRolloverStarted(block.number);
}
function _completeRollover(string calldata rewardsIpfsHash) private {
currentCycle = block.number;
cycleRewardsHashes[currentCycleIndex] = rewardsIpfsHash;
currentCycleIndex = currentCycleIndex.add(1);
rolloverStarted = false;
emit CycleRolloverComplete(block.number);
}
function getCurrentCycle() external view override returns (uint256) {
return currentCycle;
}
function getCycleDuration() external view override returns (uint256) {
return cycleDuration;
}
function getCurrentCycleIndex() external view override returns (uint256) {
return currentCycleIndex;
}
function getRolloverStatus() external view override returns (bool) {
return rolloverStarted;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IManager {
// bytes can take on the form of deploying or recovering liquidity
struct ControllerTransferData {
bytes32 controllerId; // controller to target
bytes data; // data the controller will pass
}
struct PoolTransferData {
address pool; // pool to target
uint256 amount; // amount to transfer
}
struct MaintenanceExecution {
ControllerTransferData[] cycleSteps;
}
struct RolloverExecution {
PoolTransferData[] poolData;
ControllerTransferData[] cycleSteps;
address[] poolsForWithdraw; //Pools to target for manager -> pool transfer
bool complete; //Whether to mark the rollover complete
string rewardsIpfsHash;
}
event ControllerRegistered(bytes32 id, address controller);
event ControllerUnregistered(bytes32 id, address controller);
event PoolRegistered(address pool);
event PoolUnregistered(address pool);
event CycleDurationSet(uint256 duration);
event LiquidityMovedToManager(address pool, uint256 amount);
event DeploymentStepExecuted(bytes32 controller, address adapaterAddress, bytes data);
event LiquidityMovedToPool(address pool, uint256 amount);
event CycleRolloverStarted(uint256 blockNumber);
event CycleRolloverComplete(uint256 blockNumber);
function registerController(bytes32 id, address controller) external;
function registerPool(address pool) external;
function unRegisterController(bytes32 id) external;
function unRegisterPool(address pool) external;
function getPools() external view returns (address[] memory);
function getControllers() external view returns (bytes32[] memory);
function setCycleDuration(uint256 duration) external;
function startCycleRollover() external;
function executeMaintenance(MaintenanceExecution calldata params) external;
function executeRollover(RolloverExecution calldata params) external;
function completeRollover(string calldata rewardsIpfsHash) external;
function cycleRewardsHashes(uint256 index) external view returns (string memory);
function getCurrentCycle() external view returns (uint256);
function getCurrentCycleIndex() external view returns (uint256);
function getCycleDuration() external view returns (uint256);
function getRolloverStatus() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount) external;
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (ERC20Upgradeable);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* 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 {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using AddressUpgradeable for address;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin 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 ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
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_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/IStaking.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {EnumerableSetUpgradeable as EnumerableSet} from "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Staking is IStaking, Initializable, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.UintSet;
IERC20 public tokeToken;
IManager public manager;
address public treasury;
uint256 public withheldLiquidity;
//userAddress -> withdrawalInfo
mapping(address => WithdrawalInfo) public requestedWithdrawals;
//userAddress -> -> scheduleIndex -> staking detail
mapping(address => mapping(uint256 => StakingDetails)) public userStakings;
//userAddress -> scheduleIdx[]
mapping(address => uint256[]) public userStakingSchedules;
//Schedule id/index counter
uint256 public nextScheduleIndex;
//scheduleIndex/id -> schedule
mapping(uint256 => StakingSchedule) public schedules;
//scheduleIndex/id[]
EnumerableSet.UintSet private scheduleIdxs;
//Can deposit into a non-public schedule
mapping(address => bool) public override permissionedDepositors;
modifier onlyPermissionedDepositors() {
require(_isAllowedPermissionedDeposit(), "CALLER_NOT_PERMISSIONED");
_;
}
function initialize(
IERC20 _tokeToken,
IManager _manager,
address _treasury
) public initializer {
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
require(address(_tokeToken) != address(0), "INVALID_TOKETOKEN");
require(address(_manager) != address(0), "INVALID_MANAGER");
require(_treasury != address(0), "INVALID_TREASURY");
tokeToken = _tokeToken;
manager = _manager;
treasury = _treasury;
//We want to be sure the schedule used for LP staking is first
//because the order in which withdraws happen need to start with LP stakes
_addSchedule(
StakingSchedule({
cliff: 0,
duration: 1,
interval: 1,
setup: true,
isActive: true,
hardStart: 0,
isPublic: true
})
);
}
function addSchedule(StakingSchedule memory schedule) external override onlyOwner {
_addSchedule(schedule);
}
function setPermissionedDepositor(address account, bool canDeposit)
external
override
onlyOwner
{
permissionedDepositors[account] = canDeposit;
}
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs)
external
override
onlyOwner
{
userStakingSchedules[account] = userSchedulesIdxs;
}
function getSchedules()
external
view
override
returns (StakingScheduleInfo[] memory retSchedules)
{
uint256 length = scheduleIdxs.length();
retSchedules = new StakingScheduleInfo[](length);
for (uint256 i = 0; i < length; i++) {
retSchedules[i] = StakingScheduleInfo(
schedules[scheduleIdxs.at(i)],
scheduleIdxs.at(i)
);
}
}
function removeSchedule(uint256 scheduleIndex) external override onlyOwner {
require(scheduleIdxs.contains(scheduleIndex), "INVALID_SCHEDULE");
scheduleIdxs.remove(scheduleIndex);
delete schedules[scheduleIndex];
emit ScheduleRemoved(scheduleIndex);
}
function getStakes(address account)
external
view
override
returns (StakingDetails[] memory stakes)
{
stakes = _getStakes(account);
}
function balanceOf(address account) external view override returns (uint256 value) {
value = 0;
uint256 scheduleCount = userStakingSchedules[account].length;
for (uint256 i = 0; i < scheduleCount; i++) {
uint256 remaining = userStakings[account][userStakingSchedules[account][i]].initial.sub(
userStakings[account][userStakingSchedules[account][i]].withdrawn
);
uint256 slashed = userStakings[account][userStakingSchedules[account][i]].slashed;
if (remaining > slashed) {
value = value.add(remaining.sub(slashed));
}
}
}
function availableForWithdrawal(address account, uint256 scheduleIndex)
external
view
override
returns (uint256)
{
return _availableForWithdrawal(account, scheduleIndex);
}
function unvested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
value = stake.initial.sub(_vested(account, scheduleIndex));
}
function vested(address account, uint256 scheduleIndex)
external
view
override
returns (uint256 value)
{
return _vested(account, scheduleIndex);
}
function deposit(uint256 amount, uint256 scheduleIndex) external override {
_depositFor(msg.sender, amount, scheduleIndex);
}
function depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) external override {
_depositFor(account, amount, scheduleIndex);
}
function depositWithSchedule(
address account,
uint256 amount,
StakingSchedule calldata schedule
) external override onlyPermissionedDepositors {
uint256 scheduleIx = nextScheduleIndex;
_addSchedule(schedule);
_depositFor(account, amount, scheduleIx);
}
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 length = stakes.length;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length; i++) {
stakedAvailable = stakedAvailable.add(
_availableForWithdrawal(msg.sender, stakes[i].scheduleIx)
);
}
require(stakedAvailable >= amount, "INSUFFICIENT_AVAILABLE");
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycleIndex = manager.getCurrentCycleIndex().add(1);
}
emit WithdrawalRequested(msg.sender, amount);
}
function withdraw(uint256 amount) external override {
require(amount <= requestedWithdrawals[msg.sender].amount, "WITHDRAW_INSUFFICIENT_BALANCE");
require(amount > 0, "NO_WITHDRAWAL");
require(
requestedWithdrawals[msg.sender].minCycleIndex <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
StakingDetails[] memory stakes = _getStakes(msg.sender);
uint256 available = 0;
uint256 length = stakes.length;
uint256 remainingAmount = amount;
uint256 stakedAvailable = 0;
for (uint256 i = 0; i < length && remainingAmount > 0; i++) {
stakedAvailable = _availableForWithdrawal(msg.sender, stakes[i].scheduleIx);
available = available.add(stakedAvailable);
if (stakedAvailable < remainingAmount) {
remainingAmount = remainingAmount.sub(stakedAvailable);
stakes[i].withdrawn = stakes[i].withdrawn.add(stakedAvailable);
} else {
stakes[i].withdrawn = stakes[i].withdrawn.add(remainingAmount);
remainingAmount = 0;
}
userStakings[msg.sender][stakes[i].scheduleIx] = stakes[i];
}
require(remainingAmount == 0, "INSUFFICIENT_AVAILABLE"); //May not need to check this again
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
amount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(amount);
tokeToken.safeTransfer(msg.sender, amount);
emit WithdrawCompleted(msg.sender, amount);
}
function slash(
address account,
uint256 amount,
uint256 scheduleIndex
) external onlyOwner {
StakingSchedule storage schedule = schedules[scheduleIndex];
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
require(userStake.initial > 0, "NO_VESTING");
uint256 availableToSlash = 0;
uint256 remaining = userStake.initial.sub(userStake.withdrawn);
if (remaining > userStake.slashed) {
availableToSlash = remaining.sub(userStake.slashed);
}
require(availableToSlash >= amount, "INSUFFICIENT_AVAILABLE");
userStake.slashed = userStake.slashed.add(amount);
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransfer(treasury, amount);
emit Slashed(account, amount, scheduleIndex);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _availableForWithdrawal(address account, uint256 scheduleIndex)
private
view
returns (uint256)
{
StakingDetails memory stake = userStakings[account][scheduleIndex];
uint256 vestedWoWithdrawn = _vested(account, scheduleIndex).sub(stake.withdrawn);
if (stake.slashed > vestedWoWithdrawn) return 0;
return vestedWoWithdrawn.sub(stake.slashed);
}
function _depositFor(
address account,
uint256 amount,
uint256 scheduleIndex
) private {
StakingSchedule memory schedule = schedules[scheduleIndex];
require(!paused(), "Pausable: paused");
require(amount > 0, "INVALID_AMOUNT");
require(schedule.setup, "INVALID_SCHEDULE");
require(schedule.isActive, "INACTIVE_SCHEDULE");
require(account != address(0), "INVALID_ADDRESS");
require(schedule.isPublic || _isAllowedPermissionedDeposit(), "PERMISSIONED_SCHEDULE");
StakingDetails memory userStake = userStakings[account][scheduleIndex];
if (userStake.initial == 0) {
userStakingSchedules[account].push(scheduleIndex);
}
userStake.initial = userStake.initial.add(amount);
if (schedule.hardStart > 0) {
userStake.started = schedule.hardStart;
} else {
// solhint-disable-next-line not-rely-on-time
userStake.started = block.timestamp;
}
userStake.scheduleIx = scheduleIndex;
userStakings[account][scheduleIndex] = userStake;
tokeToken.safeTransferFrom(msg.sender, address(this), amount);
emit Deposited(account, amount, scheduleIndex);
}
function _vested(address account, uint256 scheduleIndex) private view returns (uint256) {
// solhint-disable-next-line not-rely-on-time
uint256 timestamp = block.timestamp;
uint256 value = 0;
StakingDetails memory stake = userStakings[account][scheduleIndex];
StakingSchedule memory schedule = schedules[scheduleIndex];
uint256 cliffTimestamp = stake.started.add(schedule.cliff);
if (cliffTimestamp <= timestamp) {
if (cliffTimestamp.add(schedule.duration) <= timestamp) {
value = stake.initial;
} else {
uint256 secondsStaked = Math.max(timestamp.sub(cliffTimestamp), 1);
uint256 effectiveSecondsStaked = (secondsStaked.mul(schedule.interval)).div(
schedule.interval
);
value = stake.initial.mul(effectiveSecondsStaked).div(schedule.duration);
}
}
return value;
}
function _addSchedule(StakingSchedule memory schedule) private {
require(schedule.duration > 0, "INVALID_DURATION");
require(schedule.interval > 0, "INVALID_INTERVAL");
schedule.setup = true;
uint256 index = nextScheduleIndex;
schedules[index] = schedule;
scheduleIdxs.add(index);
nextScheduleIndex = nextScheduleIndex.add(1);
emit ScheduleAdded(
index,
schedule.cliff,
schedule.duration,
schedule.interval,
schedule.setup,
schedule.isActive,
schedule.hardStart
);
}
function _getStakes(address account) private view returns (StakingDetails[] memory stakes) {
uint256 stakeCnt = userStakingSchedules[account].length;
stakes = new StakingDetails[](stakeCnt);
for (uint256 i = 0; i < stakeCnt; i++) {
stakes[i] = userStakings[account][userStakingSchedules[account][i]];
}
}
function _isAllowedPermissionedDeposit() private view returns (bool) {
return permissionedDepositors[msg.sender] || msg.sender == owner();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IStaking {
struct StakingSchedule {
uint256 cliff; // Duration in seconds before staking starts
uint256 duration; // Seconds it takes for entire amount to stake
uint256 interval; // Seconds it takes for a chunk to stake
bool setup; //Just so we know its there
bool isActive; //Whether we can setup new stakes with the schedule
uint256 hardStart; //Stakings will always start at this timestamp if set
bool isPublic; //Schedule can be written to by any account
}
struct StakingScheduleInfo {
StakingSchedule schedule;
uint256 index;
}
struct StakingDetails {
uint256 initial; //Initial amount of asset when stake was created, total amount to be staked before slashing
uint256 withdrawn; //Amount that was staked and subsequently withdrawn
uint256 slashed; //Amount that has been slashed
uint256 started; //Timestamp at which the stake started
uint256 scheduleIx;
}
struct WithdrawalInfo {
uint256 minCycleIndex;
uint256 amount;
}
event ScheduleAdded(uint256 scheduleIndex, uint256 cliff, uint256 duration, uint256 interval, bool setup, bool isActive, uint256 hardStart);
event ScheduleRemoved(uint256 scheduleIndex);
event WithdrawalRequested(address account, uint256 amount);
event WithdrawCompleted(address account, uint256 amount);
event Deposited(address account, uint256 amount, uint256 scheduleIx);
event Slashed(address account, uint256 amount, uint256 scheduleIx);
function permissionedDepositors(address account) external returns (bool);
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external;
function addSchedule(StakingSchedule memory schedule) external;
function getSchedules() external view returns (StakingScheduleInfo[] memory);
function setPermissionedDepositor(address account, bool canDeposit) external;
function removeSchedule(uint256 scheduleIndex) external;
function getStakes(address account) external view returns(StakingDetails[] memory);
function balanceOf(address account) external view returns(uint256);
function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256);
function unvested(address account, uint256 scheduleIndex) external view returns(uint256);
function vested(address account, uint256 scheduleIndex) external view returns(uint256);
function deposit(uint256 amount, uint256 scheduleIndex) external;
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external;
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external;
function requestWithdrawal(uint256 amount) external;
function withdraw(uint256 amount) external;
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library MathUpgradeable {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IManager.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract Pool is ILiquidityPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for ERC20;
ERC20 public override underlyer;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
function initialize(
ERC20 _underlyer,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_underlyer) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
underlyer = _underlyer;
manager = _manager;
}
function decimals() public view override returns (uint8) {
return underlyer.decimals();
}
function deposit(uint256 amount) external override whenNotPaused {
_deposit(msg.sender, msg.sender, amount);
}
function depositFor(address account, uint256 amount) external override whenNotPaused {
_deposit(msg.sender, account, amount);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
/// @dev TODO Update rewardsContract with proper accounting
function withdraw(uint256 requestedAmount) external override whenNotPaused {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(underlyer.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
underlyer.safeTransfer(msg.sender, requestedAmount);
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[sender].amount == 0) {
delete requestedWithdrawals[sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = underlyer.allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
underlyer.safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
underlyer.safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount)
public
override
whenNotPaused
returns (bool)
{
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override whenNotPaused returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
underlyer.safeTransferFrom(fromAccount, address(this), amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/ILiquidityEthPool.sol";
import "../interfaces/IManager.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import {AddressUpgradeable as Address} from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import {MathUpgradeable as Math} from "@openzeppelin/contracts-upgradeable/math/MathUpgradeable.sol";
import {SafeMathUpgradeable as SafeMath} from "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import {OwnableUpgradeable as Ownable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import {ERC20Upgradeable as ERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import {IERC20Upgradeable as IERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import {SafeERC20Upgradeable as SafeERC20} from "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import {PausableUpgradeable as Pausable} from "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
contract EthPool is ILiquidityEthPool, Initializable, ERC20, Ownable, Pausable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
/// @dev TODO: Hardcode addresses, make immuatable, remove from initializer
IWETH public override weth;
IManager public manager;
// implied: deployableLiquidity = underlyer.balanceOf(this) - withheldLiquidity
uint256 public override withheldLiquidity;
// fAsset holder -> WithdrawalInfo
mapping(address => WithdrawalInfo) public override requestedWithdrawals;
/// @dev necessary to receive ETH
// solhint-disable-next-line no-empty-blocks
receive() external payable {}
function initialize(
IWETH _weth,
IManager _manager,
string memory _name,
string memory _symbol
) public initializer {
require(address(_weth) != address(0), "ZERO_ADDRESS");
require(address(_manager) != address(0), "ZERO_ADDRESS");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ERC20_init_unchained(_name, _symbol);
weth = _weth;
manager = _manager;
withheldLiquidity = 0;
}
function deposit(uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, msg.sender, amount, msg.value);
}
function depositFor(address account, uint256 amount) external payable override whenNotPaused {
_deposit(msg.sender, account, amount, msg.value);
}
function underlyer() external view override returns (address) {
return address(weth);
}
/// @dev References the WithdrawalInfo for how much the user is permitted to withdraw
/// @dev No withdrawal permitted unless currentCycle >= minCycle
/// @dev Decrements withheldLiquidity by the withdrawn amount
function withdraw(uint256 requestedAmount, bool asEth) external override whenNotPaused {
require(
requestedAmount <= requestedWithdrawals[msg.sender].amount,
"WITHDRAW_INSUFFICIENT_BALANCE"
);
require(requestedAmount > 0, "NO_WITHDRAWAL");
require(weth.balanceOf(address(this)) >= requestedAmount, "INSUFFICIENT_POOL_BALANCE");
require(
requestedWithdrawals[msg.sender].minCycle <= manager.getCurrentCycleIndex(),
"INVALID_CYCLE"
);
requestedWithdrawals[msg.sender].amount = requestedWithdrawals[msg.sender].amount.sub(
requestedAmount
);
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
withheldLiquidity = withheldLiquidity.sub(requestedAmount);
_burn(msg.sender, requestedAmount);
if (asEth) {
weth.withdraw(requestedAmount);
msg.sender.sendValue(requestedAmount);
} else {
IERC20(weth).safeTransfer(msg.sender, requestedAmount);
}
}
/// @dev Adjusts the withheldLiquidity as necessary
/// @dev Updates the WithdrawalInfo for when a user can withdraw and for what requested amount
function requestWithdrawal(uint256 amount) external override {
require(amount > 0, "INVALID_AMOUNT");
require(amount <= balanceOf(msg.sender), "INSUFFICIENT_BALANCE");
//adjust withheld liquidity by removing the original withheld amount and adding the new amount
withheldLiquidity = withheldLiquidity.sub(requestedWithdrawals[msg.sender].amount).add(
amount
);
requestedWithdrawals[msg.sender].amount = amount;
if (manager.getRolloverStatus()) {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(2);
} else {
requestedWithdrawals[msg.sender].minCycle = manager.getCurrentCycleIndex().add(1);
}
}
function preTransferAdjustWithheldLiquidity(address sender, uint256 amount) internal {
if (requestedWithdrawals[sender].amount > 0) {
//reduce requested withdraw amount by transferred amount;
uint256 newRequestedWithdrawl = requestedWithdrawals[sender].amount.sub(
Math.min(amount, requestedWithdrawals[sender].amount)
);
//subtract from global withheld liquidity (reduce) by removing the delta of (requestedAmount - newRequestedAmount)
withheldLiquidity = withheldLiquidity.sub(
requestedWithdrawals[msg.sender].amount.sub(newRequestedWithdrawl)
);
//update the requested withdraw for user
requestedWithdrawals[msg.sender].amount = newRequestedWithdrawl;
//if the withdraw request is 0, empty it out
if (requestedWithdrawals[msg.sender].amount == 0) {
delete requestedWithdrawals[msg.sender];
}
}
}
function approveManager(uint256 amount) public override onlyOwner {
uint256 currentAllowance = IERC20(weth).allowance(address(this), address(manager));
if (currentAllowance < amount) {
uint256 delta = amount.sub(currentAllowance);
IERC20(weth).safeIncreaseAllowance(address(manager), delta);
} else {
uint256 delta = currentAllowance.sub(amount);
IERC20(weth).safeDecreaseAllowance(address(manager), delta);
}
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transfer(address recipient, uint256 amount) public override returns (bool) {
preTransferAdjustWithheldLiquidity(msg.sender, amount);
return super.transfer(recipient, amount);
}
/// @dev Adjust withheldLiquidity and requestedWithdrawal if sender does not have sufficient unlocked balance for the transfer
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
preTransferAdjustWithheldLiquidity(sender, amount);
return super.transferFrom(sender, recipient, amount);
}
function pause() external override onlyOwner {
_pause();
}
function unpause() external override onlyOwner {
_unpause();
}
function _deposit(
address fromAccount,
address toAccount,
uint256 amount,
uint256 msgValue
) internal {
require(amount > 0, "INVALID_AMOUNT");
require(toAccount != address(0), "INVALID_ADDRESS");
_mint(toAccount, amount);
if (msgValue > 0) {
require(msgValue == amount, "AMT_VALUE_MISMATCH");
weth.deposit{value: amount}();
} else {
IERC20(weth).safeTransferFrom(fromAccount, address(this), amount);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "../interfaces/IWETH.sol";
import "../interfaces/IManager.sol";
/// @title Interface for Pool
/// @notice Allows users to deposit ERC-20 tokens to be deployed to market makers.
/// @notice Mints 1:1 fToken on deposit, represeting an IOU for the undelrying token that is freely transferable.
/// @notice Holders of fTokens earn rewards based on duration their tokens were deployed and the demand for that asset.
/// @notice Holders of fTokens can redeem for underlying asset after issuing requestWithdrawal and waiting for the next cycle.
interface ILiquidityEthPool {
struct WithdrawalInfo {
uint256 minCycle;
uint256 amount;
}
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the msg.sender.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function deposit(uint256 amount) external payable;
/// @notice Transfers amount of underlying token from user to this pool and mints fToken to the account.
/// @notice Depositor must have previously granted transfer approval to the pool via underlying token contract.
/// @notice Liquidity deposited is deployed on the next cycle - unless a withdrawal request is submitted, in which case the liquidity will be withheld.
function depositFor(address account, uint256 amount) external payable;
/// @notice Requests that the manager prepare funds for withdrawal next cycle
/// @notice Invoking this function when sender already has a currently pending request will overwrite that requested amount and reset the cycle timer
/// @param amount Amount of fTokens requested to be redeemed
function requestWithdrawal(uint256 amount) external;
function approveManager(uint256 amount) external;
/// @notice Sender must first invoke requestWithdrawal in a previous cycle
/// @notice This function will burn the fAsset and transfers underlying asset back to sender
/// @notice Will execute a partial withdrawal if either available liquidity or previously requested amount is insufficient
/// @param amount Amount of fTokens to redeem, value can be in excess of available tokens, operation will be reduced to maximum permissible
function withdraw(uint256 amount, bool asEth) external;
/// @return Reference to the underlying ERC-20 contract
function weth() external view returns (IWETH);
/// @return Reference to the underlying ERC-20 contract
function underlyer() external view returns (address);
/// @return Amount of liquidity that should not be deployed for market making (this liquidity will be used for completing requested withdrawals)
function withheldLiquidity() external view returns (uint256);
/// @notice Get withdraw requests for an account
/// @param account User account to check
/// @return minCycle Cycle - block number - that must be active before withdraw is allowed, amount Token amount requested
function requestedWithdrawals(address account) external view returns (uint256, uint256);
/// @notice Pause deposits on the pool. Withdraws still allowed
function pause() external;
/// @notice Unpause deposits on the pool.
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface IWETH is IERC20Upgradeable {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/utils/SafeCast.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorV3Interface.sol";
import "../interfaces/ILiquidityPool.sol";
import "../interfaces/IDefiRound.sol";
import "../interfaces/IWETH.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract DefiRound is IDefiRound, Ownable {
using SafeMath for uint256;
using SafeCast for int256;
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using EnumerableSet for EnumerableSet.AddressSet;
// solhint-disable-next-line
address public immutable WETH;
address public override immutable treasury;
OversubscriptionRate public overSubscriptionRate;
mapping(address => uint256) public override totalSupply;
// account -> accountData
mapping(address => AccountData) private accountData;
mapping(address => RateData) private tokenRates;
//Token -> oracle, genesis
mapping(address => SupportedTokenData) private tokenSettings;
EnumerableSet.AddressSet private supportedTokens;
EnumerableSet.AddressSet private configuredTokenRates;
STAGES public override currentStage;
WhitelistSettings public whitelistSettings;
uint256 public lastLookExpiration = type(uint256).max;
uint256 private immutable maxTotalValue;
bool private stage1Locked;
constructor(
// solhint-disable-next-line
address _WETH,
address _treasury,
uint256 _maxTotalValue
) public {
require(_WETH != address(0), "INVALID_WETH");
require(_treasury != address(0), "INVALID_TREASURY");
require(_maxTotalValue > 0, "INVALID_MAXTOTAL");
WETH = _WETH;
treasury = _treasury;
currentStage = STAGES.STAGE_1;
maxTotalValue = _maxTotalValue;
}
function deposit(TokenData calldata tokenInfo, bytes32[] memory proof) external payable override {
require(currentStage == STAGES.STAGE_1, "DEPOSITS_NOT_ACCEPTED");
require(!stage1Locked, "DEPOSITS_LOCKED");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
// Convert ETH to WETH if ETH is passed in, otherwise treat WETH as a regular ERC20
if (token == WETH && msg.value > 0) {
require(tokenAmount == msg.value, "INVALID_MSG_VALUE");
IWETH(WETH).deposit{value: tokenAmount}();
} else {
require(msg.value == 0, "NO_ETH");
}
AccountData storage tokenAccountData = accountData[msg.sender];
if (tokenAccountData.token == address(0)) {
tokenAccountData.token = token;
}
require(tokenAccountData.token == token, "SINGLE_ASSET_DEPOSITS");
tokenAccountData.initialDeposit = tokenAccountData.initialDeposit.add(tokenAmount);
tokenAccountData.currentBalance = tokenAccountData.currentBalance.add(tokenAmount);
require(tokenAccountData.currentBalance <= tokenSettings[token].maxLimit, "MAX_LIMIT_EXCEEDED");
// No need to transfer from msg.sender since is ETH was converted to WETH
if (!(token == WETH && msg.value > 0)) {
IERC20(token).safeTransferFrom(msg.sender, address(this), tokenAmount);
}
if(_totalValue() > maxTotalValue) {
stage1Locked = true;
}
emit Deposited(msg.sender, tokenInfo);
}
// solhint-disable-next-line no-empty-blocks
receive() external payable
{
require(msg.sender == WETH);
}
function withdraw(TokenData calldata tokenInfo, bool asETH) external override {
require(currentStage == STAGES.STAGE_2, "WITHDRAWS_NOT_ACCEPTED");
require(!_isLastLookComplete(), "WITHDRAWS_EXPIRED");
TokenData memory data = tokenInfo;
address token = data.token;
uint256 tokenAmount = data.amount;
require(supportedTokens.contains(token), "UNSUPPORTED_TOKEN");
require(tokenAmount > 0, "INVALID_AMOUNT");
AccountData storage tokenAccountData = accountData[msg.sender];
require(token == tokenAccountData.token, "INVALID_TOKEN");
tokenAccountData.currentBalance = tokenAccountData.currentBalance.sub(tokenAmount);
// set the data back in the mapping, otherwise updates are not saved
accountData[msg.sender] = tokenAccountData;
// Don't transfer WETH, WETH is converted to ETH and sent to the recipient
if (token == WETH && asETH) {
IWETH(WETH).withdraw(tokenAmount);
msg.sender.sendValue(tokenAmount);
} else {
IERC20(token).safeTransfer(msg.sender, tokenAmount);
}
emit Withdrawn(msg.sender, tokenInfo, asETH);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport)
external
override
onlyOwner
{
uint256 tokensLength = tokensToSupport.length;
for (uint256 i = 0; i < tokensLength; i++) {
SupportedTokenData memory data = tokensToSupport[i];
require(supportedTokens.add(data.token), "TOKEN_EXISTS");
tokenSettings[data.token] = data;
}
emit SupportedTokensAdded(tokensToSupport);
}
function getSupportedTokens() external view override returns (address[] memory tokens) {
uint256 tokensLength = supportedTokens.length();
tokens = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
tokens[i] = supportedTokens.at(i);
}
}
function publishRates(RateData[] calldata ratesData, OversubscriptionRate memory oversubRate, uint256 lastLookDuration) external override onlyOwner {
// check rates havent been published before
require(currentStage == STAGES.STAGE_1, "RATES_ALREADY_SET");
require(lastLookDuration > 0, "INVALID_DURATION");
require(oversubRate.overDenominator > 0, "INVALID_DENOMINATOR");
require(oversubRate.overNumerator > 0, "INVALID_NUMERATOR");
uint256 ratesLength = ratesData.length;
for (uint256 i = 0; i < ratesLength; i++) {
RateData memory data = ratesData[i];
require(data.numerator > 0, "INVALID_NUMERATOR");
require(data.denominator > 0, "INVALID_DENOMINATOR");
require(tokenRates[data.token].token == address(0), "RATE_ALREADY_SET");
require(configuredTokenRates.add(data.token), "ALREADY_CONFIGURED");
tokenRates[data.token] = data;
}
require(configuredTokenRates.length() == supportedTokens.length(), "MISSING_RATE");
// Stage only moves forward when prices are published
currentStage = STAGES.STAGE_2;
lastLookExpiration = block.number + lastLookDuration;
overSubscriptionRate = oversubRate;
emit RatesPublished(ratesData);
}
function getRates(address[] calldata tokens) external view override returns (RateData[] memory rates) {
uint256 tokensLength = tokens.length;
rates = new RateData[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
rates[i] = tokenRates[tokens[i]];
}
}
function getTokenValue(address token, uint256 balance) internal view returns (uint256 value) {
uint256 tokenDecimals = ERC20(token).decimals();
(, int256 tokenRate, , , ) = AggregatorV3Interface(tokenSettings[token].oracle).latestRoundData();
uint256 rate = tokenRate.toUint256();
value = (balance.mul(rate)).div(10**tokenDecimals); //Chainlink USD prices are always to 8
}
function totalValue() external view override returns (uint256) {
return _totalValue();
}
function _totalValue() internal view returns (uint256 value) {
uint256 tokensLength = supportedTokens.length();
for (uint256 i = 0; i < tokensLength; i++) {
address token = supportedTokens.at(i);
uint256 tokenBalance = IERC20(token).balanceOf(address(this));
value = value.add(getTokenValue(token, tokenBalance));
}
}
function accountBalance(address account) external view override returns (uint256 value) {
uint256 tokenBalance = accountData[account].currentBalance;
value = value.add(getTokenValue(accountData[account].token, tokenBalance));
}
function finalizeAssets(bool depositToGenesis) external override {
require(currentStage == STAGES.STAGE_3, "NOT_SYSTEM_FINAL");
AccountData storage data = accountData[msg.sender];
address token = data.token;
require(token != address(0), "NO_DATA");
( , uint256 ineffective, ) = _getRateAdjustedAmounts(data.currentBalance, token);
require(ineffective > 0, "NOTHING_TO_MOVE");
// zero out balance
data.currentBalance = 0;
accountData[msg.sender] = data;
if (depositToGenesis) {
address pool = tokenSettings[token].genesis;
uint256 currentAllowance = IERC20(token).allowance(address(this), pool);
if (currentAllowance < ineffective) {
IERC20(token).safeIncreaseAllowance(pool, ineffective.sub(currentAllowance));
}
ILiquidityPool(pool).depositFor(msg.sender, ineffective);
emit GenesisTransfer(msg.sender, ineffective);
} else {
// transfer ineffectiveTokenBalance back to user
IERC20(token).safeTransfer(msg.sender, ineffective);
}
emit AssetsFinalized(msg.sender, token, ineffective);
}
function getGenesisPools(address[] calldata tokens)
external
view
override
returns (address[] memory genesisAddresses)
{
uint256 tokensLength = tokens.length;
genesisAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
genesisAddresses[i] = tokenSettings[supportedTokens.at(i)].genesis;
}
}
function getTokenOracles(address[] calldata tokens)
external
view
override
returns (address[] memory oracleAddresses)
{
uint256 tokensLength = tokens.length;
oracleAddresses = new address[](tokensLength);
for (uint256 i = 0; i < tokensLength; i++) {
require(supportedTokens.contains(tokens[i]), "TOKEN_UNSUPPORTED");
oracleAddresses[i] = tokenSettings[tokens[i]].oracle;
}
}
function getAccountData(address account) external view override returns (AccountDataDetails[] memory data) {
uint256 supportedTokensLength = supportedTokens.length();
data = new AccountDataDetails[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
AccountData memory accountTokenInfo = accountData[account];
if (currentStage >= STAGES.STAGE_2 && accountTokenInfo.token != address(0)) {
(uint256 effective, uint256 ineffective, uint256 actual) = _getRateAdjustedAmounts(accountTokenInfo.currentBalance, token);
AccountDataDetails memory details = AccountDataDetails(
token,
accountTokenInfo.initialDeposit,
accountTokenInfo.currentBalance,
effective,
ineffective,
actual
);
data[i] = details;
} else {
data[i] = AccountDataDetails(token, accountTokenInfo.initialDeposit, accountTokenInfo.currentBalance, 0, 0, 0);
}
}
}
function transferToTreasury() external override onlyOwner {
require(_isLastLookComplete(), "CURRENT_STAGE_INVALID");
require(currentStage == STAGES.STAGE_2, "ONLY_TRANSFER_ONCE");
uint256 supportedTokensLength = supportedTokens.length();
TokenData[] memory tokens = new TokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
address token = supportedTokens.at(i);
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = _getRateAdjustedAmounts(balance, token);
tokens[i].token = token;
tokens[i].amount = effective;
IERC20(token).safeTransfer(treasury, effective);
}
currentStage = STAGES.STAGE_3;
emit TreasuryTransfer(tokens);
}
function getRateAdjustedAmounts(uint256 balance, address token) external override view returns (uint256,uint256,uint256) {
return _getRateAdjustedAmounts(balance, token);
}
function getMaxTotalValue() external view override returns (uint256) {
return maxTotalValue;
}
function _getRateAdjustedAmounts(uint256 balance, address token) internal view returns (uint256,uint256,uint256) {
require(currentStage >= STAGES.STAGE_2, "RATES_NOT_PUBLISHED");
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(overSubscriptionRate.overNumerator).div(overSubscriptionRate.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(overSubscriptionRate.overDenominator.sub(overSubscriptionRate.overNumerator))
.div(overSubscriptionRate.overDenominator);
uint256 actualReceived =
effectiveTokenBalance.mul(rateInfo.denominator).div(rateInfo.numerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actualReceived);
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
function _isLastLookComplete() internal view returns (bool) {
return block.number >= lastLookExpiration;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) public {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface IDefiRound {
enum STAGES {STAGE_1, STAGE_2, STAGE_3}
struct AccountData {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
}
struct AccountDataDetails {
address token; // address of the allowed token deposited
uint256 initialDeposit; // initial amount deposited of the token
uint256 currentBalance; // current balance of the token that can be used to claim TOKE
uint256 effectiveAmt; //Amount deposited that will be used towards TOKE
uint256 ineffectiveAmt; //Amount deposited that will be either refunded or go to farming
uint256 actualTokeReceived; //Amount of TOKE that will be received
}
struct TokenData {
address token;
uint256 amount;
}
struct SupportedTokenData {
address token;
address oracle;
address genesis;
uint256 maxLimit;
}
struct RateData {
address token;
uint256 numerator;
uint256 denominator;
}
struct OversubscriptionRate {
uint256 overNumerator;
uint256 overDenominator;
}
event Deposited(address depositor, TokenData tokenInfo);
event Withdrawn(address withdrawer, TokenData tokenInfo, bool asETH);
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event RatesPublished(RateData[] ratesData);
event GenesisTransfer(address user, uint256 amountTransferred);
event AssetsFinalized(address claimer, address token, uint256 assetsMoved);
event WhitelistConfigured(WhitelistSettings settings);
event TreasuryTransfer(TokenData[] tokens);
struct TokenValues {
uint256 effectiveTokenValue;
uint256 ineffectiveTokenValue;
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings calldata settings) external;
/// @notice returns the current stage the contract is in
/// @return stage the current stage the round contract is in
function currentStage() external returns (STAGES stage);
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
function deposit(TokenData calldata tokenData, bytes32[] memory proof) external payable;
/// @notice total value held in the entire contract amongst all the assets
/// @return value the value of all assets held
function totalValue() external view returns (uint256 value);
/// @notice Current Max Total Value
function getMaxTotalValue() external view returns (uint256 value);
/// @notice returns the address of the treasury, when users claim this is where funds that are <= maxClaimableValue go
/// @return treasuryAddress address of the treasury
function treasury() external returns (address treasuryAddress);
/// @notice the total supply held for a given token
/// @param token the token to get the supply for
/// @return amount the total supply for a given token
function totalSupply(address token) external returns (uint256 amount);
/// @notice withdraws tokens from the round contract. only callable when round 2 starts
/// @param tokenData an array of token structs
/// @param asEth flag to determine if provided WETH, that it should be withdrawn as ETH
function withdraw(TokenData calldata tokenData, bool asEth) external;
// /// @notice adds tokens to support
// /// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] calldata tokensToSupport) external;
// /// @notice returns which tokens can be deposited
// /// @return tokens tokens that are supported for deposit
function getSupportedTokens() external view returns (address[] calldata tokens);
/// @notice the oracle that will be used to denote how much the amounts deposited are worth in USD
/// @param tokens an array of tokens
/// @return oracleAddresses the an array of oracles corresponding to supported tokens
function getTokenOracles(address[] calldata tokens)
external
view
returns (address[] calldata oracleAddresses);
/// @notice publishes rates for the tokens. Rates are always relative to 1 TOKE. Can only be called once within Stage 1
// prices can be published at any time
/// @param ratesData an array of rate info structs
function publishRates(
RateData[] calldata ratesData,
OversubscriptionRate memory overSubRate,
uint256 lastLookDuration
) external;
/// @notice return the published rates for the tokens
/// @param tokens an array of tokens to get rates for
/// @return rates an array of rates for the provided tokens
function getRates(address[] calldata tokens) external view returns (RateData[] calldata rates);
/// @notice determines the account value in USD amongst all the assets the user is invovled in
/// @param account the account to look up
/// @return value the value of the account in USD
function accountBalance(address account) external view returns (uint256 value);
/// @notice Moves excess assets to private farming or refunds them
/// @dev uses the publishedRates, selected tokens, and amounts to determine what amount of TOKE is claimed
/// @param depositToGenesis applies only if oversubscribedMultiplier < 1;
/// when true oversubscribed amount will deposit to genesis, else oversubscribed amount is sent back to user
function finalizeAssets(bool depositToGenesis) external;
//// @notice returns what gensis pool a supported token is mapped to
/// @param tokens array of addresses of supported tokens
/// @return genesisAddresses array of genesis pools corresponding to supported tokens
function getGenesisPools(address[] calldata tokens)
external
view
returns (address[] memory genesisAddresses);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account)
external
view
returns (AccountDataDetails[] calldata data);
/// @notice Allows the owner to transfer all swapped assets to the treasury
/// @dev only callable by owner and if last look period is complete
function transferToTreasury() external;
/// @notice Given a balance, calculates how the the amount will be allocated between TOKE and Farming
/// @dev Only allowed at stage 3
/// @param balance balance to divy up
/// @param token token to pull the rates for
function getRateAdjustedAmounts(uint256 balance, address token)
external
view
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev These functions deal with verification of Merkle trees (hash trees),
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "../interfaces/ICoreEvent.sol";
import "../interfaces/ILiquidityPool.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/cryptography/MerkleProof.sol";
contract CoreEvent is Ownable, ICoreEvent {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
using EnumerableSet for EnumerableSet.AddressSet;
DurationInfo public durationInfo;
address public immutable treasuryAddress;
EnumerableSet.AddressSet private supportedTokenAddresses;
// token address -> SupportedTokenData
mapping(address => SupportedTokenData) public supportedTokens;
// user -> token -> AccountData
mapping(address => mapping(address => AccountData)) public accountData;
mapping(address => RateData) public tokenRates;
WhitelistSettings public whitelistSettings;
bool public stage1Locked;
modifier hasEnded() {
require(_hasEnded(), "TOO_EARLY");
_;
}
constructor(
address treasury,
SupportedTokenData[] memory tokensToSupport
) public {
treasuryAddress = treasury;
addSupportedTokens(tokensToSupport);
}
function configureWhitelist(WhitelistSettings memory settings) external override onlyOwner {
whitelistSettings = settings;
emit WhitelistConfigured(settings);
}
function setDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock == 0, "ALREADY_STARTED");
durationInfo.startingBlock = block.number;
durationInfo.blockDuration = _blockDuration;
emit DurationSet(durationInfo);
}
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) public override onlyOwner {
require (tokensToSupport.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokensToSupport.length; i++) {
require(
!supportedTokenAddresses.contains(tokensToSupport[i].token),
"DUPLICATE_TOKEN"
);
require(tokensToSupport[i].token != address(0), "ZERO_ADDRESS");
require(!tokensToSupport[i].systemFinalized, "FINALIZED_MUST_BE_FALSE");
supportedTokenAddresses.add(tokensToSupport[i].token);
supportedTokens[tokensToSupport[i].token] = tokensToSupport[i];
}
emit SupportedTokensAdded(tokensToSupport);
}
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external override {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
if (whitelistSettings.enabled) {
require(verifyDepositor(msg.sender, whitelistSettings.root, proof), "PROOF_INVALID");
}
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "0_BALANCE");
address token = tokenData[i].token;
require(supportedTokenAddresses.contains(token), "NOT_SUPPORTED");
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(
data.depositedBalance.add(amount) <= supportedTokens[token].maxUserLimit,
"OVER_LIMIT"
);
data.depositedBalance = data.depositedBalance.add(amount);
data.token = token;
erc20Token.safeTransferFrom(msg.sender, address(this), amount);
}
emit Deposited(msg.sender, tokenData);
}
function withdraw(TokenData[] calldata tokenData) external override {
require(!_hasEnded(), "RATES_LOCKED");
require(tokenData.length > 0, "NO_TOKENS");
for (uint256 i = 0; i < tokenData.length; i++) {
uint256 amount = tokenData[i].amount;
require(amount > 0, "ZERO_BALANCE");
address token = tokenData[i].token;
IERC20 erc20Token = IERC20(token);
AccountData storage data = accountData[msg.sender][token];
require(data.token != address(0), "ZERO_ADDRESS");
require(amount <= data.depositedBalance, "INSUFFICIENT_FUNDS");
data.depositedBalance = data.depositedBalance.sub(amount);
if (data.depositedBalance == 0) {
delete accountData[msg.sender][token];
}
erc20Token.safeTransfer(msg.sender, amount);
}
emit Withdrawn(msg.sender, tokenData);
}
function increaseDuration(uint256 _blockDuration) external override onlyOwner {
require(durationInfo.startingBlock > 0, "NOT_STARTED");
require(_blockDuration > durationInfo.blockDuration, "INCREASE_ONLY");
require(!stage1Locked, "STAGE1_LOCKED");
durationInfo.blockDuration = _blockDuration;
emit DurationIncreased(durationInfo);
}
function setRates(RateData[] calldata rates) external override onlyOwner hasEnded {
//Rates are settable multiple times, but only until they are finalized.
//They are set to finalized by either performing the transferToTreasury
//Or, by marking them as no-swap tokens
//Users cannot begin their next set of actions before a token finalized.
uint256 length = rates.length;
for (uint256 i = 0; i < length; i++) {
RateData memory data = rates[i];
require(supportedTokenAddresses.contains(data.token), "UNSUPPORTED_ADDRESS");
require(!supportedTokens[data.token].systemFinalized, "ALREADY_FINALIZED");
if (data.tokeNumerator > 0) {
//We are allowing an address(0) pool, it means it was a winning reactor
//but there wasn't enough to enable private farming
require(data.tokeDenominator > 0, "INVALID_TOKE_DENOMINATOR");
require(data.overNumerator > 0, "INVALID_OVER_NUMERATOR");
require(data.overDenominator > 0, "INVALID_OVER_DENOMINATOR");
tokenRates[data.token] = data;
} else {
delete tokenRates[data.token];
}
}
stage1Locked = true;
emit RatesPublished(rates);
}
function transferToTreasury(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
TokenData[] memory transfers = new TokenData[](length);
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(tokenRates[token].tokeNumerator > 0, "NO_SWAP_TOKEN");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
uint256 balance = IERC20(token).balanceOf(address(this));
(uint256 effective, , ) = getRateAdjustedAmounts(balance, token);
transfers[i].token = token;
transfers[i].amount = effective;
supportedTokens[token].systemFinalized = true;
IERC20(token).safeTransfer(treasuryAddress, effective);
}
emit TreasuryTransfer(transfers);
}
function setNoSwap(address[] calldata tokens) external override onlyOwner hasEnded {
uint256 length = tokens.length;
for (uint256 i = 0; i < length; i++) {
address token = tokens[i];
require(supportedTokenAddresses.contains(token), "UNSUPPORTED_ADDRESS");
require(tokenRates[token].tokeNumerator == 0, "ALREADY_SET_TO_SWAP");
require(!supportedTokens[token].systemFinalized, "ALREADY_FINALIZED");
supportedTokens[token].systemFinalized = true;
}
stage1Locked = true;
emit SetNoSwap(tokens);
}
function finalize(TokenFarming[] calldata tokens) external override hasEnded {
require(tokens.length > 0, "NO_TOKENS");
uint256 length = tokens.length;
FinalizedAccountData[] memory results = new FinalizedAccountData[](length);
for(uint256 i = 0; i < length; i++) {
TokenFarming calldata farm = tokens[i];
AccountData storage account = accountData[msg.sender][farm.token];
require(!account.finalized, "ALREADY_FINALIZED");
require(farm.token != address(0), "ZERO_ADDRESS");
require(supportedTokens[farm.token].systemFinalized, "NOT_SYSTEM_FINALIZED");
require(account.depositedBalance > 0, "INSUFFICIENT_FUNDS");
RateData storage rate = tokenRates[farm.token];
uint256 amtToTransfer = 0;
if (rate.tokeNumerator > 0) {
//We have set a rate, which means its a winning reactor
//which means only the ineffective amount, the amount
//not spent on TOKE, can leave the contract.
//Leaving to either the farm or back to the user
//In the event there is no farming, an oversubscription rate of 1/1
//will be provided for the token. That will ensure the ineffective
//amount is 0 and caught by the below require() as only assets with
//an oversubscription can be moved
(, uint256 ineffectiveAmt, ) = getRateAdjustedAmounts(account.depositedBalance, farm.token);
amtToTransfer = ineffectiveAmt;
} else {
amtToTransfer = account.depositedBalance;
}
require(amtToTransfer > 0, "NOTHING_TO_MOVE");
account.finalized = true;
if (farm.sendToFarming) {
require(rate.pool != address(0), "NO_FARMING");
uint256 currentAllowance = IERC20(farm.token).allowance(address(this), rate.pool);
if (currentAllowance < amtToTransfer) {
IERC20(farm.token).safeIncreaseAllowance(rate.pool, amtToTransfer.sub(currentAllowance));
}
ILiquidityPool(rate.pool).depositFor(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: amtToTransfer,
refunded: 0
});
} else {
IERC20(farm.token).safeTransfer(msg.sender, amtToTransfer);
results[i] = FinalizedAccountData({
token: farm.token,
transferredToFarm: 0,
refunded: amtToTransfer
});
}
}
emit AssetsFinalized(msg.sender, results);
}
function getRateAdjustedAmounts(uint256 balance, address token) public override view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived) {
RateData memory rateInfo = tokenRates[token];
uint256 effectiveTokenBalance =
balance.mul(rateInfo.overNumerator).div(rateInfo.overDenominator);
uint256 ineffectiveTokenBalance =
balance.mul(rateInfo.overDenominator.sub(rateInfo.overNumerator))
.div(rateInfo.overDenominator);
uint256 actual =
effectiveTokenBalance.mul(rateInfo.tokeDenominator).div(rateInfo.tokeNumerator);
return (effectiveTokenBalance, ineffectiveTokenBalance, actual);
}
function getRates() external override view returns (RateData[] memory rates) {
uint256 length = supportedTokenAddresses.length();
rates = new RateData[](length);
for (uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
rates[i] = tokenRates[token];
}
}
function getAccountData(address account) external view override returns (AccountData[] memory data) {
uint256 length = supportedTokenAddresses.length();
data = new AccountData[](length);
for(uint256 i = 0; i < length; i++) {
address token = supportedTokenAddresses.at(i);
data[i] = accountData[account][token];
data[i].token = token;
}
}
function getSupportedTokens() external view override returns (SupportedTokenData[] memory supportedTokensArray) {
uint256 supportedTokensLength = supportedTokenAddresses.length();
supportedTokensArray = new SupportedTokenData[](supportedTokensLength);
for (uint256 i = 0; i < supportedTokensLength; i++) {
supportedTokensArray[i] = supportedTokens[supportedTokenAddresses.at(i)];
}
return supportedTokensArray;
}
function _hasEnded() private view returns (bool) {
return durationInfo.startingBlock > 0 && block.number >= durationInfo.blockDuration + durationInfo.startingBlock;
}
function verifyDepositor(address participant, bytes32 root, bytes32[] memory proof) internal pure returns (bool) {
bytes32 leaf = keccak256((abi.encodePacked((participant))));
return MerkleProof.verify(proof, root, leaf);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
interface ICoreEvent {
struct SupportedTokenData {
address token;
uint256 maxUserLimit;
bool systemFinalized; // Whether or not the system is done setting rates, doing transfers, for this token
}
struct DurationInfo {
uint256 startingBlock;
uint256 blockDuration; // Block duration of the deposit/withdraw stage
}
struct RateData {
address token;
uint256 tokeNumerator;
uint256 tokeDenominator;
uint256 overNumerator;
uint256 overDenominator;
address pool;
}
struct TokenData {
address token;
uint256 amount;
}
struct AccountData {
address token; // Address of the allowed token deposited
uint256 depositedBalance;
bool finalized; // Has the user either taken their refund or sent to farming. Will not be set on swapped but undersubscribed tokens.
}
struct FinalizedAccountData {
address token;
uint256 transferredToFarm;
uint256 refunded;
}
struct TokenFarming {
address token; // address of the allowed token deposited
bool sendToFarming; // Refund is default
}
struct WhitelistSettings {
bool enabled;
bytes32 root;
}
event SupportedTokensAdded(SupportedTokenData[] tokenData);
event TreasurySet(address treasury);
event DurationSet(DurationInfo duration);
event DurationIncreased(DurationInfo duration);
event Deposited(address depositor, TokenData[] tokenInfo);
event Withdrawn(address withdrawer, TokenData[] tokenInfo);
event RatesPublished(RateData[] ratesData);
event AssetsFinalized(address user, FinalizedAccountData[] data);
event TreasuryTransfer(TokenData[] tokens);
event WhitelistConfigured(WhitelistSettings settings);
event SetNoSwap(address[] tokens);
//==========================================
// Initial setup operations
//==========================================
/// @notice Enable or disable the whitelist
/// @param settings The root to use and whether to check the whitelist at all
function configureWhitelist(WhitelistSettings memory settings) external;
/// @notice defines the length in blocks the round will run for
/// @notice round is started via this call and it is only callable one time
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for
function setDuration(uint256 blockDuration) external;
/// @notice adds tokens to support
/// @param tokensToSupport an array of supported token structs
function addSupportedTokens(SupportedTokenData[] memory tokensToSupport) external;
//==========================================
// Stage 1 timeframe operations
//==========================================
/// @notice deposits tokens into the round contract
/// @param tokenData an array of token structs
/// @param proof Merkle proof for the user. Only required if whitelistSettings.enabled
function deposit(TokenData[] calldata tokenData, bytes32[] calldata proof) external;
/// @notice withdraws tokens from the round contract
/// @param tokenData an array of token structs
function withdraw(TokenData[] calldata tokenData) external;
/// @notice extends the deposit/withdraw stage
/// @notice Only extendable if no tokens have been finalized and no rates set
/// @param blockDuration Duration in blocks the deposit/withdraw portion will run for. Must be greater than original
function increaseDuration(uint256 blockDuration) external;
//==========================================
// Stage 1 -> 2 transition operations
//==========================================
/// @notice once the expected duration has passed, publish the Toke and over subscription rates
/// @notice tokens which do not have a published rate will have their users forced to withdraw all funds
/// @dev pass a tokeNumerator of 0 to delete a set rate
/// @dev Cannot be called for a token once transferToTreasury/setNoSwap has been called for that token
function setRates(RateData[] calldata rates) external;
/// @notice Allows the owner to transfer the effective balance of a token based on the set rate to the treasury
/// @dev only callable by owner and if rates have been set
/// @dev is only callable one time for a token
function transferToTreasury(address[] calldata tokens) external;
/// @notice Marks a token as finalized but not swapping
/// @dev complement to transferToTreasury which is for tokens that will be swapped, this one for ones that won't
function setNoSwap(address[] calldata tokens) external;
//==========================================
// Stage 2 operations
//==========================================
/// @notice Once rates have been published, and the token finalized via transferToTreasury/setNoSwap, either refunds or sends to private farming
/// @param tokens an array of tokens and whether to send them to private farming. False on farming will send back to user.
function finalize(TokenFarming[] calldata tokens) external;
//==========================================
// View operations
//==========================================
/// @notice Breaks down the balance according to the published rates
/// @dev only callable after rates have been set
function getRateAdjustedAmounts(uint256 balance, address token) external view returns (uint256 effectiveAmt, uint256 ineffectiveAmt, uint256 actualReceived);
/// @notice return the published rates for the tokens
/// @return rates an array of rates for the provided tokens
function getRates() external view returns (RateData[] memory rates);
/// @notice returns a list of AccountData for a provided account
/// @param account the address of the account
/// @return data an array of AccountData denoting what the status is for each of the tokens deposited (if any)
function getAccountData(address account) external view returns (AccountData[] calldata data);
/// @notice get all tokens currently supported by the contract
/// @return supportedTokensArray an array of supported token structs
function getSupportedTokens() external view returns (SupportedTokenData[] memory supportedTokensArray);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../utils/Context.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20.sol";
import "../../utils/Pausable.sol";
/**
* @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 ERC20Pausable is ERC20, Pausable {
/**
* @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");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Toke is ERC20Pausable, Ownable {
uint256 private constant SUPPLY = 100_000_000e18;
constructor() public ERC20("Tokemak", "TOKE") {
_mint(msg.sender, SUPPLY); // 100M
}
function pause() external onlyOwner {
_pause();
}
function unpause() external onlyOwner {
_unpause();
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
contract Rewards is Ownable {
using SafeMath for uint256;
using ECDSA for bytes32;
using SafeERC20 for IERC20;
mapping(address => uint256) public claimedAmounts;
event SignerSet(address newSigner);
event Claimed(uint256 cycle, address recipient, uint256 amount);
struct EIP712Domain {
string name;
string version;
uint256 chainId;
address verifyingContract;
}
struct Recipient {
uint256 chainId;
uint256 cycle;
address wallet;
uint256 amount;
}
bytes32 private constant EIP712_DOMAIN_TYPEHASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 private constant RECIPIENT_TYPEHASH =
keccak256("Recipient(uint256 chainId,uint256 cycle,address wallet,uint256 amount)");
bytes32 private immutable domainSeparator;
IERC20 public immutable tokeToken;
address public rewardsSigner;
constructor(IERC20 token, address signerAddress) public {
require(address(token) != address(0), "Invalid TOKE Address");
require(signerAddress != address(0), "Invalid Signer Address");
tokeToken = token;
rewardsSigner = signerAddress;
domainSeparator = _hashDomain(
EIP712Domain({
name: "TOKE Distribution",
version: "1",
chainId: _getChainID(),
verifyingContract: address(this)
})
);
}
function _hashDomain(EIP712Domain memory eip712Domain) private pure returns (bytes32) {
return
keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(eip712Domain.name)),
keccak256(bytes(eip712Domain.version)),
eip712Domain.chainId,
eip712Domain.verifyingContract
)
);
}
function _hashRecipient(Recipient memory recipient) private pure returns (bytes32) {
return
keccak256(
abi.encode(
RECIPIENT_TYPEHASH,
recipient.chainId,
recipient.cycle,
recipient.wallet,
recipient.amount
)
);
}
function _hash(Recipient memory recipient) private view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, _hashRecipient(recipient)));
}
function _getChainID() private pure returns (uint256) {
uint256 id;
// solhint-disable-next-line no-inline-assembly
assembly {
id := chainid()
}
return id;
}
function setSigner(address newSigner) external onlyOwner {
require(newSigner != address(0), "Invalid Signer Address");
rewardsSigner = newSigner;
}
function getClaimableAmount(
Recipient calldata recipient
) external view returns (uint256) {
return recipient.amount.sub(claimedAmounts[recipient.wallet]);
}
function claim(
Recipient calldata recipient,
uint8 v,
bytes32 r,
bytes32 s // bytes calldata signature
) external {
address signatureSigner = _hash(recipient).recover(v, r, s);
require(signatureSigner == rewardsSigner, "Invalid Signature");
require(recipient.chainId == _getChainID(), "Invalid chainId");
require(recipient.wallet == msg.sender, "Sender wallet Mismatch");
uint256 claimableAmount = recipient.amount.sub(claimedAmounts[recipient.wallet]);
require(claimableAmount > 0, "Invalid claimable amount");
require(tokeToken.balanceOf(address(this)) >= claimableAmount, "Insufficient Funds");
claimedAmounts[recipient.wallet] = claimedAmounts[recipient.wallet].add(claimableAmount);
tokeToken.safeTransfer(recipient.wallet, claimableAmount);
emit Claimed(recipient.cycle, recipient.wallet, claimableAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IStaking.sol";
/// @title Tokemak Redeem Contract
/// @notice Converts PreToke to Toke
/// @dev Can only be used when fromToken has been unpaused
contract Redeem is Ownable {
using SafeERC20 for IERC20;
address public immutable fromToken;
address public immutable toToken;
address public immutable stakingContract;
uint256 public immutable expirationBlock;
uint256 public immutable stakingSchedule;
/// @notice Redeem Constructor
/// @dev approves max uint256 on creation for the toToken against the staking contract
/// @param _fromToken the token users will convert from
/// @param _toToken the token users will convert to
/// @param _stakingContract the staking contract
/// @param _expirationBlock a block number at which the owner can withdraw the full balance of toToken
constructor(
address _fromToken,
address _toToken,
address _stakingContract,
uint256 _expirationBlock,
uint256 _stakingSchedule
) public {
require(_fromToken != address(0), "INVALID_FROMTOKEN");
require(_toToken != address(0), "INVALID_TOTOKEN");
require(_stakingContract != address(0), "INVALID_STAKING");
fromToken = _fromToken;
toToken = _toToken;
stakingContract = _stakingContract;
expirationBlock = _expirationBlock;
stakingSchedule = _stakingSchedule;
//Approve staking contract for toToken to allow for staking within convert()
IERC20(_toToken).safeApprove(_stakingContract, type(uint256).max);
}
/// @notice Allows a holder of fromToken to convert into toToken and simultaneously stake within the stakingContract
/// @dev a user must approve this contract in order for it to burnFrom()
function convert() external {
uint256 fromBal = IERC20(fromToken).balanceOf(msg.sender);
require(fromBal > 0, "INSUFFICIENT_BALANCE");
ERC20Burnable(fromToken).burnFrom(msg.sender, fromBal);
IStaking(stakingContract).depositFor(msg.sender, fromBal, stakingSchedule);
}
/// @notice Allows the claim on the toToken balance after the expiration has passed
/// @dev callable only by owner
function recoupRemaining() external onlyOwner {
require(block.number >= expirationBlock, "EXPIRATION_NOT_PASSED");
uint256 bal = IERC20(toToken).balanceOf(address(this));
IERC20(toToken).safeTransfer(msg.sender, bal);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../access/AccessControl.sol";
import "../utils/Context.sol";
import "../token/ERC20/ERC20.sol";
import "../token/ERC20/ERC20Burnable.sol";
import "../token/ERC20/ERC20Pausable.sol";
/**
* @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 ERC20PresetMinterPauser is Context, AccessControl, ERC20Burnable, ERC20Pausable {
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}.
*/
constructor(string memory name, string memory symbol) public ERC20(name, symbol) {
_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(ERC20, ERC20Pausable) {
super._beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
// solhint-disable-next-line
contract PreToke is ERC20PresetMinterPauser("PreToke", "PTOKE") {
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
// We import the contract so truffle compiles it, and we have the ABI
// available when working from truffle console.
import "@gnosis.pm/mock-contract/contracts/MockContract.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/presets/ERC20PresetMinterPauser.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2ERC20.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol" as ISushiswapV2Router;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol" as ISushiswapV2Factory;
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2ERC20.sol" as ISushiswapV2ERC20;
pragma solidity ^0.6.0;
interface MockInterface {
/**
* @dev After calling this method, the mock will return `response` when it is called
* with any calldata that is not mocked more specifically below
* (e.g. using givenMethodReturn).
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenAnyReturn(bytes calldata response) external;
function givenAnyReturnBool(bool response) external;
function givenAnyReturnUint(uint response) external;
function givenAnyReturnAddress(address response) external;
function givenAnyRevert() external;
function givenAnyRevertWithMessage(string calldata message) external;
function givenAnyRunOutOfGas() external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called regardless of arguments. If the methodId and arguments
* are mocked more specifically (using `givenMethodAndArguments`) the latter
* will take precedence.
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
* @param response ABI encoded response that will be returned if method is invoked
*/
function givenMethodReturn(bytes calldata method, bytes calldata response) external;
function givenMethodReturnBool(bytes calldata method, bool response) external;
function givenMethodReturnUint(bytes calldata method, uint response) external;
function givenMethodReturnAddress(bytes calldata method, address response) external;
function givenMethodRevert(bytes calldata method) external;
function givenMethodRevertWithMessage(bytes calldata method, string calldata message) external;
function givenMethodRunOutOfGas(bytes calldata method) external;
/**
* @dev After calling this method, the mock will return `response` when the given
* methodId is called with matching arguments. These exact calldataMocks will take
* precedence over all other calldataMocks.
* @param call ABI encoded calldata (methodId and arguments)
* @param response ABI encoded response that will be returned if contract is invoked with calldata
*/
function givenCalldataReturn(bytes calldata call, bytes calldata response) external;
function givenCalldataReturnBool(bytes calldata call, bool response) external;
function givenCalldataReturnUint(bytes calldata call, uint response) external;
function givenCalldataReturnAddress(bytes calldata call, address response) external;
function givenCalldataRevert(bytes calldata call) external;
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) external;
function givenCalldataRunOutOfGas(bytes calldata call) external;
/**
* @dev Returns the number of times anything has been called on this mock since last reset
*/
function invocationCount() external returns (uint);
/**
* @dev Returns the number of times the given method has been called on this mock since last reset
* @param method ABI encoded methodId. It is valid to pass full calldata (including arguments). The mock will extract the methodId from it
*/
function invocationCountForMethod(bytes calldata method) external returns (uint);
/**
* @dev Returns the number of times this mock has been called with the exact calldata since last reset.
* @param call ABI encoded calldata (methodId and arguments)
*/
function invocationCountForCalldata(bytes calldata call) external returns (uint);
/**
* @dev Resets all mocked methods and invocation counts.
*/
function reset() external;
}
/**
* Implementation of the MockInterface.
*/
contract MockContract is MockInterface {
enum MockType { Return, Revert, OutOfGas }
bytes32 public constant MOCKS_LIST_START = hex"01";
bytes public constant MOCKS_LIST_END = "0xff";
bytes32 public constant MOCKS_LIST_END_HASH = keccak256(MOCKS_LIST_END);
bytes4 public constant SENTINEL_ANY_MOCKS = hex"01";
bytes public constant DEFAULT_FALLBACK_VALUE = abi.encode(false);
// A linked list allows easy iteration and inclusion checks
mapping(bytes32 => bytes) calldataMocks;
mapping(bytes => MockType) calldataMockTypes;
mapping(bytes => bytes) calldataExpectations;
mapping(bytes => string) calldataRevertMessage;
mapping(bytes32 => uint) calldataInvocations;
mapping(bytes4 => bytes4) methodIdMocks;
mapping(bytes4 => MockType) methodIdMockTypes;
mapping(bytes4 => bytes) methodIdExpectations;
mapping(bytes4 => string) methodIdRevertMessages;
mapping(bytes32 => uint) methodIdInvocations;
MockType fallbackMockType;
bytes fallbackExpectation = DEFAULT_FALLBACK_VALUE;
string fallbackRevertMessage;
uint invocations;
uint resetCount;
constructor() public {
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
}
function trackCalldataMock(bytes memory call) private {
bytes32 callHash = keccak256(call);
if (calldataMocks[callHash].length == 0) {
calldataMocks[callHash] = calldataMocks[MOCKS_LIST_START];
calldataMocks[MOCKS_LIST_START] = call;
}
}
function trackMethodIdMock(bytes4 methodId) private {
if (methodIdMocks[methodId] == 0x0) {
methodIdMocks[methodId] = methodIdMocks[SENTINEL_ANY_MOCKS];
methodIdMocks[SENTINEL_ANY_MOCKS] = methodId;
}
}
function _givenAnyReturn(bytes memory response) internal {
fallbackMockType = MockType.Return;
fallbackExpectation = response;
}
function givenAnyReturn(bytes calldata response) override external {
_givenAnyReturn(response);
}
function givenAnyReturnBool(bool response) override external {
uint flag = response ? 1 : 0;
_givenAnyReturn(uintToBytes(flag));
}
function givenAnyReturnUint(uint response) override external {
_givenAnyReturn(uintToBytes(response));
}
function givenAnyReturnAddress(address response) override external {
_givenAnyReturn(uintToBytes(uint(response)));
}
function givenAnyRevert() override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = "";
}
function givenAnyRevertWithMessage(string calldata message) override external {
fallbackMockType = MockType.Revert;
fallbackRevertMessage = message;
}
function givenAnyRunOutOfGas() override external {
fallbackMockType = MockType.OutOfGas;
}
function _givenCalldataReturn(bytes memory call, bytes memory response) private {
calldataMockTypes[call] = MockType.Return;
calldataExpectations[call] = response;
trackCalldataMock(call);
}
function givenCalldataReturn(bytes calldata call, bytes calldata response) override external {
_givenCalldataReturn(call, response);
}
function givenCalldataReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenCalldataReturn(call, uintToBytes(flag));
}
function givenCalldataReturnUint(bytes calldata call, uint response) override external {
_givenCalldataReturn(call, uintToBytes(response));
}
function givenCalldataReturnAddress(bytes calldata call, address response) override external {
_givenCalldataReturn(call, uintToBytes(uint(response)));
}
function _givenMethodReturn(bytes memory call, bytes memory response) private {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Return;
methodIdExpectations[method] = response;
trackMethodIdMock(method);
}
function givenMethodReturn(bytes calldata call, bytes calldata response) override external {
_givenMethodReturn(call, response);
}
function givenMethodReturnBool(bytes calldata call, bool response) override external {
uint flag = response ? 1 : 0;
_givenMethodReturn(call, uintToBytes(flag));
}
function givenMethodReturnUint(bytes calldata call, uint response) override external {
_givenMethodReturn(call, uintToBytes(response));
}
function givenMethodReturnAddress(bytes calldata call, address response) override external {
_givenMethodReturn(call, uintToBytes(uint(response)));
}
function givenCalldataRevert(bytes calldata call) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = "";
trackCalldataMock(call);
}
function givenMethodRevert(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
trackMethodIdMock(method);
}
function givenCalldataRevertWithMessage(bytes calldata call, string calldata message) override external {
calldataMockTypes[call] = MockType.Revert;
calldataRevertMessage[call] = message;
trackCalldataMock(call);
}
function givenMethodRevertWithMessage(bytes calldata call, string calldata message) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.Revert;
methodIdRevertMessages[method] = message;
trackMethodIdMock(method);
}
function givenCalldataRunOutOfGas(bytes calldata call) override external {
calldataMockTypes[call] = MockType.OutOfGas;
trackCalldataMock(call);
}
function givenMethodRunOutOfGas(bytes calldata call) override external {
bytes4 method = bytesToBytes4(call);
methodIdMockTypes[method] = MockType.OutOfGas;
trackMethodIdMock(method);
}
function invocationCount() override external returns (uint) {
return invocations;
}
function invocationCountForMethod(bytes calldata call) override external returns (uint) {
bytes4 method = bytesToBytes4(call);
return methodIdInvocations[keccak256(abi.encodePacked(resetCount, method))];
}
function invocationCountForCalldata(bytes calldata call) override external returns (uint) {
return calldataInvocations[keccak256(abi.encodePacked(resetCount, call))];
}
function reset() override external {
// Reset all exact calldataMocks
bytes memory nextMock = calldataMocks[MOCKS_LIST_START];
bytes32 mockHash = keccak256(nextMock);
// We cannot compary bytes
while(mockHash != MOCKS_LIST_END_HASH) {
// Reset all mock maps
calldataMockTypes[nextMock] = MockType.Return;
calldataExpectations[nextMock] = hex"";
calldataRevertMessage[nextMock] = "";
// Set next mock to remove
nextMock = calldataMocks[mockHash];
// Remove from linked list
calldataMocks[mockHash] = "";
// Update mock hash
mockHash = keccak256(nextMock);
}
// Clear list
calldataMocks[MOCKS_LIST_START] = MOCKS_LIST_END;
// Reset all any calldataMocks
bytes4 nextAnyMock = methodIdMocks[SENTINEL_ANY_MOCKS];
while(nextAnyMock != SENTINEL_ANY_MOCKS) {
bytes4 currentAnyMock = nextAnyMock;
methodIdMockTypes[currentAnyMock] = MockType.Return;
methodIdExpectations[currentAnyMock] = hex"";
methodIdRevertMessages[currentAnyMock] = "";
nextAnyMock = methodIdMocks[currentAnyMock];
// Remove from linked list
methodIdMocks[currentAnyMock] = 0x0;
}
// Clear list
methodIdMocks[SENTINEL_ANY_MOCKS] = SENTINEL_ANY_MOCKS;
fallbackExpectation = DEFAULT_FALLBACK_VALUE;
fallbackMockType = MockType.Return;
invocations = 0;
resetCount += 1;
}
function useAllGas() private {
while(true) {
bool s;
assembly {
//expensive call to EC multiply contract
s := call(sub(gas(), 2000), 6, 0, 0x0, 0xc0, 0x0, 0x60)
}
}
}
function bytesToBytes4(bytes memory b) private pure returns (bytes4) {
bytes4 out;
for (uint i = 0; i < 4; i++) {
out |= bytes4(b[i] & 0xFF) >> (i * 8);
}
return out;
}
function uintToBytes(uint256 x) private pure returns (bytes memory b) {
b = new bytes(32);
assembly { mstore(add(b, 32), x) }
}
function updateInvocationCount(bytes4 methodId, bytes memory originalMsgData) public {
require(msg.sender == address(this), "Can only be called from the contract itself");
invocations += 1;
methodIdInvocations[keccak256(abi.encodePacked(resetCount, methodId))] += 1;
calldataInvocations[keccak256(abi.encodePacked(resetCount, originalMsgData))] += 1;
}
fallback () payable external {
bytes4 methodId;
assembly {
methodId := calldataload(0)
}
// First, check exact matching overrides
if (calldataMockTypes[msg.data] == MockType.Revert) {
revert(calldataRevertMessage[msg.data]);
}
if (calldataMockTypes[msg.data] == MockType.OutOfGas) {
useAllGas();
}
bytes memory result = calldataExpectations[msg.data];
// Then check method Id overrides
if (result.length == 0) {
if (methodIdMockTypes[methodId] == MockType.Revert) {
revert(methodIdRevertMessages[methodId]);
}
if (methodIdMockTypes[methodId] == MockType.OutOfGas) {
useAllGas();
}
result = methodIdExpectations[methodId];
}
// Last, use the fallback override
if (result.length == 0) {
if (fallbackMockType == MockType.Revert) {
revert(fallbackRevertMessage);
}
if (fallbackMockType == MockType.OutOfGas) {
useAllGas();
}
result = fallbackExpectation;
}
// Record invocation as separate call so we don't rollback in case we are called with STATICCALL
(, bytes memory r) = address(this).call{gas: 100000}(abi.encodeWithSignature("updateInvocationCount(bytes4,bytes)", methodId, msg.data));
assert(r.length == 0);
assembly {
return(add(0x20, result), mload(result))
}
}
}
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 IUniswapV2ERC20 {
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;
}
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.2;
import './IUniswapV2Router01.sol';
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// SPDX-License-Identifier: GPL-3.0
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 migrator() 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;
function setMigrator(address) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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;
}
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: GPL-3.0
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.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Router02.sol";
import "@sushiswap/core/contracts/uniswapv2/interfaces/IUniswapV2Factory.sol";
contract SushiswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable SUSHISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable SUSHISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
require(address(router) != address(0), "INVALID_ROUTER");
require(address(factory) != address(0), "INVALID_FACTORY");
SUSHISWAP_ROUTER = router;
SUSHISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
SUSHISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = SUSHISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
SUSHISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(SUSHISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(SUSHISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol";
import "@uniswap/v2-core/contracts/interfaces/IUniswapV2Factory.sol";
contract UniswapController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Router02 public immutable UNISWAP_ROUTER;
// solhint-disable-next-line var-name-mixedcase
IUniswapV2Factory public immutable UNISWAP_FACTORY;
constructor(IUniswapV2Router02 router, IUniswapV2Factory factory) public {
require(address(router) != address(0), "INVALID_ROUTER");
require(address(factory) != address(0), "INVALID_FACTORY");
UNISWAP_ROUTER = router;
UNISWAP_FACTORY = factory;
}
function deploy(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(
data,
(address, address, uint256, uint256, uint256, uint256, address, uint256)
);
_approve(IERC20(tokenA), amountADesired);
_approve(IERC20(tokenB), amountBDesired);
//(uint256 amountA, uint256 amountB, uint256 liquidity) =
UNISWAP_ROUTER.addLiquidity(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
to,
deadline
);
// TODO: perform checks on amountA, amountB, liquidity
}
function withdraw(bytes calldata data) external {
(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) = abi.decode(data, (address, address, uint256, uint256, uint256, address, uint256));
address pair = UNISWAP_FACTORY.getPair(tokenA, tokenB);
require(pair != address(0), "pair doesn't exist");
_approve(IERC20(pair), liquidity);
//(uint256 amountA, uint256 amountB) =
UNISWAP_ROUTER.removeLiquidity(
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
to,
deadline
);
//TODO: perform checks on amountA and amountB
}
function _approve(IERC20 token, uint256 amount) internal {
uint256 currentAllowance = token.allowance(address(this), address(UNISWAP_ROUTER));
if (currentAllowance < amount) {
token.safeIncreaseAllowance(
address(UNISWAP_ROUTER),
type(uint256).max.sub(currentAllowance)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../interfaces/balancer/IBalancerPool.sol";
contract BalancerController {
using SafeERC20 for IERC20;
using Address for address;
using Address for address payable;
using SafeMath for uint256;
function deploy(
address poolAddress,
IERC20[] calldata tokens,
uint256[] calldata amounts,
bytes calldata data
) external {
require(tokens.length == amounts.length, "TOKEN_AMOUNTS_COUNT_MISMATCH");
require(tokens.length > 0, "TOKENS_AMOUNTS_NOT_PROVIDED");
for (uint256 i = 0; i < tokens.length; i++) {
_approve(tokens[i], poolAddress, amounts[i]);
}
//Notes:
// - If your pool is eligible for weekly BAL rewards, they will be distributed to your LPs automatically
// - If you contribute significant long-term liquidity to the platform, you can apply to have smart contract deployment gas costs reimbursed from the Balancer Ecosystem fund
// - The pool is the LP token, All pools in Balancer are also ERC20 tokens known as BPTs \(Balancer Pool Tokens\)
(uint256 poolAmountOut, uint256[] memory maxAmountsIn) =
abi.decode(data, (uint256, uint256[]));
IBalancerPool(poolAddress).joinPool(poolAmountOut, maxAmountsIn);
}
function withdraw(address poolAddress, bytes calldata data) external {
(uint256 poolAmountIn, uint256[] memory minAmountsOut) =
abi.decode(data, (uint256, uint256[]));
_approve(IERC20(poolAddress), poolAddress, poolAmountIn);
IBalancerPool(poolAddress).exitPool(poolAmountIn, minAmountsOut);
}
function _approve(
IERC20 token,
address poolAddress,
uint256 amount
) internal {
uint256 currentAllowance = token.allowance(address(this), poolAddress);
if (currentAllowance < amount) {
token.safeIncreaseAllowance(poolAddress, type(uint256).max.sub(currentAllowance));
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.11;
interface IBalancerPool {
event Approval(address indexed src, address indexed dst, uint amt);
event Transfer(address indexed src, address indexed dst, uint amt);
function totalSupply() external view returns (uint);
function balanceOf(address whom) external view returns (uint);
function allowance(address src, address dst) external view returns (uint);
function approve(address dst, uint amt) external returns (bool);
function transfer(address dst, uint amt) external returns (bool);
function transferFrom(
address src, address dst, uint amt
) external returns (bool);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function getBalance(address token) external view returns (uint);
function decimals() external view returns(uint8);
function isFinalized() external view returns (bool);
function getFinalTokens()
external view
returns (address[] memory tokens);
}
|
Returns the largest of two numbers./
|
function permissionedDepositors(address account) external returns (bool);
function setUserSchedules(address account, uint256[] calldata userSchedulesIdxs) external;
function addSchedule(StakingSchedule memory schedule) external;
function getSchedules() external view returns (StakingScheduleInfo[] memory);
function setPermissionedDepositor(address account, bool canDeposit) external;
function removeSchedule(uint256 scheduleIndex) external;
function getStakes(address account) external view returns(StakingDetails[] memory);
function balanceOf(address account) external view returns(uint256);
function availableForWithdrawal(address account, uint256 scheduleIndex) external view returns (uint256);
function unvested(address account, uint256 scheduleIndex) external view returns(uint256);
function vested(address account, uint256 scheduleIndex) external view returns(uint256);
function deposit(uint256 amount, uint256 scheduleIndex) external;
function depositFor(address account, uint256 amount, uint256 scheduleIndex) external;
function depositWithSchedule(address account, uint256 amount, StakingSchedule calldata schedule) external;
function requestWithdrawal(uint256 amount) external;
function withdraw(uint256 amount) external;
function pause() external;
function unpause() external;
}
pragma solidity >=0.6.0 <0.8.0;
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
| 6,377,840 |
./full_match/44787/0x0aAA859ae2C87d201EfD4aE3834D9633e9b54AfA/sources/contracts/ambassadors/AmbassadorsImplementation.sol
|
Returns boolean whether an address is ambassador at a given entity. _ambassador Address of the ambassador _entityAddress Address of the entity return Boolean whether an address is ambassador at a given entity or not/
|
function isAmbassadorAt(address _ambassador, address _entityAddress)
public
view
override
returns (bool)
{
return
ambassadorToEntity[ambassadorByAddress[_ambassador]] == entityByAddress[_entityAddress];
}
| 13,271,875 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.