file_name
stringlengths 71
779k
| comments
stringlengths 20
182k
| code_string
stringlengths 20
36.9M
| __index_level_0__
int64 0
17.2M
| input_ids
sequence | attention_mask
sequence | labels
sequence |
---|---|---|---|---|---|---|
./partial_match/1/0xcC48E741996B0d77b38d9dC2bf9217e65E368E06/sources/Mailbox.sol | * @notice Verifies that a quorum of the origin domain's validators signed a checkpoint, and verifies the merkle proof of `_message` against that checkpoint. @param _metadata ABI encoded module metadata (see MultisigIsmMetadata.sol) @param _message Formatted Hyperlane message (see Message.sol)./ | function verify(bytes calldata _metadata, bytes calldata _message)
public
view
returns (bool)
{
require(_verifyMerkleProof(_metadata, _message), "!merkle");
require(_verifyValidatorSignatures(_metadata, _message), "!sigs");
return true;
}
| 4,298,036 | [
1,
19802,
716,
279,
31854,
434,
326,
4026,
2461,
1807,
11632,
6726,
279,
9776,
16,
471,
20761,
326,
30235,
14601,
434,
1375,
67,
2150,
68,
5314,
716,
9776,
18,
225,
389,
4165,
10336,
45,
3749,
1605,
1982,
261,
5946,
7778,
291,
360,
2520,
81,
2277,
18,
18281,
13,
225,
389,
2150,
4077,
2344,
18274,
29351,
883,
261,
5946,
2350,
18,
18281,
2934,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
3929,
12,
3890,
745,
892,
389,
4165,
16,
1731,
745,
892,
389,
2150,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
2583,
24899,
8705,
8478,
15609,
20439,
24899,
4165,
16,
389,
2150,
3631,
17528,
6592,
15609,
8863,
203,
3639,
2583,
24899,
8705,
5126,
23918,
24899,
4165,
16,
389,
2150,
3631,
17528,
7340,
87,
8863,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
// File: contracts/core/iface/IAgentRegistry.sol
// Copyright 2017 Loopring Technology Limited.
interface IAgent{}
abstract contract IAgentRegistry
{
/// @dev Returns whether an agent address is an agent of an account owner
/// @param owner The account owner.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address owner,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is an agent of all account owners
/// @param owners The account owners.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address[] calldata owners,
address agent
)
external
virtual
view
returns (bool);
/// @dev Returns whether an agent address is a universal agent.
/// @param agent The agent address
/// @return True if the agent address is a universal agent, else false
function isUniversalAgent(address agent)
public
virtual
view
returns (bool);
}
// File: contracts/lib/Ownable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// File: contracts/lib/Claimable.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @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, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
// File: contracts/core/iface/IBlockVerifier.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockVerifier
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockVerifier is Claimable
{
// -- Events --
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
// -- Public functions --
/// @dev Sets the verifying key for the specified circuit.
/// Every block permutation needs its own circuit and thus its own set of
/// verification keys. Only a limited number of block sizes per block
/// type are supported.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param vk The verification key
function registerCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[18] calldata vk
)
external
virtual;
/// @dev Disables the use of the specified circuit.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
function disableCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual;
/// @dev Verifies blocks with the given public data and proofs.
/// Verifying a block makes sure all requests handled in the block
/// are correctly handled by the operator.
/// @param blockType The type of block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param publicInputs The hash of all the public data of the blocks
/// @param proofs The ZK proofs proving that the blocks are correct
/// @return True if the block is valid, false otherwise
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit with the specified parameters is registered.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is registered, false otherwise
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit can still be used to commit new blocks.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is enabled, false otherwise
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
}
// File: contracts/core/iface/IDepositContract.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IDepositContract.
/// @dev Contract storing and transferring funds for an exchange.
///
/// ERC1155 tokens can be supported by registering pseudo token addresses calculated
/// as `address(keccak256(real_token_address, token_params))`. Then the custom
/// deposit contract can look up the real token address and paramsters with the
/// pseudo token address before doing the transfers.
/// @author Brecht Devos - <[email protected]>
interface IDepositContract
{
/// @dev Returns if a token is suppoprted by this contract.
function isTokenSupported(address token)
external
view
returns (bool);
/// @dev Transfers tokens from a user to the exchange. This function will
/// be called when a user deposits funds to the exchange.
/// In a simple implementation the funds are simply stored inside the
/// deposit contract directly. More advanced implementations may store the funds
/// in some DeFi application to earn interest, so this function could directly
/// call the necessary functions to store the funds there.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens to transfer.
/// @param extraData Opaque data that can be used by the contract to handle the deposit
/// @return amountReceived The amount to deposit to the user's account in the Merkle tree
function deposit(
address from,
address token,
uint96 amount,
bytes calldata extraData
)
external
payable
returns (uint96 amountReceived);
/// @dev Transfers tokens from the exchange to a user. This function will
/// be called when a withdrawal is done for a user on the exchange.
/// In the simplest implementation the funds are simply stored inside the
/// deposit contract directly so this simply transfers the requested tokens back
/// to the user. More advanced implementations may store the funds
/// in some DeFi application to earn interest so the function would
/// need to get those tokens back from the DeFi application first before they
/// can be transferred to the user.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address from which 'amount' tokens are transferred.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens transferred.
/// @param extraData Opaque data that can be used by the contract to handle the withdrawal
function withdraw(
address from,
address to,
address token,
uint amount,
bytes calldata extraData
)
external
payable;
/// @dev Transfers tokens (ETH not supported) for a user using the allowance set
/// for the exchange. This way the approval can be used for all functionality (and
/// extended functionality) of the exchange.
/// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`
/// should be used for that as they will contain specialised logic for those operations.
/// This function can be called by the exchange to transfer onchain funds of users
/// necessary for Agent functionality.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function transfer(
address from,
address to,
address token,
uint amount
)
external
payable;
/// @dev Checks if the given address is used for depositing ETH or not.
/// Is used while depositing to send the correct ETH amount to the deposit contract.
///
/// Note that 0x0 is always registered for deposting ETH when the exchange is created!
/// This function allows additional addresses to be used for depositing ETH, the deposit
/// contract can implement different behaviour based on the address value.
///
/// @param addr The address to check
/// @return True if the address is used for depositing ETH, else false.
function isETH(address addr)
external
view
returns (bool);
}
// File: contracts/core/iface/ILoopringV3.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ILoopringV3
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract ILoopringV3 is Claimable
{
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount);
event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);
event ExchangeStakeBurned(address exchangeAddr, uint amount);
event SettingsUpdated(uint time);
// == Public Variables ==
mapping (address => uint) internal exchangeStake;
uint public totalStake;
address public blockVerifierAddress;
uint public forcedWithdrawalFee;
uint public tokenRegistrationFeeLRCBase;
uint public tokenRegistrationFeeLRCDelta;
uint8 public protocolTakerFeeBips;
uint8 public protocolMakerFeeBips;
address payable public protocolFeeVault;
// == Public Functions ==
/// @dev Returns the LRC token address
/// @return the LRC token address
function lrcAddress()
external
view
virtual
returns (address);
/// @dev Updates the global exchange settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateSettings(
address payable _protocolFeeVault, // address(0) not allowed
address _blockVerifierAddress, // address(0) not allowed
uint _forcedWithdrawalFee
)
external
virtual;
/// @dev Updates the global protocol fee settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateProtocolFeeSettings(
uint8 _protocolTakerFeeBips,
uint8 _protocolMakerFeeBips
)
external
virtual;
/// @dev Gets the amount of staked LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @return stakedLRC The amount of LRC
function getExchangeStake(
address exchangeAddr
)
public
virtual
view
returns (uint stakedLRC);
/// @dev Burns a certain amount of staked LRC for a specific exchange.
/// This function is meant to be called only from exchange contracts.
/// @return burnedLRC The amount of LRC burned. If the amount is greater than
/// the staked amount, all staked LRC will be burned.
function burnExchangeStake(
uint amount
)
external
virtual
returns (uint burnedLRC);
/// @dev Stakes more LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @param amountLRC The amount of LRC to stake
/// @return stakedLRC The total amount of LRC staked for the exchange
function depositExchangeStake(
address exchangeAddr,
uint amountLRC
)
external
virtual
returns (uint stakedLRC);
/// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.
/// This function is meant to be called only from within exchange contracts.
/// @param recipient The address to receive LRC
/// @param requestedAmount The amount of LRC to withdraw
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient,
uint requestedAmount
)
external
virtual
returns (uint amountLRC);
/// @dev Gets the protocol fee values for an exchange.
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
function getProtocolFeeValues(
)
public
virtual
view
returns (
uint8 takerFeeBips,
uint8 makerFeeBips
);
}
// File: contracts/core/iface/ExchangeData.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeData
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeData
{
// -- Enums --
enum TransactionType
{
NOOP,
DEPOSIT,
WITHDRAWAL,
TRANSFER,
SPOT_TRADE,
ACCOUNT_UPDATE,
AMM_UPDATE,
SIGNATURE_VERIFICATION
}
// -- Structs --
struct Token
{
address token;
}
struct ProtocolFeeData
{
uint32 syncedAt; // only valid before 2105 (85 years to go)
uint8 takerFeeBips;
uint8 makerFeeBips;
uint8 previousTakerFeeBips;
uint8 previousMakerFeeBips;
}
// General auxiliary data for each conditional transaction
struct AuxiliaryData
{
uint txIndex;
bool approved;
bytes data;
}
// This is the (virtual) block the owner needs to submit onchain to maintain the
// per-exchange (virtual) blockchain.
struct Block
{
uint8 blockType;
uint16 blockSize;
uint8 blockVersion;
bytes data;
uint256[8] proof;
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
// Block specific data that is only used to help process the block on-chain.
// It is not used as input for the circuits and it is not necessary for data-availability.
// This bytes array contains the abi encoded AuxiliaryData[] data.
bytes auxiliaryData;
// Arbitrary data, mainly for off-chain data-availability, i.e.,
// the multihash of the IPFS file that contains the block data.
bytes offchainData;
}
struct BlockInfo
{
// The time the block was submitted on-chain.
uint32 timestamp;
// The public data hash of the block (the 28 most significant bytes).
bytes28 blockDataHash;
}
// Represents an onchain deposit request.
struct Deposit
{
uint96 amount;
uint64 timestamp;
}
// A forced withdrawal request.
// If the actual owner of the account initiated the request (we don't know who the owner is
// at the time the request is being made) the full balance will be withdrawn.
struct ForcedWithdrawal
{
address owner;
uint64 timestamp;
}
struct Constants
{
uint SNARK_SCALAR_FIELD;
uint MAX_OPEN_FORCED_REQUESTS;
uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;
uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;
uint MAX_NUM_ACCOUNTS;
uint MAX_NUM_TOKENS;
uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;
uint MIN_TIME_IN_SHUTDOWN;
uint TX_DATA_AVAILABILITY_SIZE;
uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;
}
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint public constant MAX_OPEN_FORCED_REQUESTS = 4096;
uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days;
uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days;
uint public constant MAX_NUM_ACCOUNTS = 2 ** 32;
uint public constant MAX_NUM_TOKENS = 2 ** 16;
uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days;
uint public constant MIN_TIME_IN_SHUTDOWN = 30 days;
// The amount of bytes each rollup transaction uses in the block data for data-availability.
// This is the maximum amount of bytes of all different transaction types.
uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days;
uint32 public constant ACCOUNTID_PROTOCOLFEE = 0;
uint public constant TX_DATA_AVAILABILITY_SIZE = 68;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29;
uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39;
struct AccountLeaf
{
uint32 accountID;
address owner;
uint pubKeyX;
uint pubKeyY;
uint32 nonce;
uint feeBipsAMM;
}
struct BalanceLeaf
{
uint16 tokenID;
uint96 balance;
uint96 weightAMM;
uint storageRoot;
}
struct MerkleProof
{
ExchangeData.AccountLeaf accountLeaf;
ExchangeData.BalanceLeaf balanceLeaf;
uint[48] accountMerkleProof;
uint[24] balanceMerkleProof;
}
struct BlockContext
{
bytes32 DOMAIN_SEPARATOR;
uint32 timestamp;
}
// Represents the entire exchange state except the owner of the exchange.
struct State
{
uint32 maxAgeDepositUntilWithdrawable;
bytes32 DOMAIN_SEPARATOR;
ILoopringV3 loopring;
IBlockVerifier blockVerifier;
IAgentRegistry agentRegistry;
IDepositContract depositContract;
// The merkle root of the offchain data stored in a Merkle tree. The Merkle tree
// stores balances for users using an account model.
bytes32 merkleRoot;
// List of all blocks
mapping(uint => BlockInfo) blocks;
uint numBlocks;
// List of all tokens
Token[] tokens;
// A map from a token to its tokenID + 1
mapping (address => uint16) tokenToTokenId;
// A map from an accountID to a tokenID to if the balance is withdrawn
mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;
// A map from an account to a token to the amount withdrawable for that account.
// This is only used when the automatic distribution of the withdrawal failed.
mapping (address => mapping (uint16 => uint)) amountWithdrawable;
// A map from an account to a token to the forced withdrawal (always full balance)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
// A map from an address to a token to a deposit
mapping (address => mapping (uint16 => Deposit)) pendingDeposits;
// A map from an account owner to an approved transaction hash to if the transaction is approved or not
mapping (address => mapping (bytes32 => bool)) approvedTx;
// A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address
mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;
// Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner
uint32 numPendingForcedTransactions;
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData;
// Time when the exchange was shutdown
uint shutdownModeStartTime;
// Time when the exchange has entered withdrawal mode
uint withdrawalModeStartTime;
// Last time the protocol fee was withdrawn for a specific token
mapping (address => uint) protocolFeeLastWithdrawnTime;
}
}
// File: contracts/core/iface/IExchangeV3.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IExchangeV3
/// @dev Note that Claimable and RentrancyGuard are inherited here to
/// ensure all data members are declared on IExchangeV3 to make it
/// easy to support upgradability through proxies.
///
/// Subclasses of this contract must NOT define constructor to
/// initialize data.
///
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract IExchangeV3 is Claimable
{
// -- Events --
event ExchangeCloned(
address exchangeAddress,
address owner,
bytes32 genesisMerkleRoot
);
event TokenRegistered(
address token,
uint16 tokenId
);
event Shutdown(
uint timestamp
);
event WithdrawalModeActivated(
uint timestamp
);
event BlockSubmitted(
uint indexed blockIdx,
bytes32 merkleRoot,
bytes32 publicDataHash
);
event DepositRequested(
address from,
address to,
address token,
uint16 tokenId,
uint96 amount
);
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
event ProtocolFeesUpdated(
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
event TransactionApproved(
address owner,
bytes32 transactionHash
);
// -- Initialization --
/// @dev Initializes this exchange. This method can only be called once.
/// @param loopring The LoopringV3 contract address.
/// @param owner The owner of this exchange.
/// @param genesisMerkleRoot The initial Merkle tree state.
function initialize(
address loopring,
address owner,
bytes32 genesisMerkleRoot
)
virtual
external;
/// @dev Initialized the agent registry contract used by the exchange.
/// Can only be called by the exchange owner once.
/// @param agentRegistry The agent registry contract to be used
function setAgentRegistry(address agentRegistry)
external
virtual;
/// @dev Gets the agent registry contract used by the exchange.
/// @return the agent registry contract
function getAgentRegistry()
external
virtual
view
returns (IAgentRegistry);
/// Can only be called by the exchange owner once.
/// @param depositContract The deposit contract to be used
function setDepositContract(address depositContract)
external
virtual;
/// @dev refresh the blockVerifier contract which maybe changed in loopringV3 contract.
function refreshBlockVerifier()
external
virtual;
/// @dev Gets the deposit contract used by the exchange.
/// @return the deposit contract
function getDepositContract()
external
virtual
view
returns (IDepositContract);
// @dev Exchange owner withdraws fees from the exchange.
// @param token Fee token address
// @param feeRecipient Fee recipient address
function withdrawExchangeFees(
address token,
address feeRecipient
)
external
virtual;
// -- Constants --
/// @dev Returns a list of constants used by the exchange.
/// @return constants The list of constants.
function getConstants()
external
virtual
pure
returns(ExchangeData.Constants memory);
// -- Mode --
/// @dev Returns hether the exchange is in withdrawal mode.
/// @return Returns true if the exchange is in withdrawal mode, else false.
function isInWithdrawalMode()
external
virtual
view
returns (bool);
/// @dev Returns whether the exchange is shutdown.
/// @return Returns true if the exchange is shutdown, else false.
function isShutdown()
external
virtual
view
returns (bool);
// -- Tokens --
/// @dev Registers an ERC20 token for a token id. Note that different exchanges may have
/// different ids for the same ERC20 token.
///
/// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH),
/// and 3 is reserved for Loopring Token (LRC).
///
/// This function is only callable by the exchange owner.
///
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function registerToken(
address tokenAddress
)
external
virtual
returns (uint16 tokenID);
/// @dev Returns the id of a registered token.
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function getTokenID(
address tokenAddress
)
external
virtual
view
returns (uint16 tokenID);
/// @dev Returns the address of a registered token.
/// @param tokenID The token's ID in this exchanges.
/// @return tokenAddress The token's address
function getTokenAddress(
uint16 tokenID
)
external
virtual
view
returns (address tokenAddress);
// -- Stakes --
/// @dev Gets the amount of LRC the owner has staked onchain for this exchange.
/// The stake will be burned if the exchange does not fulfill its duty by
/// processing user requests in time. Please note that order matching may potentially
/// performed by another party and is not part of the exchange's duty.
///
/// @return The amount of LRC staked
function getExchangeStake()
external
virtual
view
returns (uint);
/// @dev Withdraws the amount staked for this exchange.
/// This can only be done if the exchange has been correctly shutdown:
/// - The exchange owner has shutdown the exchange
/// - All deposit requests are processed
/// - All funds are returned to the users (merkle root is reset to initial state)
///
/// Can only be called by the exchange owner.
///
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient
)
external
virtual
returns (uint amountLRC);
/// @dev Can by called by anyone to burn the stake of the exchange when certain
/// conditions are fulfilled.
///
/// Currently this will only burn the stake of the exchange if
/// the exchange is in withdrawal mode.
function burnExchangeStake()
external
virtual;
// -- Blocks --
/// @dev Gets the current Merkle root of this exchange's virtual blockchain.
/// @return The current Merkle root.
function getMerkleRoot()
external
virtual
view
returns (bytes32);
/// @dev Gets the height of this exchange's virtual blockchain. The block height for a
/// new exchange is 1.
/// @return The virtual blockchain height which is the index of the last block.
function getBlockHeight()
external
virtual
view
returns (uint);
/// @dev Gets some minimal info of a previously submitted block that's kept onchain.
/// A DEX can use this function to implement a payment receipt verification
/// contract with a challange-response scheme.
/// @param blockIdx The block index.
function getBlockInfo(uint blockIdx)
external
virtual
view
returns (ExchangeData.BlockInfo memory);
/// @dev Sumbits new blocks to the rollup blockchain.
///
/// This function can only be called by the exchange operator.
///
/// @param blocks The blocks being submitted
/// - blockType: The type of the new block
/// - blockSize: The number of onchain or offchain requests/settlements
/// that have been processed in this block
/// - blockVersion: The circuit version to use for verifying the block
/// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain
/// - data: The data for this block
/// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e.,
/// the multihash of the IPFS file that contains the block data.
function submitBlocks(ExchangeData.Block[] calldata blocks)
external
virtual;
/// @dev Gets the number of available forced request slots.
/// @return The number of available slots.
function getNumAvailableForcedSlots()
external
virtual
view
returns (uint);
// -- Deposits --
/// @dev Deposits Ether or ERC20 tokens to the specified account.
///
/// This function is only callable by an agent of 'from'.
///
/// A fee to the owner is paid in ETH to process the deposit.
/// The operator is not forced to do the deposit and the user can send
/// any fee amount.
///
/// @param from The address that deposits the funds to the exchange
/// @param to The account owner's address receiving the funds
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param amount The amount of tokens to deposit
/// @param auxiliaryData Optional extra data used by the deposit contract
function deposit(
address from,
address to,
address tokenAddress,
uint96 amount,
bytes calldata auxiliaryData
)
external
virtual
payable;
/// @dev Gets the amount of tokens that may be added to the owner's account.
/// @param owner The destination address for the amount deposited.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The amount of tokens pending.
function getPendingDepositAmount(
address owner,
address tokenAddress
)
external
virtual
view
returns (uint96);
// -- Withdrawals --
/// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens.
/// This request always withdraws the full balance.
///
/// This function is only callable by an agent of the account.
///
/// The total fee in ETH that the user needs to pay is 'withdrawalFee'.
/// If the user sends too much ETH the surplus is sent back immediately.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param owner The expected owner of the account
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param accountID The address the account in the Merkle tree.
function forceWithdraw(
address owner,
address tokenAddress,
uint32 accountID
)
external
virtual
payable;
/// @dev Checks if a forced withdrawal is pending for an account balance.
/// @param accountID The accountID of the account to check.
/// @param token The token address
/// @return True if a request is pending, false otherwise
function isForcedWithdrawalPending(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the
/// protocol fees account. The complete balance is always withdrawn.
///
/// Anyone can request a withdrawal of the protocol fees.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param tokenAddress The address of the token, use `0x0` for Ether.
function withdrawProtocolFees(
address tokenAddress
)
external
virtual
payable;
/// @dev Gets the time the protocol fee for a token was last withdrawn.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The time the protocol fee was last withdrawn.
function getProtocolFeeLastWithdrawnTime(
address tokenAddress
)
external
virtual
view
returns (uint);
/// @dev Allows anyone to withdraw funds for a specified user using the balances stored
/// in the Merkle tree. The funds will be sent to the owner of the acount.
///
/// Can only be used in withdrawal mode (i.e. when the owner has stopped
/// committing blocks and is not able to commit any more blocks).
///
/// This will NOT modify the onchain merkle root! The merkle root stored
/// onchain will remain the same after the withdrawal. We store if the user
/// has withdrawn the balance in State.withdrawnInWithdrawMode.
///
/// @param merkleProof The Merkle inclusion proof
function withdrawFromMerkleTree(
ExchangeData.MerkleProof calldata merkleProof
)
external
virtual;
/// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`.
/// @param accountID The accountID of the balance to check.
/// @param token The token address
/// @return True if it was already withdrawn, false otherwise
function isWithdrawnInWithdrawalMode(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Allows withdrawing funds deposited to the contract in a deposit request when
/// it was never processed by the owner within the maximum time allowed.
///
/// Can be called by anyone. The deposited tokens will be sent back to
/// the owner of the account they were deposited in.
///
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
function withdrawFromDepositRequest(
address owner,
address token
)
external
virtual;
/// @dev Allows withdrawing funds after a withdrawal request (either onchain
/// or offchain) was submitted in a block by the operator.
///
/// Can be called by anyone. The withdrawn tokens will be sent to
/// the owner of the account they were withdrawn out.
///
/// Normally it is should not be needed for users to call this manually.
/// Funds from withdrawal requests will be sent to the account owner
/// immediately by the owner when the block is submitted.
/// The user will however need to call this manually if the transfer failed.
///
/// Tokens and owners must have the same size.
///
/// @param owners The addresses of the account the withdrawal was done for.
/// @param tokens The token addresses
function withdrawFromApprovedWithdrawals(
address[] calldata owners,
address[] calldata tokens
)
external
virtual;
/// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`.
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
/// @return The amount withdrawable
function getAmountWithdrawable(
address owner,
address token
)
external
virtual
view
returns (uint);
/// @dev Notifies the exchange that the owner did not process a forced request.
/// If this is indeed the case, the exchange will enter withdrawal mode.
///
/// Can be called by anyone.
///
/// @param accountID The accountID the forced request was made for
/// @param token The token address of the the forced request
function notifyForcedRequestTooOld(
uint32 accountID,
address token
)
external
virtual;
/// @dev Allows a withdrawal to be done to an adddresss that is different
/// than initialy specified in the withdrawal request. This can be used to
/// implement functionality like fast withdrawals.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
/// @param newRecipient The new recipient address of the withdrawal.
function setWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID,
address newRecipient
)
external
virtual;
/// @dev Gets the withdrawal recipient.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
function getWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID
)
external
virtual
view
returns (address);
/// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance
/// the user has set for the exchange. This way the user only needs to approve a single exchange contract
/// for all exchange/agent features, which allows for a more seamless user experience.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function onchainTransferFrom(
address from,
address to,
address token,
uint amount
)
external
virtual;
/// @dev Allows an agent to approve a rollup tx.
///
/// This function can only be called by an agent.
///
/// @param owner The owner of the account
/// @param txHash The hash of the transaction
function approveTransaction(
address owner,
bytes32 txHash
)
external
virtual;
/// @dev Allows an agent to approve multiple rollup txs.
///
/// This function can only be called by an agent.
///
/// @param owners The account owners
/// @param txHashes The hashes of the transactions
function approveTransactions(
address[] calldata owners,
bytes32[] calldata txHashes
)
external
virtual;
/// @dev Checks if a rollup tx is approved using the tx's hash.
///
/// @param owner The owner of the account that needs to authorize the tx
/// @param txHash The hash of the transaction
/// @return True if the tx is approved, else false
function isTransactionApproved(
address owner,
bytes32 txHash
)
external
virtual
view
returns (bool);
// -- Admins --
/// @dev Sets the max time deposits have to wait before becoming withdrawable.
/// @param newValue The new value.
/// @return The old value.
function setMaxAgeDepositUntilWithdrawable(
uint32 newValue
)
external
virtual
returns (uint32);
/// @dev Returns the max time deposits have to wait before becoming withdrawable.
/// @return The value.
function getMaxAgeDepositUntilWithdrawable()
external
virtual
view
returns (uint32);
/// @dev Shuts down the exchange.
/// Once the exchange is shutdown all onchain requests are permanently disabled.
/// When all requirements are fulfilled the exchange owner can withdraw
/// the exchange stake with withdrawStake.
///
/// Note that the exchange can still enter the withdrawal mode after this function
/// has been invoked successfully. To prevent entering the withdrawal mode before the
/// the echange stake can be withdrawn, all withdrawal requests still need to be handled
/// for at least MIN_TIME_IN_SHUTDOWN seconds.
///
/// Can only be called by the exchange owner.
///
/// @return success True if the exchange is shutdown, else False
function shutdown()
external
virtual
returns (bool success);
/// @dev Gets the protocol fees for this exchange.
/// @return syncedAt The timestamp the protocol fees were last updated
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
/// @return previousTakerFeeBips The previous protocol taker fee
/// @return previousMakerFeeBips The previous protocol maker fee
function getProtocolFeeValues()
external
virtual
view
returns (
uint32 syncedAt,
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
/// @dev Gets the domain separator used in this exchange.
function getDomainSeparator()
external
virtual
view
returns (bytes32);
/// @dev set amm pool feeBips value.
function setAmmFeeBips(uint8 _feeBips)
external
virtual;
/// @dev get amm pool feeBips value.
function getAmmFeeBips()
external
virtual
view
returns (uint8);
}
// File: contracts/amm/libamm/IAmmSharedConfig.sol
// Copyright 2017 Loopring Technology Limited.
interface IAmmSharedConfig
{
function maxForcedExitAge() external view returns (uint);
function maxForcedExitCount() external view returns (uint);
function forcedExitFee() external view returns (uint);
}
// File: contracts/amm/libamm/AmmData.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmData
library AmmData
{
uint public constant POOL_TOKEN_BASE = 100 * (10 ** 8);
uint public constant POOL_TOKEN_MINTED_SUPPLY = uint96(-1);
enum PoolTxType
{
NOOP,
JOIN,
EXIT
}
struct PoolConfig
{
address sharedConfig;
address exchange;
string poolName;
uint32 accountID;
address[] tokens;
uint96[] weights;
uint8 feeBips;
string tokenSymbol;
}
struct PoolJoin
{
address owner;
uint96[] joinAmounts;
uint32[] joinStorageIDs;
uint96 mintMinAmount;
uint96 fee;
uint32 validUntil;
}
struct PoolExit
{
address owner;
uint96 burnAmount;
uint32 burnStorageID; // for pool token withdrawal from user to the pool
uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee.
uint96 fee;
uint32 validUntil;
}
struct PoolTx
{
PoolTxType txType;
bytes data;
bytes signature;
}
struct Token
{
address addr;
uint96 weight;
uint16 tokenID;
}
struct Context
{
// functional parameters
uint txIdx;
// AMM pool state variables
bytes32 domainSeparator;
uint32 accountID;
uint16 poolTokenID;
uint8 feeBips;
uint totalSupply;
Token[] tokens;
uint96[] tokenBalancesL2;
}
struct State {
// Pool token state variables
string poolName;
string symbol;
uint _totalSupply;
mapping(address => uint) balanceOf;
mapping(address => mapping(address => uint)) allowance;
mapping(address => uint) nonces;
// AMM pool state variables
IAmmSharedConfig sharedConfig;
Token[] tokens;
// The order of the following variables important to minimize loads
bytes32 exchangeDomainSeparator;
bytes32 domainSeparator;
IExchangeV3 exchange;
uint32 accountID;
uint16 poolTokenID;
uint8 feeBips;
address exchangeOwner;
uint64 shutdownTimestamp;
uint16 forcedExitCount;
// A map from a user to the forced exit.
mapping (address => PoolExit) forcedExit;
mapping (bytes32 => bool) approvedTx;
}
}
// File: contracts/aux/access/IBlockReceiver.sol
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockReceiver
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockReceiver
{
function beforeBlockSubmission(
bytes calldata txsData,
bytes calldata callbackData
)
external
virtual;
}
// File: contracts/lib/ReentrancyGuard.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ReentrancyGuard
/// @author Brecht Devos - <[email protected]>
/// @dev Exposes a modifier that guards a function against reentrancy
/// Changing the value of the same storage value multiple times in a transaction
/// is cheap (starting from Istanbul) so there is no need to minimize
/// the number of times the value is changed
contract ReentrancyGuard
{
//The default value must be 0 in order to work behind a proxy.
uint private _guardValue;
// Use this modifier on a function to prevent reentrancy
modifier nonReentrant()
{
// Check if the guard value has its original value
require(_guardValue == 0, "REENTRANCY");
// Set the value to something else
_guardValue = 1;
// Function body
_;
// Set the value back
_guardValue = 0;
}
}
// File: contracts/thirdparty/BytesUtil.sol
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
require(_bytes.length >= (_start + 20));
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) {
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) {
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) {
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) {
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) {
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) {
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) {
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) {
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) {
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// File: contracts/core/impl/libtransactions/BlockReader.sol
// Copyright 2017 Loopring Technology Limited.
/// @title BlockReader
/// @author Brecht Devos - <[email protected]>
/// @dev Utility library to read block data.
library BlockReader {
using BlockReader for ExchangeData.Block;
using BytesUtil for bytes;
uint public constant OFFSET_TO_TRANSACTIONS = 20 + 32 + 32 + 4 + 1 + 1 + 4 + 4;
struct BlockHeader
{
address exchange;
bytes32 merkleRootBefore;
bytes32 merkleRootAfter;
uint32 timestamp;
uint8 protocolTakerFeeBips;
uint8 protocolMakerFeeBips;
uint32 numConditionalTransactions;
uint32 operatorAccountID;
}
function readHeader(
bytes memory _blockData
)
internal
pure
returns (BlockHeader memory header)
{
uint offset = 0;
header.exchange = _blockData.toAddress(offset);
offset += 20;
header.merkleRootBefore = _blockData.toBytes32(offset);
offset += 32;
header.merkleRootAfter = _blockData.toBytes32(offset);
offset += 32;
header.timestamp = _blockData.toUint32(offset);
offset += 4;
header.protocolTakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.protocolMakerFeeBips = _blockData.toUint8(offset);
offset += 1;
header.numConditionalTransactions = _blockData.toUint32(offset);
offset += 4;
header.operatorAccountID = _blockData.toUint32(offset);
offset += 4;
assert(offset == OFFSET_TO_TRANSACTIONS);
}
function readTransactionData(
bytes memory data,
uint txIdx,
uint blockSize,
bytes memory txData
)
internal
pure
{
require(txIdx < blockSize, "INVALID_TX_IDX");
// The transaction was transformed to make it easier to compress.
// Transform it back here.
// Part 1
uint txDataOffset = OFFSET_TO_TRANSACTIONS +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1;
assembly {
mstore(add(txData, 32), mload(add(data, add(txDataOffset, 32))))
}
// Part 2
txDataOffset = OFFSET_TO_TRANSACTIONS +
blockSize * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_1 +
txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE_PART_2;
assembly {
mstore(add(txData, 61 /*32 + 29*/), mload(add(data, add(txDataOffset, 32))))
mstore(add(txData, 68 ), mload(add(data, add(txDataOffset, 39))))
}
}
}
// File: contracts/lib/MathUint.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
using MathUint for uint;
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function add64(
uint64 a,
uint64 b
)
internal
pure
returns (uint64 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// File: contracts/lib/EIP712.sol
// Copyright 2017 Loopring Technology Limited.
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainHash,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainHash,
dataHash
)
);
}
}
// File: contracts/lib/AddressUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
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;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success, ) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// File: contracts/lib/ERC1271.sol
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// File: contracts/lib/SignatureUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// File: contracts/core/impl/libexchange/ExchangeSignatures.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeSignatures.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeSignatures
{
using SignatureUtil for bytes32;
function requireAuthorizedTx(
ExchangeData.State storage S,
address signer,
bytes memory signature,
bytes32 txHash
)
internal // inline call
{
require(signer != address(0), "INVALID_SIGNER");
// Verify the signature if one is provided, otherwise fall back to an approved tx
if (signature.length > 0) {
require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE");
} else {
require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED");
delete S.approvedTx[signer][txHash];
}
}
}
// File: contracts/core/impl/libtransactions/AmmUpdateTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmUpdateTransaction
/// @author Brecht Devos - <[email protected]>
library AmmUpdateTransaction
{
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public AMMUPDATE_TYPEHASH = keccak256(
"AmmUpdate(address owner,uint32 accountID,uint16 tokenID,uint8 feeBips,uint96 tokenWeight,uint32 validUntil,uint32 nonce)"
);
struct AmmUpdate
{
address owner;
uint32 accountID;
uint16 tokenID;
uint8 feeBips;
uint96 tokenWeight;
uint32 validUntil;
uint32 nonce;
uint96 balance;
}
// Auxiliary data for each AMM update
struct AmmUpdateAuxiliaryData
{
bytes signature;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read in the AMM update
AmmUpdate memory update;
readTx(data, offset, update);
AmmUpdateAuxiliaryData memory auxData = abi.decode(auxiliaryData, (AmmUpdateAuxiliaryData));
// Check validUntil
require(ctx.timestamp < auxData.validUntil, "AMM_UPDATE_EXPIRED");
update.validUntil = auxData.validUntil;
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, update);
// Check the on-chain authorization
S.requireAuthorizedTx(update.owner, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
AmmUpdate memory update
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.AMM_UPDATE), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
update.owner = data.toAddressUnsafe(_offset);
_offset += 20;
update.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
update.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
update.feeBips = data.toUint8Unsafe(_offset);
_offset += 1;
update.tokenWeight = data.toUint96Unsafe(_offset);
_offset += 12;
update.nonce = data.toUint32Unsafe(_offset);
_offset += 4;
update.balance = data.toUint96Unsafe(_offset);
_offset += 12;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
AmmUpdate memory update
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
AMMUPDATE_TYPEHASH,
update.owner,
update.accountID,
update.tokenID,
update.feeBips,
update.tokenWeight,
update.validUntil,
update.nonce
)
)
);
}
}
// File: contracts/lib/MathUint96.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint96
{
function add(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function sub(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
}
// File: contracts/core/impl/libtransactions/DepositTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title DepositTransaction
/// @author Brecht Devos - <[email protected]>
library DepositTransaction
{
using BytesUtil for bytes;
using MathUint96 for uint96;
struct Deposit
{
address to;
uint32 toAccountID;
uint16 tokenID;
uint96 amount;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory /*ctx*/,
bytes memory data,
uint offset,
bytes memory /*auxiliaryData*/
)
internal
{
// Read in the deposit
Deposit memory deposit;
readTx(data, offset, deposit);
if (deposit.amount == 0) {
return;
}
// Process the deposit
ExchangeData.Deposit memory pendingDeposit = S.pendingDeposits[deposit.to][deposit.tokenID];
// Make sure the deposit was actually done
require(pendingDeposit.timestamp > 0, "DEPOSIT_DOESNT_EXIST");
// Processing partial amounts of the deposited amount is allowed.
// This is done to ensure the user can do multiple deposits after each other
// without invalidating work done by the exchange owner for previous deposit amounts.
require(pendingDeposit.amount >= deposit.amount, "INVALID_AMOUNT");
pendingDeposit.amount = pendingDeposit.amount.sub(deposit.amount);
// If the deposit was fully consumed, reset it so the storage is freed up
// and the owner receives a gas refund.
if (pendingDeposit.amount == 0) {
delete S.pendingDeposits[deposit.to][deposit.tokenID];
} else {
S.pendingDeposits[deposit.to][deposit.tokenID] = pendingDeposit;
}
}
function readTx(
bytes memory data,
uint offset,
Deposit memory deposit
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.DEPOSIT), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
deposit.to = data.toAddressUnsafe(_offset);
_offset += 20;
deposit.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
deposit.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
deposit.amount = data.toUint96Unsafe(_offset);
_offset += 12;
}
}
// File: contracts/core/impl/libtransactions/SignatureVerificationTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureVerificationTransaction
/// @author Brecht Devos - <[email protected]>
library SignatureVerificationTransaction
{
using BytesUtil for bytes;
using MathUint for uint;
struct SignatureVerification
{
address owner;
uint32 accountID;
uint256 data;
}
function readTx(
bytes memory data,
uint offset,
SignatureVerification memory verification
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.SIGNATURE_VERIFICATION), "INVALID_TX_TYPE");
_offset += 1;
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
verification.owner = data.toAddressUnsafe(_offset);
_offset += 20;
verification.accountID = data.toUint32Unsafe(_offset);
_offset += 4;
verification.data = data.toUintUnsafe(_offset);
_offset += 32;
}
}
// File: contracts/thirdparty/SafeCast.sol
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @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 uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(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 uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(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);
}
}
// File: contracts/lib/FloatUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for floats
/// @author Brecht Devos - <[email protected]>
library FloatUtil
{
using MathUint for uint;
using SafeCast for uint;
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits for the exponent
/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)
/// @return value The decoded integer value.
function decodeFloat(
uint f,
uint numBits
)
internal
pure
returns (uint96 value)
{
if (f == 0) {
return 0;
}
uint numBitsMantissa = numBits.sub(5);
uint exponent = f >> numBitsMantissa;
// log2(10**77) = 255.79 < 256
require(exponent <= 77, "EXPONENT_TOO_LARGE");
uint mantissa = f & ((1 << numBitsMantissa) - 1);
value = mantissa.mul(10 ** exponent).toUint96();
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 11 bits mantissa
/// @return value The decoded integer value.
function decodeFloat16(
uint16 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 2047) * (10 ** (uint(f) >> 11)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits exponent, 19 bits mantissa
/// @return value The decoded integer value.
function decodeFloat24(
uint24 f
)
internal
pure
returns (uint96)
{
uint value = ((uint(f) & 524287) * (10 ** (uint(f) >> 19)));
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
}
// File: contracts/core/impl/libtransactions/TransferTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title TransferTransaction
/// @author Brecht Devos - <[email protected]>
library TransferTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint24;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public TRANSFER_TYPEHASH = keccak256(
"Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)"
);
struct Transfer
{
uint32 fromAccountID;
uint32 toAccountID;
address from;
address to;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint32 validUntil;
uint32 storageID;
}
// Auxiliary data for each transfer
struct TransferAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the transfer
Transfer memory transfer;
readTx(data, offset, transfer);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
// Fill in withdrawal data missing from DA
transfer.validUntil = auxData.validUntil;
transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED");
require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer);
// Check the on-chain authorization
S.requireAuthorizedTx(transfer.from, auxData.signature, txHash);
}
function readTx(
bytes memory data,
uint offset,
Transfer memory transfer
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.TRANSFER), "INVALID_TX_TYPE");
_offset += 1;
// Check that this is a conditional transfer
require(data.toUint8Unsafe(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
transfer.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.amount = data.toUint24Unsafe(_offset).decodeFloat24();
_offset += 3;
transfer.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
transfer.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
transfer.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
transfer.to = data.toAddressUnsafe(_offset);
_offset += 20;
transfer.from = data.toAddressUnsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Transfer memory transfer
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
transfer.from,
transfer.to,
transfer.tokenID,
transfer.amount,
transfer.feeTokenID,
transfer.maxFee,
transfer.validUntil,
transfer.storageID
)
)
);
}
}
// File: contracts/core/impl/libexchange/ExchangeMode.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeMode.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeMode
{
using MathUint for uint;
function isInWithdrawalMode(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool result)
{
result = S.withdrawalModeStartTime > 0;
}
function isShutdown(
ExchangeData.State storage S
)
internal // inline call
view
returns (bool)
{
return S.shutdownModeStartTime > 0;
}
function getNumAvailableForcedSlots(
ExchangeData.State storage S
)
internal
view
returns (uint)
{
return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions;
}
}
// File: contracts/lib/Poseidon.sol
// Copyright 2017 Loopring Technology Limited.
/// @title Poseidon hash function
/// See: https://eprint.iacr.org/2019/458.pdf
/// Code auto-generated by generate_poseidon_EVM_code.py
/// @author Brecht Devos - <[email protected]>
library Poseidon
{
//
// hash_t5f6p52
//
struct HashInputs5
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
}
function hash_t5f6p52_internal(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint q
)
internal
pure
returns (uint)
{
assembly {
function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q)
nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q)
nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q)
nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q)
nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q)
nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q)
nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q)
nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q)
nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q)
nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q)
nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q)
nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q)
nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q)
nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q)
nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q)
nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q)
nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q)
nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q)
nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q)
nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q)
nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q)
nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q)
nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q)
nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q)
nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q)
}
function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := addmod(_t0, c, _q)
nt1 := addmod(_t1, c, _q)
nt2 := addmod(_t2, c, _q)
nt3 := addmod(_t3, c, _q)
nt4 := addmod(_t4, c, _q)
}
function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 {
nt0 := mulmod(_t0, _t0, _q)
nt0 := mulmod(nt0, nt0, _q)
nt0 := mulmod(_t0, nt0, _q)
nt1 := mulmod(_t1, _t1, _q)
nt1 := mulmod(nt1, nt1, _q)
nt1 := mulmod(_t1, nt1, _q)
nt2 := mulmod(_t2, _t2, _q)
nt2 := mulmod(nt2, nt2, _q)
nt2 := mulmod(_t2, nt2, _q)
nt3 := mulmod(_t3, _t3, _q)
nt3 := mulmod(nt3, nt3, _q)
nt3 := mulmod(_t3, nt3, _q)
nt4 := mulmod(_t4, _t4, _q)
nt4 := mulmod(nt4, nt4, _q)
nt4 := mulmod(_t4, nt4, _q)
}
function sbox_partial(_t, _q) -> nt {
nt := mulmod(_t, _t, _q)
nt := mulmod(nt, nt, _q)
nt := mulmod(_t, nt, _q)
}
// round 0
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 1
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 2
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 3
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 4
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 5
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 6
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 7
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 8
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 9
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 10
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 11
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 12
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 13
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 14
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 15
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 16
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 17
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 18
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 19
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 20
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 21
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 22
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 23
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 24
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 25
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 26
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 27
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 28
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 29
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 30
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 31
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 32
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 33
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 34
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 35
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 36
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 37
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 38
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 39
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 40
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 41
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 42
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 43
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 44
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 45
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 46
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 47
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 48
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 49
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 50
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 51
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 52
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 53
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 54
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849)
t0 := sbox_partial(t0, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 55
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 56
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
// round 57
t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544)
t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q)
t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q)
}
return t0;
}
function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q);
}
//
// hash_t7f6p52
//
struct HashInputs7
{
uint t0;
uint t1;
uint t2;
uint t3;
uint t4;
uint t5;
uint t6;
}
function mix(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q);
o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q);
o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q);
o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q);
o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q);
o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q);
o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q);
o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q);
o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q);
o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q);
o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q);
o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q);
o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q);
o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q);
o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q);
o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q);
o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q);
o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q);
o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q);
o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q);
o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q);
o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q);
o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q);
o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q);
o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q);
o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q);
o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q);
o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q);
o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q);
o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q);
o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q);
o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q);
o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q);
o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q);
o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q);
o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q);
o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q);
o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q);
o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q);
o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q);
o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q);
o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q);
o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q);
o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q);
o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q);
o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q);
o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q);
o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q);
o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function ark(HashInputs7 memory i, uint q, uint c) internal pure
{
HashInputs7 memory o;
o.t0 = addmod(i.t0, c, q);
o.t1 = addmod(i.t1, c, q);
o.t2 = addmod(i.t2, c, q);
o.t3 = addmod(i.t3, c, q);
o.t4 = addmod(i.t4, c, q);
o.t5 = addmod(i.t5, c, q);
o.t6 = addmod(i.t6, c, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_full(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
o.t1 = mulmod(i.t1, i.t1, q);
o.t1 = mulmod(o.t1, o.t1, q);
o.t1 = mulmod(i.t1, o.t1, q);
o.t2 = mulmod(i.t2, i.t2, q);
o.t2 = mulmod(o.t2, o.t2, q);
o.t2 = mulmod(i.t2, o.t2, q);
o.t3 = mulmod(i.t3, i.t3, q);
o.t3 = mulmod(o.t3, o.t3, q);
o.t3 = mulmod(i.t3, o.t3, q);
o.t4 = mulmod(i.t4, i.t4, q);
o.t4 = mulmod(o.t4, o.t4, q);
o.t4 = mulmod(i.t4, o.t4, q);
o.t5 = mulmod(i.t5, i.t5, q);
o.t5 = mulmod(o.t5, o.t5, q);
o.t5 = mulmod(i.t5, o.t5, q);
o.t6 = mulmod(i.t6, i.t6, q);
o.t6 = mulmod(o.t6, o.t6, q);
o.t6 = mulmod(i.t6, o.t6, q);
i.t0 = o.t0;
i.t1 = o.t1;
i.t2 = o.t2;
i.t3 = o.t3;
i.t4 = o.t4;
i.t5 = o.t5;
i.t6 = o.t6;
}
function sbox_partial(HashInputs7 memory i, uint q) internal pure
{
HashInputs7 memory o;
o.t0 = mulmod(i.t0, i.t0, q);
o.t0 = mulmod(o.t0, o.t0, q);
o.t0 = mulmod(i.t0, o.t0, q);
i.t0 = o.t0;
}
function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint)
{
// validate inputs
require(i.t0 < q, "INVALID_INPUT");
require(i.t1 < q, "INVALID_INPUT");
require(i.t2 < q, "INVALID_INPUT");
require(i.t3 < q, "INVALID_INPUT");
require(i.t4 < q, "INVALID_INPUT");
require(i.t5 < q, "INVALID_INPUT");
require(i.t6 < q, "INVALID_INPUT");
// round 0
ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522);
sbox_full(i, q);
mix(i, q);
// round 1
ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128);
sbox_full(i, q);
mix(i, q);
// round 2
ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509);
sbox_full(i, q);
mix(i, q);
// round 3
ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615);
sbox_partial(i, q);
mix(i, q);
// round 4
ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514);
sbox_partial(i, q);
mix(i, q);
// round 5
ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619);
sbox_partial(i, q);
mix(i, q);
// round 6
ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153);
sbox_partial(i, q);
mix(i, q);
// round 7
ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608);
sbox_partial(i, q);
mix(i, q);
// round 8
ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567);
sbox_partial(i, q);
mix(i, q);
// round 9
ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471);
sbox_partial(i, q);
mix(i, q);
// round 10
ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765);
sbox_partial(i, q);
mix(i, q);
// round 11
ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772);
sbox_partial(i, q);
mix(i, q);
// round 12
ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850);
sbox_partial(i, q);
mix(i, q);
// round 13
ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375);
sbox_partial(i, q);
mix(i, q);
// round 14
ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136);
sbox_partial(i, q);
mix(i, q);
// round 15
ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374);
sbox_partial(i, q);
mix(i, q);
// round 16
ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107);
sbox_partial(i, q);
mix(i, q);
// round 17
ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214);
sbox_partial(i, q);
mix(i, q);
// round 18
ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455);
sbox_partial(i, q);
mix(i, q);
// round 19
ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212);
sbox_partial(i, q);
mix(i, q);
// round 20
ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626);
sbox_partial(i, q);
mix(i, q);
// round 21
ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417);
sbox_partial(i, q);
mix(i, q);
// round 22
ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006);
sbox_partial(i, q);
mix(i, q);
// round 23
ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766);
sbox_partial(i, q);
mix(i, q);
// round 24
ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832);
sbox_partial(i, q);
mix(i, q);
// round 25
ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231);
sbox_partial(i, q);
mix(i, q);
// round 26
ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114);
sbox_partial(i, q);
mix(i, q);
// round 27
ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719);
sbox_partial(i, q);
mix(i, q);
// round 28
ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018);
sbox_partial(i, q);
mix(i, q);
// round 29
ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562);
sbox_partial(i, q);
mix(i, q);
// round 30
ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826);
sbox_partial(i, q);
mix(i, q);
// round 31
ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245);
sbox_partial(i, q);
mix(i, q);
// round 32
ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748);
sbox_partial(i, q);
mix(i, q);
// round 33
ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508);
sbox_partial(i, q);
mix(i, q);
// round 34
ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523);
sbox_partial(i, q);
mix(i, q);
// round 35
ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410);
sbox_partial(i, q);
mix(i, q);
// round 36
ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935);
sbox_partial(i, q);
mix(i, q);
// round 37
ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643);
sbox_partial(i, q);
mix(i, q);
// round 38
ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512);
sbox_partial(i, q);
mix(i, q);
// round 39
ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393);
sbox_partial(i, q);
mix(i, q);
// round 40
ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525);
sbox_partial(i, q);
mix(i, q);
// round 41
ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006);
sbox_partial(i, q);
mix(i, q);
// round 42
ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058);
sbox_partial(i, q);
mix(i, q);
// round 43
ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739);
sbox_partial(i, q);
mix(i, q);
// round 44
ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548);
sbox_partial(i, q);
mix(i, q);
// round 45
ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311);
sbox_partial(i, q);
mix(i, q);
// round 46
ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208);
sbox_partial(i, q);
mix(i, q);
// round 47
ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706);
sbox_partial(i, q);
mix(i, q);
// round 48
ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232);
sbox_partial(i, q);
mix(i, q);
// round 49
ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524);
sbox_partial(i, q);
mix(i, q);
// round 50
ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266);
sbox_partial(i, q);
mix(i, q);
// round 51
ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210);
sbox_partial(i, q);
mix(i, q);
// round 52
ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743);
sbox_partial(i, q);
mix(i, q);
// round 53
ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373);
sbox_partial(i, q);
mix(i, q);
// round 54
ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849);
sbox_partial(i, q);
mix(i, q);
// round 55
ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076);
sbox_full(i, q);
mix(i, q);
// round 56
ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047);
sbox_full(i, q);
mix(i, q);
// round 57
ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544);
sbox_full(i, q);
mix(i, q);
return i.t0;
}
}
// File: contracts/core/impl/libexchange/ExchangeBalances.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeBalances.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeBalances
{
using MathUint for uint;
function verifyAccountBalance(
uint merkleRoot,
ExchangeData.MerkleProof calldata merkleProof
)
public
pure
{
require(
isAccountBalanceCorrect(merkleRoot, merkleProof),
"INVALID_MERKLE_TREE_DATA"
);
}
function isAccountBalanceCorrect(
uint merkleRoot,
ExchangeData.MerkleProof memory merkleProof
)
public
pure
returns (bool)
{
// Calculate the Merkle root using the Merkle paths provided
uint calculatedRoot = getBalancesRoot(
merkleProof.balanceLeaf.tokenID,
merkleProof.balanceLeaf.balance,
merkleProof.balanceLeaf.weightAMM,
merkleProof.balanceLeaf.storageRoot,
merkleProof.balanceMerkleProof
);
calculatedRoot = getAccountInternalsRoot(
merkleProof.accountLeaf.accountID,
merkleProof.accountLeaf.owner,
merkleProof.accountLeaf.pubKeyX,
merkleProof.accountLeaf.pubKeyY,
merkleProof.accountLeaf.nonce,
merkleProof.accountLeaf.feeBipsAMM,
calculatedRoot,
merkleProof.accountMerkleProof
);
// Check against the expected Merkle root
return (calculatedRoot == merkleRoot);
}
function getBalancesRoot(
uint16 tokenID,
uint balance,
uint weightAMM,
uint storageRoot,
uint[24] memory balanceMerkleProof
)
private
pure
returns (uint)
{
// Hash the balance leaf
uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0);
// Calculate the Merkle root of the balance quad Merkle tree
uint _id = tokenID;
for (uint depth = 0; depth < 8; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
balanceItem = hashImpl(
balanceItem,
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceItem,
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceItem,
balanceMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
balanceItem = hashImpl(
balanceMerkleProof[base],
balanceMerkleProof[base + 1],
balanceMerkleProof[base + 2],
balanceItem
);
}
_id = _id >> 2;
}
return balanceItem;
}
function getAccountInternalsRoot(
uint32 accountID,
address owner,
uint pubKeyX,
uint pubKeyY,
uint nonce,
uint feeBipsAMM,
uint balancesRoot,
uint[48] memory accountMerkleProof
)
private
pure
returns (uint)
{
// Hash the account leaf
uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot);
// Calculate the Merkle root of the account quad Merkle tree
uint _id = accountID;
for (uint depth = 0; depth < 16; depth++) {
uint base = depth * 3;
if (_id & 3 == 0) {
accountItem = hashImpl(
accountItem,
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 1) {
accountItem = hashImpl(
accountMerkleProof[base],
accountItem,
accountMerkleProof[base + 1],
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 2) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountItem,
accountMerkleProof[base + 2]
);
} else if (_id & 3 == 3) {
accountItem = hashImpl(
accountMerkleProof[base],
accountMerkleProof[base + 1],
accountMerkleProof[base + 2],
accountItem
);
}
_id = _id >> 2;
}
return accountItem;
}
function hashAccountLeaf(
uint t0,
uint t1,
uint t2,
uint t3,
uint t4,
uint t5
)
public
pure
returns (uint)
{
Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0);
return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
function hashImpl(
uint t0,
uint t1,
uint t2,
uint t3
)
private
pure
returns (uint)
{
Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0);
return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD);
}
}
// File: contracts/lib/ERC20SafeTransfer.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 safe transfer
/// @dev see https://github.com/sec-bit/badERC20Fix
/// @author Brecht Devos - <[email protected]>
library ERC20SafeTransfer
{
function safeTransferAndVerify(
address token,
address to,
uint value
)
internal
{
safeTransferWithGasLimitAndVerify(
token,
to,
value,
gasleft()
);
}
function safeTransfer(
address token,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferWithGasLimit(
token,
to,
value,
gasleft()
);
}
function safeTransferWithGasLimitAndVerify(
address token,
address to,
uint value,
uint gasLimit
)
internal
{
require(
safeTransferWithGasLimit(token, to, value, gasLimit),
"TRANSFER_FAILURE"
);
}
function safeTransferWithGasLimit(
address token,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transfer is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function safeTransferFromAndVerify(
address token,
address from,
address to,
uint value
)
internal
{
safeTransferFromWithGasLimitAndVerify(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFromWithGasLimitAndVerify(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
{
bool result = safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasLimit
);
require(result, "TRANSFER_FAILURE");
}
function safeTransferFromWithGasLimit(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
// A transfer/transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
if (success) {
assembly {
switch returndatasize()
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 {
success := 1
}
// Standard ERC20: a single boolean value is returned which needs to be true
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
// None of the above: not successful
default {
success := 0
}
}
}
return success;
}
}
// File: contracts/core/impl/libexchange/ExchangeTokens.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeTokens.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeTokens
{
using MathUint for uint;
using ERC20SafeTransfer for address;
using ExchangeMode for ExchangeData.State;
event TokenRegistered(
address token,
uint16 tokenId
);
function getTokenAddress(
ExchangeData.State storage S,
uint16 tokenID
)
public
view
returns (address)
{
require(tokenID < S.tokens.length, "INVALID_TOKEN_ID");
return S.tokens[tokenID].token;
}
function registerToken(
ExchangeData.State storage S,
address tokenAddress
)
public
returns (uint16 tokenID)
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST");
require(S.tokens.length < ExchangeData.MAX_NUM_TOKENS, "TOKEN_REGISTRY_FULL");
// Check if the deposit contract supports the new token
if (S.depositContract != IDepositContract(0)) {
require(
S.depositContract.isTokenSupported(tokenAddress),
"UNSUPPORTED_TOKEN"
);
}
// Assign a tokenID and store the token
ExchangeData.Token memory token = ExchangeData.Token(
tokenAddress
);
tokenID = uint16(S.tokens.length);
S.tokens.push(token);
S.tokenToTokenId[tokenAddress] = tokenID + 1;
emit TokenRegistered(tokenAddress, tokenID);
}
function getTokenID(
ExchangeData.State storage S,
address tokenAddress
)
internal // inline call
view
returns (uint16 tokenID)
{
tokenID = S.tokenToTokenId[tokenAddress];
require(tokenID != 0, "TOKEN_NOT_FOUND");
tokenID = tokenID - 1;
}
}
// File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeWithdrawals.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeWithdrawals
{
enum WithdrawalCategory
{
DISTRIBUTION,
FROM_MERKLE_TREE,
FROM_DEPOSIT_REQUEST,
FROM_APPROVED_WITHDRAWAL
}
using AddressUtil for address;
using AddressUtil for address payable;
using BytesUtil for bytes;
using MathUint for uint;
using ExchangeBalances for ExchangeData.State;
using ExchangeMode for ExchangeData.State;
using ExchangeTokens for ExchangeData.State;
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
function forceWithdraw(
ExchangeData.State storage S,
address owner,
address token,
uint32 accountID
)
public
{
require(!S.isInWithdrawalMode(), "INVALID_MODE");
// Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed.
require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN");
require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID");
uint16 tokenID = S.getTokenID(token);
// A user needs to pay a fixed ETH withdrawal fee, set by the protocol.
uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee();
// Check ETH value sent, can be larger than the expected withdraw fee
require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE");
// Send surplus of ETH back to the sender
uint feeSurplus = msg.value.sub(withdrawalFeeETH);
if (feeSurplus > 0) {
msg.sender.sendETHAndVerify(feeSurplus, gasleft());
}
// There can only be a single forced withdrawal per (account, token) pair.
require(
S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0,
"WITHDRAWAL_ALREADY_PENDING"
);
// Store the forced withdrawal request data
S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({
owner: owner,
timestamp: uint64(block.timestamp)
});
// Increment the number of pending forced transactions so we can keep count.
S.numPendingForcedTransactions++;
emit ForcedWithdrawalRequested(
owner,
token,
accountID
);
}
// We alow anyone to withdraw these funds for the account owner
function withdrawFromMerkleTree(
ExchangeData.State storage S,
ExchangeData.MerkleProof calldata merkleProof
)
public
{
require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE");
address owner = merkleProof.accountLeaf.owner;
uint32 accountID = merkleProof.accountLeaf.accountID;
uint16 tokenID = merkleProof.balanceLeaf.tokenID;
uint96 balance = merkleProof.balanceLeaf.balance;
// Make sure the funds aren't withdrawn already.
require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY");
// Verify that the provided Merkle tree data is valid by using the Merkle proof.
ExchangeBalances.verifyAccountBalance(
uint(S.merkleRoot),
merkleProof
);
// Make sure the balance can only be withdrawn once
S.withdrawnInWithdrawMode[accountID][tokenID] = true;
// Transfer the tokens to the account owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_MERKLE_TREE),
owner,
owner,
tokenID,
balance,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromDepositRequest(
ExchangeData.State storage S,
address owner,
address token
)
public
{
uint16 tokenID = S.getTokenID(token);
ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID];
require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET");
// Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode
require(
block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable ||
S.isInWithdrawalMode(),
"DEPOSIT_NOT_WITHDRAWABLE_YET"
);
uint amount = deposit.amount;
// Reset the deposit request
delete S.pendingDeposits[owner][tokenID];
// Transfer the tokens
transferTokens(
S,
uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
function withdrawFromApprovedWithdrawals(
ExchangeData.State storage S,
address[] memory owners,
address[] memory tokens
)
public
{
require(owners.length == tokens.length, "INVALID_INPUT_DATA");
for (uint i = 0; i < owners.length; i++) {
address owner = owners[i];
uint16 tokenID = S.getTokenID(tokens[i]);
uint amount = S.amountWithdrawable[owner][tokenID];
// Make sure this amount can't be withdrawn again
delete S.amountWithdrawable[owner][tokenID];
// Transfer the tokens to the owner
transferTokens(
S,
uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL),
owner,
owner,
tokenID,
amount,
new bytes(0),
gasleft(),
false
);
}
}
function distributeWithdrawal(
ExchangeData.State storage S,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit
)
public
{
// Try to transfer the tokens
bool success = transferTokens(
S,
uint8(WithdrawalCategory.DISTRIBUTION),
from,
to,
tokenID,
amount,
extraData,
gasLimit,
true
);
// If the transfer was successful there's nothing left to do.
// However, if the transfer failed the tokens are still in the contract and can be
// withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal.
if (!success) {
S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount);
}
}
// == Internal and Private Functions ==
// If allowFailure is true the transfer can fail because of a transfer error or
// because the transfer uses more than `gasLimit` gas. The function
// will return true when successful, false otherwise.
// If allowFailure is false the transfer is guaranteed to succeed using
// as much gas as needed, otherwise it throws. The function always returns true.
function transferTokens(
ExchangeData.State storage S,
uint8 category,
address from,
address to,
uint16 tokenID,
uint amount,
bytes memory extraData,
uint gasLimit,
bool allowFailure
)
private
returns (bool success)
{
// Redirect withdrawals to address(0) to the protocol fee vault
if (to == address(0)) {
to = S.loopring.protocolFeeVault();
}
address token = S.getTokenAddress(tokenID);
// Transfer the tokens from the deposit contract to the owner
if (gasLimit > 0) {
try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) {
success = true;
} catch {
success = false;
}
} else {
success = false;
}
require(allowFailure || success, "TRANSFER_FAILURE");
if (success) {
emit WithdrawalCompleted(category, from, to, token, amount);
// Keep track of when the protocol fees were last withdrawn
// (only done to make this data easier available).
if (from == address(0)) {
S.protocolFeeLastWithdrawnTime[token] = block.timestamp;
}
} else {
emit WithdrawalFailed(category, from, to, token, amount);
}
}
}
// File: contracts/core/impl/libtransactions/WithdrawTransaction.sol
// Copyright 2017 Loopring Technology Limited.
/// @title WithdrawTransaction
/// @author Brecht Devos - <[email protected]>
/// @dev The following 4 types of withdrawals are supported:
/// - withdrawType = 0: offchain withdrawals with EdDSA signatures
/// - withdrawType = 1: offchain withdrawals with ECDSA signatures or onchain appprovals
/// - withdrawType = 2: onchain valid forced withdrawals (owner and accountID match), or
/// offchain operator-initiated withdrawals for protocol fees or for
/// users in shutdown mode
/// - withdrawType = 3: onchain invalid forced withdrawals (owner and accountID mismatch)
library WithdrawTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint16;
using MathUint for uint;
using ExchangeMode for ExchangeData.State;
using ExchangeSignatures for ExchangeData.State;
using ExchangeWithdrawals for ExchangeData.State;
bytes32 constant public WITHDRAWAL_TYPEHASH = keccak256(
"Withdrawal(address owner,uint32 accountID,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,address to,bytes extraData,uint256 minGas,uint32 validUntil,uint32 storageID)"
);
struct Withdrawal
{
uint withdrawalType;
address from;
uint32 fromAccountID;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
address to;
bytes extraData;
uint minGas;
uint32 validUntil;
uint32 storageID;
bytes20 onchainDataHash;
}
// Auxiliary data for each withdrawal
struct WithdrawalAuxiliaryData
{
bool storeRecipient;
uint gasLimit;
bytes signature;
uint minGas;
address to;
bytes extraData;
uint96 maxFee;
uint32 validUntil;
}
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
Withdrawal memory withdrawal;
readTx(data, offset, withdrawal);
WithdrawalAuxiliaryData memory auxData = abi.decode(auxiliaryData, (WithdrawalAuxiliaryData));
// Validate the withdrawal data not directly part of the DA
bytes20 onchainDataHash = hashOnchainData(
auxData.minGas,
auxData.to,
auxData.extraData
);
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
require(withdrawal.onchainDataHash == onchainDataHash, "INVALID_WITHDRAWAL_DATA");
// Fill in withdrawal data missing from DA
withdrawal.to = auxData.to;
withdrawal.minGas = auxData.minGas;
withdrawal.extraData = auxData.extraData;
withdrawal.maxFee = auxData.maxFee == 0 ? withdrawal.fee : auxData.maxFee;
withdrawal.validUntil = auxData.validUntil;
// If the account has an owner, don't allow withdrawing to the zero address
// (which will be the protocol fee vault contract).
require(withdrawal.from == address(0) || withdrawal.to != address(0), "INVALID_WITHDRAWAL_RECIPIENT");
if (withdrawal.withdrawalType == 0) {
// Signature checked offchain, nothing to do
} else if (withdrawal.withdrawalType == 1) {
// Validate
require(ctx.timestamp < withdrawal.validUntil, "WITHDRAWAL_EXPIRED");
require(withdrawal.fee <= withdrawal.maxFee, "WITHDRAWAL_FEE_TOO_HIGH");
// Check appproval onchain
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, withdrawal);
// Check onchain authorization
S.requireAuthorizedTx(withdrawal.from, auxData.signature, txHash);
} else if (withdrawal.withdrawalType == 2 || withdrawal.withdrawalType == 3) {
// Forced withdrawals cannot make use of certain features because the
// necessary data is not authorized by the account owner.
// For protocol fee withdrawals, `owner` and `to` are both address(0).
require(withdrawal.from == withdrawal.to, "INVALID_WITHDRAWAL_ADDRESS");
// Forced withdrawal fees are charged when the request is submitted.
require(withdrawal.fee == 0, "FEE_NOT_ZERO");
require(withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
ExchangeData.ForcedWithdrawal memory forcedWithdrawal =
S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
if (forcedWithdrawal.timestamp != 0) {
if (withdrawal.withdrawalType == 2) {
require(withdrawal.from == forcedWithdrawal.owner, "INCONSISENT_OWNER");
} else { //withdrawal.withdrawalType == 3
require(withdrawal.from != forcedWithdrawal.owner, "INCONSISENT_OWNER");
require(withdrawal.amount == 0, "UNAUTHORIZED_WITHDRAWAL");
}
// delete the withdrawal request and free a slot
delete S.pendingForcedWithdrawals[withdrawal.fromAccountID][withdrawal.tokenID];
S.numPendingForcedTransactions--;
} else {
// Allow the owner to submit full withdrawals without authorization
// - when in shutdown mode
// - to withdraw protocol fees
require(
withdrawal.fromAccountID == ExchangeData.ACCOUNTID_PROTOCOLFEE ||
S.isShutdown(),
"FULL_WITHDRAWAL_UNAUTHORIZED"
);
}
} else {
revert("INVALID_WITHDRAWAL_TYPE");
}
// Check if there is a withdrawal recipient
address recipient = S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
if (recipient != address(0)) {
// Auxiliary data is not supported
require (withdrawal.extraData.length == 0, "AUXILIARY_DATA_NOT_ALLOWED");
// Set the new recipient address
withdrawal.to = recipient;
// Allow any amount of gas to be used on this withdrawal (which allows the transfer to be skipped)
withdrawal.minGas = 0;
// Do NOT delete the recipient to prevent replay attack
// delete S.withdrawalRecipient[withdrawal.owner][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID];
} else if (auxData.storeRecipient) {
// Store the destination address to mark the withdrawal as done
require(withdrawal.to != address(0), "INVALID_DESTINATION_ADDRESS");
S.withdrawalRecipient[withdrawal.from][withdrawal.to][withdrawal.tokenID][withdrawal.amount][withdrawal.storageID] = withdrawal.to;
}
// Validate gas provided
require(auxData.gasLimit >= withdrawal.minGas, "OUT_OF_GAS_FOR_WITHDRAWAL");
// Try to transfer the tokens with the provided gas limit
S.distributeWithdrawal(
withdrawal.from,
withdrawal.to,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.extraData,
auxData.gasLimit
);
}
function readTx(
bytes memory data,
uint offset,
Withdrawal memory withdrawal
)
internal
pure
{
uint _offset = offset;
require(data.toUint8Unsafe(_offset) == uint8(ExchangeData.TransactionType.WITHDRAWAL), "INVALID_TX_TYPE");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
withdrawal.withdrawalType = data.toUint8Unsafe(_offset);
_offset += 1;
withdrawal.from = data.toAddressUnsafe(_offset);
_offset += 20;
withdrawal.fromAccountID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.tokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.amount = data.toUint96Unsafe(_offset);
_offset += 12;
withdrawal.feeTokenID = data.toUint16Unsafe(_offset);
_offset += 2;
withdrawal.fee = data.toUint16Unsafe(_offset).decodeFloat16();
_offset += 2;
withdrawal.storageID = data.toUint32Unsafe(_offset);
_offset += 4;
withdrawal.onchainDataHash = data.toBytes20Unsafe(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Withdrawal memory withdrawal
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
WITHDRAWAL_TYPEHASH,
withdrawal.from,
withdrawal.fromAccountID,
withdrawal.tokenID,
withdrawal.amount,
withdrawal.feeTokenID,
withdrawal.maxFee,
withdrawal.to,
keccak256(withdrawal.extraData),
withdrawal.minGas,
withdrawal.validUntil,
withdrawal.storageID
)
)
);
}
function hashOnchainData(
uint minGas,
address to,
bytes memory extraData
)
internal
pure
returns (bytes20)
{
// Only the 20 MSB are used, which is still 80-bit of security, which is more
// than enough, especially when combined with validUntil.
return bytes20(keccak256(
abi.encodePacked(
minGas,
to,
extraData
)
));
}
}
// File: contracts/aux/transactions/TransactionReader.sol
// Copyright 2017 Loopring Technology Limited.
/// @title TransactionReader
/// @author Brecht Devos - <[email protected]>
/// @dev Utility library to read transactions.
library TransactionReader {
using BlockReader for bytes;
using TransactionReader for ExchangeData.Block;
using BytesUtil for bytes;
function readDeposit(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
returns (DepositTransaction.Deposit memory deposit)
{
_block.readTx(txIdx, txData);
DepositTransaction.readTx(txData, 0, deposit);
}
function readWithdrawal(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
returns (WithdrawTransaction.Withdrawal memory withdrawal)
{
_block.readTx(txIdx, txData);
WithdrawTransaction.readTx(txData, 0, withdrawal);
}
function readAmmUpdate(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
returns (AmmUpdateTransaction.AmmUpdate memory ammUpdate)
{
_block.readTx(txIdx, txData);
AmmUpdateTransaction.readTx(txData, 0, ammUpdate);
}
function readTransfer(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
returns (TransferTransaction.Transfer memory transfer)
{
_block.readTx(txIdx, txData);
TransferTransaction.readTx(txData, 0, transfer);
}
function readSignatureVerification(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
returns (SignatureVerificationTransaction.SignatureVerification memory verification)
{
_block.readTx(txIdx, txData);
SignatureVerificationTransaction.readTx(txData, 0, verification);
}
function readTx(
ExchangeData.Block memory _block,
uint txIdx,
bytes memory txData
)
internal
pure
{
_block.data.readTransactionData(txIdx, _block.blockSize, txData);
}
function readTxs(
ExchangeData.Block memory _block,
uint txIdx,
uint16 numTransactions,
bytes memory txsData
)
internal
pure
{
bytes memory txData = txsData;
uint TX_DATA_AVAILABILITY_SIZE = ExchangeData.TX_DATA_AVAILABILITY_SIZE;
for (uint i = 0; i < numTransactions; i++) {
_block.data.readTransactionData(txIdx + i, _block.blockSize, txData);
assembly {
txData := add(txData, TX_DATA_AVAILABILITY_SIZE)
}
}
}
}
// File: contracts/amm/libamm/AmmUtil.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmUtil
library AmmUtil
{
using AddressUtil for address;
using BytesUtil for bytes;
using ERC20SafeTransfer for address;
using MathUint for uint;
using TransactionReader for ExchangeData.Block;
uint8 public constant L2_SIGNATURE_TYPE = 16;
function verifySignatureL2(
AmmData.Context memory ctx,
bytes memory txsData,
address owner,
bytes32 txHash,
bytes memory signature
)
internal
pure
{
// Check the signature type
require(signature.toUint8Unsafe(0) == L2_SIGNATURE_TYPE, "INVALID_SIGNATURE_TYPE");
// Read the signature verification transaction
SignatureVerificationTransaction.SignatureVerification memory verification;
SignatureVerificationTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, verification);
// Verify that the hash was signed on L2
require(
verification.owner == owner &&
verification.data == uint(txHash) >> 3,
"INVALID_OFFCHAIN_L2_APPROVAL"
);
}
function isAlmostEqualAmount(
uint96 amount,
uint96 targetAmount
)
internal
pure
returns (bool)
{
if (targetAmount == 0) {
return amount == 0;
} else {
// Max rounding error for a float24 is 2/100000
// But relayer may use float rounding multiple times
// so the range is expanded to [100000 - 8, 100000 + 8]
uint ratio = (uint(amount) * 100000) / uint(targetAmount);
return (100000 - 8) <= ratio && ratio <= (100000 + 8);
}
}
function isAlmostEqualFee(
uint96 amount,
uint96 targetAmount
)
internal
pure
returns (bool)
{
if (targetAmount == 0) {
return amount == 0;
} else {
// Max rounding error for a float16 is 5/1000
uint ratio = (uint(amount) * 1000) / uint(targetAmount);
return (1000 - 5) <= ratio && ratio <= (1000 + 5);
}
}
function transferIn(
address token,
uint amount
)
internal
{
if (token == address(0)) {
require(msg.value == amount, "INVALID_ETH_VALUE");
} else if (amount > 0) {
token.safeTransferFromAndVerify(msg.sender, address(this), amount);
}
}
function transferOut(
address token,
uint amount,
address to
)
internal
{
if (token == address(0)) {
to.sendETHAndVerify(amount, gasleft());
} else {
token.safeTransferAndVerify(to, amount);
}
}
}
// File: contracts/amm/libamm/AmmExitRequest.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmExitRequest
library AmmExitRequest
{
bytes32 constant public POOLEXIT_TYPEHASH = keccak256(
"PoolExit(address owner,uint96 burnAmount,uint32 burnStorageID,uint96[] exitMinAmounts,uint96 fee,uint32 validUntil)"
);
event PoolExitRequested(AmmData.PoolExit exit, bool force);
function exitPool(
AmmData.State storage S,
uint96 burnAmount,
uint96[] calldata exitMinAmounts,
bool force
)
public
{
require(burnAmount > 0, "INVALID_BURN_AMOUNT");
require(exitMinAmounts.length == S.tokens.length, "INVALID_EXIT_AMOUNTS");
AmmData.PoolExit memory exit = AmmData.PoolExit({
owner: msg.sender,
burnAmount: burnAmount,
burnStorageID: 0,
exitMinAmounts: exitMinAmounts,
fee: 0,
validUntil: uint32(block.timestamp + S.sharedConfig.maxForcedExitAge())
});
if (force) {
require(S.forcedExit[msg.sender].validUntil == 0, "DUPLICATE");
require(S.forcedExitCount < S.sharedConfig.maxForcedExitCount(), "TOO_MANY_FORCED_EXITS");
AmmUtil.transferIn(address(this), burnAmount);
uint feeAmount = S.sharedConfig.forcedExitFee();
AmmUtil.transferIn(address(0), feeAmount);
AmmUtil.transferOut(address(0), feeAmount, S.exchange.owner());
S.forcedExit[msg.sender] = exit;
S.forcedExitCount++;
} else {
AmmUtil.transferIn(address(0), 0);
bytes32 txHash = hash(S.domainSeparator, exit);
S.approvedTx[txHash] = true;
}
emit PoolExitRequested(exit, force);
}
function hash(
bytes32 domainSeparator,
AmmData.PoolExit memory exit
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
domainSeparator,
keccak256(
abi.encode(
POOLEXIT_TYPEHASH,
exit.owner,
exit.burnAmount,
exit.burnStorageID,
keccak256(abi.encodePacked(exit.exitMinAmounts)),
exit.fee,
exit.validUntil
)
)
);
}
}
// File: contracts/amm/libamm/AmmPoolToken.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmPoolToken
library AmmPoolToken
{
using MathUint for uint;
using MathUint96 for uint96;
using SignatureUtil for bytes32;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
function totalSupply(
AmmData.State storage S
)
internal
view
returns (uint)
{
return S._totalSupply;
}
function approve(
AmmData.State storage S,
address spender,
uint value
)
internal
returns (bool)
{
_approve(S, msg.sender, spender, value);
return true;
}
function transfer(
AmmData.State storage S,
address to,
uint value
)
internal
returns (bool)
{
_transfer(S, msg.sender, to, value);
return true;
}
function transferFrom(
AmmData.State storage S,
address from,
address to,
uint value
)
internal
returns (bool)
{
if (msg.sender != address(this) &&
S.allowance[from][msg.sender] != uint(-1)) {
S.allowance[from][msg.sender] = S.allowance[from][msg.sender].sub(value);
}
_transfer(S, from, to, value);
return true;
}
function permit(
AmmData.State storage S,
address owner,
address spender,
uint256 value,
uint256 deadline,
bytes calldata signature
)
internal
{
require(deadline >= block.timestamp, 'EXPIRED');
bytes32 hash = EIP712.hashPacked(
S.domainSeparator,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
S.nonces[owner]++,
deadline
)
)
);
require(hash.verifySignature(owner, signature), 'INVALID_SIGNATURE');
_approve(S, owner, spender, value);
}
function _approve(
AmmData.State storage S,
address owner,
address spender,
uint value
)
private
{
if (spender != address(this)) {
S.allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
function _transfer(
AmmData.State storage S,
address from,
address to,
uint value
)
private
{
S.balanceOf[from] = S.balanceOf[from].sub(value);
S.balanceOf[to] = S.balanceOf[to].add(value);
emit Transfer(from, to, value);
}
}
// File: contracts/amm/libamm/AmmExitProcess.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmExitProcess
library AmmExitProcess
{
using AmmPoolToken for AmmData.State;
using AmmUtil for AmmData.Context;
using AmmUtil for uint96;
using ERC20SafeTransfer for address;
using MathUint for uint;
using MathUint96 for uint96;
using SafeCast for uint;
using SignatureUtil for bytes32;
using TransactionReader for ExchangeData.Block;
event ForcedExitProcessed(address owner, uint96 burnAmount, uint96[] amounts);
function processExit(
AmmData.State storage S,
AmmData.Context memory ctx,
bytes memory txsData,
AmmData.PoolExit memory exit,
bytes memory signature
)
internal
{
require(exit.validUntil >= block.timestamp, "EXPIRED");
require(exit.burnAmount > 0, "ZERO_BURN_AMOUNT");
bytes32 txHash = AmmExitRequest.hash(ctx.domainSeparator, exit);
bool isForcedExit = false;
if (signature.length == 0) {
bytes32 forcedExitHash = AmmExitRequest.hash(ctx.domainSeparator, S.forcedExit[exit.owner]);
if (txHash == forcedExitHash) {
delete S.forcedExit[exit.owner];
S.forcedExitCount--;
isForcedExit = true;
} else {
require(S.approvedTx[txHash], "INVALID_ONCHAIN_APPROVAL");
delete S.approvedTx[txHash];
}
} else if (signature.length == 1) {
ctx.verifySignatureL2(txsData, exit.owner, txHash, signature);
} else {
require(txHash.verifySignature(exit.owner, signature), "INVALID_OFFCHAIN_APPROVAL");
}
(bool slippageOK, uint96[] memory amounts) = _calculateExitAmounts(ctx, exit);
TransferTransaction.Transfer memory transfer;
if (isForcedExit) {
if (!slippageOK) {
AmmUtil.transferOut(address(this), exit.burnAmount, exit.owner);
emit ForcedExitProcessed(exit.owner, 0, new uint96[](0));
return;
}
ctx.totalSupply = ctx.totalSupply.sub(exit.burnAmount);
} else {
require(slippageOK, "EXIT_SLIPPAGE_INVALID");
_burnPoolTokenOnL2(ctx, txsData, exit.burnAmount, exit.owner, exit.burnStorageID, signature, transfer);
}
// Handle liquidity tokens
for (uint i = 0; i < ctx.tokens.length; i++) {
TransferTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, transfer);
require(
transfer.fromAccountID == ctx.accountID &&
// transfer.toAccountID == UNKNOWN &&
// transfer.storageID == UNKNOWN &&
transfer.from == address(this) &&
transfer.to == exit.owner &&
transfer.tokenID == ctx.tokens[i].tokenID &&
transfer.amount.add(transfer.fee).isAlmostEqualAmount(amounts[i]),
"INVALID_EXIT_TRANSFER_TX_DATA"
);
if (transfer.fee > 0) {
require(
i == ctx.tokens.length - 1 &&
transfer.feeTokenID == ctx.tokens[i].tokenID &&
transfer.fee <= exit.fee,
"INVALID_FEES"
);
}
ctx.tokenBalancesL2[i] = ctx.tokenBalancesL2[i].sub(transfer.amount);
}
if (isForcedExit) {
emit ForcedExitProcessed(exit.owner, exit.burnAmount, amounts);
}
}
function _burnPoolTokenOnL2(
AmmData.Context memory ctx,
bytes memory txsData,
uint96 amount,
address from,
uint32 burnStorageID,
bytes memory signature,
TransferTransaction.Transfer memory transfer
)
internal
view
{
TransferTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, transfer);
require(
// transfer.fromAccountID == UNKNOWN &&
transfer.toAccountID == ctx.accountID &&
transfer.from == from &&
transfer.to == address(this) &&
transfer.tokenID == ctx.poolTokenID &&
transfer.amount.isAlmostEqualAmount(amount) &&
transfer.feeTokenID == 0 &&
transfer.fee == 0 &&
(signature.length == 0 || transfer.storageID == burnStorageID),
"INVALID_BURN_TX_DATA"
);
// Update pool balance
ctx.totalSupply = ctx.totalSupply.sub(transfer.amount);
}
function _calculateExitAmounts(
AmmData.Context memory ctx,
AmmData.PoolExit memory exit
)
private
pure
returns(
bool /* slippageOK */,
uint96[] memory amounts
)
{
amounts = new uint96[](ctx.tokens.length);
// Calculate how much will be withdrawn
uint ratio = uint(AmmData.POOL_TOKEN_BASE).mul(exit.burnAmount) / ctx.totalSupply;
for (uint i = 0; i < ctx.tokens.length; i++) {
amounts[i] = (ratio.mul(ctx.tokenBalancesL2[i]) / AmmData.POOL_TOKEN_BASE).toUint96();
if (amounts[i] < exit.exitMinAmounts[i]) {
return (false, amounts);
}
}
return (true, amounts);
}
}
// File: contracts/amm/libamm/AmmJoinRequest.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmJoinRequest
library AmmJoinRequest
{
bytes32 constant private POOLJOIN_TYPEHASH = keccak256(
"PoolJoin(address owner,uint96[] joinAmounts,uint32[] joinStorageIDs,uint96 mintMinAmount,uint96 fee,uint32 validUntil)"
);
event PoolJoinRequested(AmmData.PoolJoin join);
function joinPool(
AmmData.State storage S,
uint96[] calldata joinAmounts,
uint96 mintMinAmount,
uint96 fee
)
public
{
require(joinAmounts.length == S.tokens.length,"INVALID_PARAM_SIZE");
for (uint i = 0; i < S.tokens.length; i++) {
require(joinAmounts[i] > 0, "INVALID_VALUE");
}
AmmData.PoolJoin memory join = AmmData.PoolJoin({
owner: msg.sender,
joinAmounts: joinAmounts,
joinStorageIDs: new uint32[](0),
mintMinAmount: mintMinAmount,
fee: fee,
validUntil: uint32(block.timestamp + S.sharedConfig.maxForcedExitAge())
});
// Approve the join
bytes32 txHash = hash(S.domainSeparator, join);
S.approvedTx[txHash] = true;
emit PoolJoinRequested(join);
}
function hash(
bytes32 domainSeparator,
AmmData.PoolJoin memory join
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
domainSeparator,
keccak256(
abi.encode(
POOLJOIN_TYPEHASH,
join.owner,
keccak256(abi.encodePacked(join.joinAmounts)),
keccak256(abi.encodePacked(join.joinStorageIDs)),
join.mintMinAmount,
join.fee,
join.validUntil
)
)
);
}
}
// File: contracts/amm/libamm/AmmJoinProcess.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmJoinProcess
library AmmJoinProcess
{
using AmmPoolToken for AmmData.State;
using AmmUtil for AmmData.Context;
using AmmUtil for uint96;
using MathUint for uint;
using MathUint96 for uint96;
using SafeCast for uint;
using SignatureUtil for bytes32;
using TransactionReader for ExchangeData.Block;
// event JoinProcessed(address owner, uint96 mintAmount, uint96[] amounts);
function processJoin(
AmmData.State storage S,
AmmData.Context memory ctx,
bytes memory txsData,
AmmData.PoolJoin memory join,
bytes memory signature
)
internal
{
require(join.validUntil >= block.timestamp, "EXPIRED");
bytes32 txHash = AmmJoinRequest.hash(ctx.domainSeparator, join);
if (signature.length == 0) {
require(S.approvedTx[txHash], "INVALID_ONCHAIN_APPROVAL");
delete S.approvedTx[txHash];
} else if (signature.length == 1) {
ctx.verifySignatureL2(txsData, join.owner, txHash, signature);
} else {
require(txHash.verifySignature(join.owner, signature), "INVALID_OFFCHAIN_L1_APPROVAL");
}
// Check if the requirements are fulfilled
(bool slippageOK, uint96 mintAmount, uint96[] memory amounts) = _calculateJoinAmounts(ctx, join);
require(slippageOK, "JOIN_SLIPPAGE_INVALID");
// Handle liquidity tokens
TransferTransaction.Transfer memory transfer;
for (uint i = 0; i < ctx.tokens.length; i++) {
TransferTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, transfer);
require(
// transfer.fromAccountID == UNKNOWN &&
transfer.toAccountID == ctx.accountID &&
transfer.from == join.owner &&
transfer.to == address(this) &&
transfer.tokenID == ctx.tokens[i].tokenID &&
transfer.amount.isAlmostEqualAmount(amounts[i]) &&
(signature.length == 0 || transfer.storageID == join.joinStorageIDs[i]),
"INVALID_JOIN_TRANSFER_TX_DATA"
);
if (transfer.fee > 0) {
require(
i == ctx.tokens.length - 1 &&
transfer.feeTokenID == ctx.tokens[i].tokenID &&
transfer.fee <= join.fee,
"INVALID_FEES"
);
}
ctx.tokenBalancesL2[i] = ctx.tokenBalancesL2[i].add(transfer.amount);
}
_mintPoolTokenOnL2(ctx, txsData, mintAmount, join.owner, transfer);
// emit JoinProcessed(join.owner, mintAmount, amounts);
}
function _mintPoolTokenOnL2(
AmmData.Context memory ctx,
bytes memory txsData,
uint96 amount,
address to,
TransferTransaction.Transfer memory transfer
)
private
view
{
TransferTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, transfer);
require(
transfer.fromAccountID == ctx.accountID &&
// transfer.toAccountID == UNKNOWN &&
transfer.from == address(this) &&
transfer.to == to &&
transfer.tokenID == ctx.poolTokenID &&
transfer.amount.isAlmostEqualAmount(amount) &&
transfer.feeTokenID == 0 &&
transfer.fee == 0,
// transfer.storageID == UNKNOWN &&
"INVALID_MINT_TX_DATA"
);
// Update pool balance
ctx.totalSupply = ctx.totalSupply.add(transfer.amount);
}
function _calculateJoinAmounts(
AmmData.Context memory ctx,
AmmData.PoolJoin memory join
)
private
pure
returns(
bool slippageOK,
uint96 mintAmount,
uint96[] memory amounts
)
{
// Check if we can still use this join
amounts = new uint96[](ctx.tokens.length);
if (ctx.totalSupply == 0) {
return(true, AmmData.POOL_TOKEN_BASE.toUint96(), join.joinAmounts);
}
// Calculate the amount of pool tokens that should be minted
bool initialized = false;
for (uint i = 0; i < ctx.tokens.length; i++) {
if (ctx.tokenBalancesL2[i] > 0) {
uint amountOut = uint(join.joinAmounts[i])
.mul(ctx.totalSupply) / uint(ctx.tokenBalancesL2[i]);
if (!initialized) {
initialized = true;
mintAmount = amountOut.toUint96();
} else if (amountOut < mintAmount) {
mintAmount = amountOut.toUint96();
}
}
}
if (mintAmount == 0) {
return (false, 0, amounts);
}
// Calculate the amounts to deposit
uint ratio = uint(AmmData.POOL_TOKEN_BASE).mul(mintAmount) / ctx.totalSupply;
for (uint i = 0; i < ctx.tokens.length; i++) {
amounts[i] = (ratio.mul(ctx.tokenBalancesL2[i]) / AmmData.POOL_TOKEN_BASE).toUint96();
}
slippageOK = (mintAmount >= join.mintMinAmount);
return (slippageOK, mintAmount, amounts);
}
}
// File: contracts/amm/libamm/AmmUpdateProcess.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmUpdateProcess
library AmmUpdateProcess
{
using TransactionReader for ExchangeData.Block;
function approveAmmUpdates(
AmmData.Context memory ctx,
bytes memory txsData
)
internal
view
{
AmmUpdateTransaction.AmmUpdate memory update;
for (uint i = 0; i < ctx.tokens.length; i++) {
// Check that the AMM update in the block matches the expected update
AmmUpdateTransaction.readTx(txsData, ctx.txIdx++ * ExchangeData.TX_DATA_AVAILABILITY_SIZE, update);
require(
update.owner == address(this) &&
update.accountID == ctx.accountID &&
update.tokenID == ctx.tokens[i].tokenID &&
update.feeBips == ctx.feeBips &&
update.tokenWeight == ctx.tokens[i].weight,
"INVALID_AMM_UPDATE_TX_DATA"
);
ctx.tokenBalancesL2[i] = update.balance;
}
}
}
// File: contracts/amm/libamm/AmmBlockReceiver.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmBlockReceiver
library AmmBlockReceiver
{
using AmmExitProcess for AmmData.State;
using AmmJoinProcess for AmmData.State;
using AmmPoolToken for AmmData.State;
using AmmUpdateProcess for AmmData.Context;
using BlockReader for bytes;
function beforeBlockSubmission(
AmmData.State storage S,
bytes memory txsData,
bytes calldata callbackData
)
internal
{
AmmData.Context memory ctx = _getContext(S);
ctx.approveAmmUpdates(txsData);
_processPoolTx(S, ctx, txsData, callbackData);
// Update state
S._totalSupply = ctx.totalSupply;
// Make sure we have consumed exactly the expected number of transactions
require(txsData.length == ctx.txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE, "INVALID_NUM_TXS");
}
function _getContext(
AmmData.State storage S
)
private
view
returns (AmmData.Context memory)
{
uint size = S.tokens.length;
return AmmData.Context({
txIdx: 0,
domainSeparator: S.domainSeparator,
accountID: S.accountID,
poolTokenID: S.poolTokenID,
feeBips: S.feeBips,
totalSupply: S._totalSupply,
tokens: S.tokens,
tokenBalancesL2: new uint96[](size)
});
}
function _processPoolTx(
AmmData.State storage S,
AmmData.Context memory ctx,
bytes memory txsData,
bytes calldata callbackData
)
private
{
AmmData.PoolTx memory poolTx = abi.decode(callbackData, (AmmData.PoolTx));
if (poolTx.txType == AmmData.PoolTxType.JOIN) {
S.processJoin(
ctx,
txsData,
abi.decode(poolTx.data, (AmmData.PoolJoin)),
poolTx.signature
);
} else if (poolTx.txType == AmmData.PoolTxType.EXIT) {
S.processExit(
ctx,
txsData,
abi.decode(poolTx.data, (AmmData.PoolExit)),
poolTx.signature
);
} else {
revert("INVALID_POOL_TX_TYPE");
}
}
}
// File: contracts/lib/ERC20.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
virtual
view
returns (uint);
function balanceOf(
address who
)
public
virtual
view
returns (uint);
function allowance(
address owner,
address spender
)
public
virtual
view
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// File: contracts/amm/libamm/AmmStatus.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmStatus
library AmmStatus
{
using AmmPoolToken for AmmData.State;
using MathUint for uint;
using MathUint96 for uint96;
using SignatureUtil for bytes32;
event Shutdown(uint timestamp);
function isOnline(AmmData.State storage S)
internal
view
returns (bool)
{
return S.shutdownTimestamp == 0;
}
function setupPool(
AmmData.State storage S,
AmmData.PoolConfig calldata config
)
public
{
require(
bytes(config.poolName).length > 0 && bytes(config.tokenSymbol).length > 0,
"INVALID_NAME_OR_SYMBOL"
);
require(config.sharedConfig != address(0), "INVALID_SHARED_CONFIG");
require(config.tokens.length == config.weights.length, "INVALID_DATA");
require(config.tokens.length >= 2, "INVALID_DATA");
require(config.exchange != address(0), "INVALID_EXCHANGE");
require(config.accountID != 0, "INVALID_ACCOUNT_ID");
require(S.tokens.length == 0, "ALREADY_INITIALIZED");
S.sharedConfig = IAmmSharedConfig(config.sharedConfig);
IExchangeV3 exchange = IExchangeV3(config.exchange);
S.exchange = exchange;
S.exchangeOwner = exchange.owner();
S.exchangeDomainSeparator = exchange.getDomainSeparator();
S.accountID = config.accountID;
S.poolTokenID = exchange.getTokenID(address(this));
S.feeBips = config.feeBips;
S.domainSeparator = EIP712.hash(EIP712.Domain(config.poolName, "1.0.0", address(this)));
S.poolName = config.poolName;
S.symbol = config.tokenSymbol;
for (uint i = 0; i < config.tokens.length; i++) {
require(config.weights[i] > 0, "INVALID_TOKEN_WEIGHT");
address token = config.tokens[i];
S.tokens.push(AmmData.Token({
addr: token,
tokenID: exchange.getTokenID(token),
weight: config.weights[i]
}));
}
// Mint all liquidity tokens to the pool account on L2
S.balanceOf[address(this)] = AmmData.POOL_TOKEN_MINTED_SUPPLY;
S.allowance[address(this)][address(exchange.getDepositContract())] = uint(-1);
exchange.deposit(
address(this), // from
address(this), // to
address(this), // token
uint96(AmmData.POOL_TOKEN_MINTED_SUPPLY),
new bytes(0)
);
}
// Anyone is able to shut down the pool when requests aren't being processed any more.
function shutdown(
AmmData.State storage S,
address exitOwner
)
public
{
// If the exchange is in withdrawal mode allow the pool to be shutdown immediately
if (!S.exchange.isInWithdrawalMode()) {
uint64 validUntil = S.forcedExit[exitOwner].validUntil;
require(validUntil > 0 && validUntil < block.timestamp, "INVALID_CHALLENGE");
uint size = S.tokens.length;
for (uint i = 0; i < size; i++) {
S.exchange.forceWithdraw{value: msg.value / size}(
address(this),
S.tokens[i].addr,
S.accountID
);
}
}
S.shutdownTimestamp = uint64(block.timestamp);
emit Shutdown(block.timestamp);
}
// Anyone is able to update the cached exchange owner to the current owner.
function updateExchangeOwnerAndFeeBips(AmmData.State storage S)
public
{
S.exchangeOwner = S.exchange.owner();
S.feeBips = S.exchange.getAmmFeeBips();
}
}
// File: contracts/amm/libamm/AmmWithdrawal.sol
// Copyright 2017 Loopring Technology Limited.
/// @title AmmWithdrawal
library AmmWithdrawal
{
using AmmPoolToken for AmmData.State;
using AmmStatus for AmmData.State;
using MathUint for uint;
function withdrawWhenOffline(
AmmData.State storage S
)
public
{
_checkWithdrawalConditionInShutdown(S);
// Burn the full balance
uint poolAmount = S.balanceOf[msg.sender];
if (poolAmount > 0) {
S.transfer(address(this), poolAmount);
}
// Burn any additional pool tokens stuck in forced exits
AmmData.PoolExit storage exit = S.forcedExit[msg.sender];
if (exit.burnAmount > 0) {
poolAmount = poolAmount.add(exit.burnAmount);
delete S.forcedExit[msg.sender];
}
require(poolAmount > 0, "ZERO_POOL_AMOUNT");
// Withdraw the part owned of the pool
uint totalSupply = S.totalSupply();
for (uint i = 0; i < S.tokens.length; i++) {
address token = S.tokens[i].addr;
uint balance = token == address(0) ?
address(this).balance :
ERC20(token).balanceOf(address(this));
uint amount = balance.mul(poolAmount) / totalSupply;
AmmUtil.transferOut(token, amount, msg.sender);
}
S._totalSupply = S._totalSupply.sub(poolAmount);
}
function _checkWithdrawalConditionInShutdown(
AmmData.State storage S
)
private
view
{
IExchangeV3 exchange = S.exchange;
bool withdrawalMode = exchange.isInWithdrawalMode();
for (uint i = 0; i < S.tokens.length; i++) {
address token = S.tokens[i].addr;
require(
withdrawalMode && exchange.isWithdrawnInWithdrawalMode(S.accountID, token) ||
!withdrawalMode && !exchange.isForcedWithdrawalPending(S.accountID, token),
"PENDING_WITHDRAWAL"
);
// Check that nothing is withdrawable anymore.
require(
exchange.getAmountWithdrawable(address(this), token) == 0,
"MORE_TO_WITHDRAW"
);
}
}
}
// File: contracts/lib/ERC2612.sol
// Copyright 2017 Loopring Technology Limited.
/// @title ERC2612 Token with permit – 712-signed approvals but with
/// bytes as signature
/// @dev see https://eips.ethereum.org/EIPS/eip-2612
/// @author Daniel Wang - <[email protected]>
abstract contract ERC2612 is ERC20
{
function nonces(address owner)
public
view
virtual
returns (uint);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
bytes calldata signature
)
external
virtual;
}
// File: contracts/amm/PoolToken.sol
// Copyright 2017 Loopring Technology Limited.
abstract contract PoolToken is ERC2612 {
using MathUint for uint;
using AmmPoolToken for AmmData.State;
uint public constant decimals = 8;
AmmData.State state;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name()
public
view
returns (string memory)
{
return state.poolName;
}
function symbol()
public
view
returns (string memory)
{
return state.symbol;
}
function totalSupply()
public
view
override
returns (uint)
{
return state.totalSupply();
}
function balanceOf(address owner)
public
view
override
returns (uint balance)
{
return state.balanceOf[owner];
}
function allowance(address owner, address spender)
public
view
override
returns (uint)
{
return spender == address(this) ?
uint(-1) :
state.allowance[owner][spender];
}
function nonces(address owner)
public
view
override
returns (uint)
{
return state.nonces[owner];
}
function approve(address spender, uint value)
public
override
returns (bool)
{
return state.approve(spender, value);
}
function transfer(address to, uint value)
public
override
returns (bool)
{
return state.transfer(to, value);
}
function transferFrom(address from, address to, uint value)
public
override
returns (bool)
{
return state.transferFrom(from, to, value);
}
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
bytes calldata signature
)
external
override
{
state.permit(owner, spender, value, deadline, signature);
}
}
// File: contracts/amm/LoopringAmmPool.sol
// Copyright 2017 Loopring Technology Limited.
// import "../lib/Drainable.sol";
/// @title LoopringAmmPool
contract LoopringAmmPool is
PoolToken,
IAgent,
IBlockReceiver,
ReentrancyGuard
{
using AmmBlockReceiver for AmmData.State;
using AmmJoinRequest for AmmData.State;
using AmmExitRequest for AmmData.State;
using AmmPoolToken for AmmData.State;
using AmmStatus for AmmData.State;
using AmmWithdrawal for AmmData.State;
event PoolJoinRequested(AmmData.PoolJoin join);
event PoolExitRequested(AmmData.PoolExit exit, bool force);
event ForcedExitProcessed(address owner, uint96 burnAmount, uint96[] amounts);
event Shutdown(uint timestamp);
modifier onlyFromExchangeOwner()
{
require(msg.sender == state.exchangeOwner, "UNAUTHORIZED");
_;
}
modifier onlyWhenOnline()
{
require(state.isOnline(), "NOT_ONLINE");
_;
}
modifier onlyWhenOffline()
{
require(!state.isOnline(), "NOT_OFFLINE");
_;
}
function isOnline()
public
view
returns (bool)
{
return state.isOnline();
}
receive() payable external {}
function setupPool(AmmData.PoolConfig calldata config)
external
nonReentrant
{
state.setupPool(config);
}
// Anyone is able to shut down the pool when requests aren't being processed any more.
function shutdown(address exitOwner)
external
payable
onlyWhenOnline
nonReentrant
{
state.shutdown(exitOwner);
}
function joinPool(
uint96[] calldata joinAmounts,
uint96 mintMinAmount,
uint96 fee
)
external
payable
onlyWhenOnline
nonReentrant
{
state.joinPool(joinAmounts, mintMinAmount, fee);
}
function exitPool(
uint96 burnAmount,
uint96[] calldata exitMinAmounts
)
external
payable
onlyWhenOnline
nonReentrant
{
state.exitPool(burnAmount, exitMinAmounts, false);
}
function forceExitPool(
uint96 burnAmount,
uint96[] calldata exitMinAmounts
)
external
payable
onlyWhenOnline
nonReentrant
{
state.exitPool(burnAmount, exitMinAmounts, true);
}
function beforeBlockSubmission(
bytes calldata txsData,
bytes calldata callbackData
)
external
override
onlyWhenOnline
onlyFromExchangeOwner
// nonReentrant // Not needed, does not do any external calls
// and can only be called by the exchange owner.
{
state.beforeBlockSubmission(txsData, callbackData);
}
function withdrawWhenOffline()
external
onlyWhenOffline
nonReentrant
{
state.withdrawWhenOffline();
}
function updateExchangeOwnerAndFeeBips()
external
nonReentrant
{
state.updateExchangeOwnerAndFeeBips();
}
} | Update state Make sure we have consumed exactly the expected number of transactions | {
AmmData.Context memory ctx = _getContext(S);
ctx.approveAmmUpdates(txsData);
_processPoolTx(S, ctx, txsData, callbackData);
S._totalSupply = ctx.totalSupply;
require(txsData.length == ctx.txIdx * ExchangeData.TX_DATA_AVAILABILITY_SIZE, "INVALID_NUM_TXS");
}
| 6,318,370 | [
1,
1891,
919,
4344,
3071,
732,
1240,
12393,
8950,
326,
2665,
1300,
434,
8938,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
3986,
81,
751,
18,
1042,
3778,
1103,
273,
389,
29120,
12,
55,
1769,
203,
203,
3639,
1103,
18,
12908,
537,
37,
7020,
5121,
12,
978,
87,
751,
1769,
203,
203,
3639,
389,
2567,
2864,
4188,
12,
55,
16,
1103,
16,
20599,
751,
16,
1348,
751,
1769,
203,
203,
3639,
348,
6315,
4963,
3088,
1283,
273,
1103,
18,
4963,
3088,
1283,
31,
203,
203,
3639,
2583,
12,
978,
87,
751,
18,
2469,
422,
1103,
18,
978,
4223,
380,
18903,
751,
18,
16556,
67,
4883,
67,
5856,
6575,
22879,
67,
4574,
16,
315,
9347,
67,
6069,
67,
16556,
55,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/security/Pausable.sol
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
address owner = _msgSender();
_approve(owner, spender, allowance(owner, spender) + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
address owner = _msgSender();
uint256 currentAllowance = allowance(owner, spender);
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Updates `owner` s allowance for `spender` based on spent `amount`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: RNFT.sol
pragma solidity ^0.8.9;
pragma abicoder v2;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract RiskedNFT is ERC20, Ownable, Pausable {
// CONFIG START
uint256 private initialSupply;
uint256 private denominator = 100;
uint256 private swapThreshold = 0.0000005 ether; // The contract will only swap to ETH, once the fee tokens reach the specified threshold
uint256 private devTaxBuy;
uint256 private marketingTaxBuy;
uint256 private liquidityTaxBuy;
uint256 private charityTaxBuy;
uint256 private devTaxSell;
uint256 private marketingTaxSell;
uint256 private liquidityTaxSell;
uint256 private charityTaxSell;
address private devTaxWallet;
address private marketingTaxWallet;
address private liquidityTaxWallet;
address private charityTaxWallet;
// CONFIG END
mapping (address => bool) private blacklist;
mapping (address => bool) private excludeList;
mapping (string => uint256) private buyTaxes;
mapping (string => uint256) private sellTaxes;
mapping (string => address) private taxWallets;
bool public taxStatus = true;
IUniswapV2Router02 private uniswapV2Router02;
IUniswapV2Factory private uniswapV2Factory;
IUniswapV2Pair private uniswapV2Pair;
constructor(string memory _tokenName,string memory _tokenSymbol,uint256 _supply,address[6] memory _addr,uint256[8] memory _value) ERC20(_tokenName, _tokenSymbol) payable
{
initialSupply =_supply * (10**18);
transferOwnership(_addr[5]);
uniswapV2Router02 = IUniswapV2Router02(_addr[1]);
uniswapV2Factory = IUniswapV2Factory(uniswapV2Router02.factory());
uniswapV2Pair = IUniswapV2Pair(uniswapV2Factory.createPair(address(this), uniswapV2Router02.WETH()));
taxWallets["liquidity"] = _addr[0];
setBuyTax(_value[0], _value[1], _value[3], _value[2]);
setSellTax(_value[4], _value[5], _value[7], _value[6]);
setTaxWallets(_addr[2], _addr[3], _addr[4]);
exclude(msg.sender);
exclude(address(this));
payable(_addr[0]).transfer(msg.value);
_mint(msg.sender, initialSupply);
}
uint256 private marketingTokens;
uint256 private devTokens;
uint256 private liquidityTokens;
uint256 private charityTokens;
/**
* @dev Calculates the tax, transfer it to the contract. If the user is selling, and the swap threshold is met, it executes the tax.
*/
function handleTax(address from, address to, uint256 amount) private returns (uint256) {
address[] memory sellPath = new address[](2);
sellPath[0] = address(this);
sellPath[1] = uniswapV2Router02.WETH();
if(!isExcluded(from) && !isExcluded(to)) {
uint256 tax;
uint256 baseUnit = amount / denominator;
if(from == address(uniswapV2Pair)) {
tax += baseUnit * buyTaxes["marketing"];
tax += baseUnit * buyTaxes["dev"];
tax += baseUnit * buyTaxes["liquidity"];
tax += baseUnit * buyTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * buyTaxes["marketing"];
devTokens += baseUnit * buyTaxes["dev"];
liquidityTokens += baseUnit * buyTaxes["liquidity"];
charityTokens += baseUnit * buyTaxes["charity"];
} else if(to == address(uniswapV2Pair)) {
tax += baseUnit * sellTaxes["marketing"];
tax += baseUnit * sellTaxes["dev"];
tax += baseUnit * sellTaxes["liquidity"];
tax += baseUnit * sellTaxes["charity"];
if(tax > 0) {
_transfer(from, address(this), tax);
}
marketingTokens += baseUnit * sellTaxes["marketing"];
devTokens += baseUnit * sellTaxes["dev"];
liquidityTokens += baseUnit * sellTaxes["liquidity"];
charityTokens += baseUnit * sellTaxes["charity"];
uint256 taxSum = marketingTokens + devTokens + liquidityTokens + charityTokens;
if(taxSum == 0) return amount;
uint256 ethValue = uniswapV2Router02.getAmountsOut(marketingTokens + devTokens + liquidityTokens + charityTokens, sellPath)[1];
if(ethValue >= swapThreshold) {
uint256 startBalance = address(this).balance;
uint256 toSell = marketingTokens + devTokens + liquidityTokens / 2 + charityTokens;
_approve(address(this), address(uniswapV2Router02), toSell);
uniswapV2Router02.swapExactTokensForETH(
toSell,
0,
sellPath,
address(this),
block.timestamp
);
uint256 ethGained = address(this).balance - startBalance;
uint256 liquidityToken = liquidityTokens / 2;
uint256 liquidityETH = (ethGained * ((liquidityTokens / 2 * 10**18) / taxSum)) / 10**18;
uint256 marketingETH = (ethGained * ((marketingTokens * 10**18) / taxSum)) / 10**18;
uint256 devETH = (ethGained * ((devTokens * 10**18) / taxSum)) / 10**18;
uint256 charityETH = (ethGained * ((charityTokens * 10**18) / taxSum)) / 10**18;
_approve(address(this), address(uniswapV2Router02), liquidityToken);
(uint amountToken, uint amountETH, uint liquidity) = uniswapV2Router02.addLiquidityETH{value: liquidityETH}(
address(this),
liquidityToken,
0,
0,
taxWallets["liquidity"],
block.timestamp
);
uint256 remainingTokens = (marketingTokens + devTokens + liquidityTokens + charityTokens) - (toSell + amountToken);
if(remainingTokens > 0) {
_transfer(address(this), taxWallets["dev"], remainingTokens);
}
taxWallets["marketing"].call{value: marketingETH}("");
taxWallets["dev"].call{value: devETH}("");
taxWallets["charity"].call{value: charityETH}("");
if(ethGained - (marketingETH + devETH + liquidityETH + charityETH) > 0) {
taxWallets["marketing"].call{value: ethGained - (marketingETH + devETH + liquidityETH + charityETH)}("");
}
marketingTokens = 0;
devTokens = 0;
liquidityTokens = 0;
charityTokens = 0;
}
}
amount -= tax;
}
return amount;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal override virtual {
require(!paused(), "RiskedNFT: token transfer while paused");
require(!isBlacklisted(msg.sender), "RiskedNFT: sender blacklisted");
require(!isBlacklisted(recipient), "RiskedNFT: recipient blacklisted");
require(!isBlacklisted(tx.origin), "RiskedNFT: sender blacklisted");
if(taxStatus) {
amount = handleTax(sender, recipient, amount);
}
super._transfer(sender, recipient, amount);
}
/**
* @dev Triggers the tax handling functionality
*/
function triggerTax() public onlyOwner {
handleTax(address(0), address(uniswapV2Pair), 0);
}
/**
* @dev Pauses transfers on the token.
*/
function pause() public onlyOwner {
require(!paused(), "RiskedNFT: Contract is already paused");
_pause();
}
/**
* @dev Unpauses transfers on the token.
*/
function unpause() public onlyOwner {
require(paused(), "RiskedNFT: Contract is not paused");
_unpause();
}
/**
* @dev Burns tokens from caller address.
*/
function burn(uint256 amount) public onlyOwner {
_burn(msg.sender, amount);
}
/**
* @dev Blacklists the specified account (Disables transfers to and from the account).
*/
function enableBlacklist(address account) public onlyOwner {
require(!blacklist[account], "RiskedNFT: Account is already blacklisted");
blacklist[account] = true;
}
/**
* @dev Remove the specified account from the blacklist.
*/
function disableBlacklist(address account) public onlyOwner {
require(blacklist[account], "RiskedNFT: Account is not blacklisted");
blacklist[account] = false;
}
/**
* @dev Excludes the specified account from tax.
*/
function exclude(address account) public onlyOwner {
require(!isExcluded(account), "RiskedNFT: Account is already excluded");
excludeList[account] = true;
}
/**
* @dev Re-enables tax on the specified account.
*/
function removeExclude(address account) public onlyOwner {
require(isExcluded(account), "RiskedNFT: Account is not excluded");
excludeList[account] = false;
}
/**
* @dev Sets tax for buys.
*/
function setBuyTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
buyTaxes["dev"] = dev;
buyTaxes["marketing"] = marketing;
buyTaxes["liquidity"] = liquidity;
buyTaxes["charity"] = charity;
}
/**
* @dev Sets tax for sells.
*/
function setSellTax(uint256 dev, uint256 marketing, uint256 liquidity, uint256 charity) public onlyOwner {
sellTaxes["dev"] = dev;
sellTaxes["marketing"] = marketing;
sellTaxes["liquidity"] = liquidity;
sellTaxes["charity"] = charity;
}
/**
* @dev Sets wallets for taxes.
*/
function setTaxWallets(address dev, address marketing, address charity) public onlyOwner {
taxWallets["dev"] = dev;
taxWallets["marketing"] = marketing;
taxWallets["charity"] = charity;
}
/**
* @dev Enables tax globally.
*/
function enableTax() public onlyOwner {
require(!taxStatus, "RiskedNFT: Tax is already enabled");
taxStatus = true;
}
/**
* @dev Disables tax globally.
*/
function disableTax() public onlyOwner {
require(taxStatus, "RiskedNFT: Tax is already disabled");
taxStatus = false;
}
/**
* @dev Returns true if the account is blacklisted, and false otherwise.
*/
function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
/**
* @dev Returns true if the account is excluded, and false otherwise.
*/
function isExcluded(address account) public view returns (bool) {
return excludeList[account];
}
receive() external payable {}
} | * @dev Returns true if the account is blacklisted, and false otherwise./ | function isBlacklisted(address account) public view returns (bool) {
return blacklist[account];
}
| 575,774 | [
1,
1356,
638,
309,
326,
2236,
353,
25350,
16,
471,
629,
3541,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
353,
13155,
18647,
12,
2867,
2236,
13,
1071,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
11709,
63,
4631,
15533,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint256 public numRegisteredAirlines;
uint256 public numRegisteredPassengers;
uint256 public numRegisteredFlights;
struct Airline {
string name;
bool isRegistered;
bool canParticipate;
uint256 funds;
address airlineAddress;
mapping(address => mapping(bytes32 => uint256)) balances; // Maps passenger address to money spent on each flight
//bytes32[] flights; // List of scheduled flights per airline
}
struct Flight {
string number;
bool isRegistered;
uint8 statusCode;
string updatedTimeStamp;
Airline airline;
//address[] passengers;
}
struct Passenger {
string name;
address passengerAddress;
bool isRegistered;
uint256 credit;
}
mapping(address => Airline) private airlines;
mapping(bytes32 => Flight) private flights;
mapping(address => Passenger) private passengers;
mapping(bytes32 => address[]) private passengersPerFlight;
mapping(address => mapping(bytes32 => bool)) private isInsured;
//mapping(address => bytes32[]) public flightsPerAirline;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor(string _airlineName)
public
{
contractOwner = msg.sender;
airlines[msg.sender] = Airline({
name: _airlineName,
isRegistered: true,
canParticipate: false,
funds: 0,
airlineAddress: msg.sender
});
numRegisteredAirlines = numRegisteredAirlines.add(1);
}
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier isOperational()
{
require(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier onlyContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier onlyInsuredPassenger(address _passengerAddress, bytes32 key){
require(isInsured[_passengerAddress][key], "This passenger is not insured");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function getOperationalStatus()
public
view
returns(bool)
{
return operational;
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
*/
function setOperatingStatus(bool mode)
external
onlyContractOwner
{
operational = mode;
}
/**
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline(string _name, address _address)
external
isOperational
{
airlines[_address] = Airline({
name: _name,
isRegistered: true,
canParticipate: false,
funds: 0,
airlineAddress: _address
});
numRegisteredAirlines = numRegisteredAirlines.add(1);
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerFlight(address airlineAddress, bytes32 key, string flightNumber, string timeStamp, uint8 _statusCode)
external
isOperational
{
flights[key] = Flight({
number: flightNumber,
isRegistered: true,
statusCode: _statusCode,
updatedTimeStamp: timeStamp,
airline: airlines[airlineAddress]
});
//airlines[airlineAddress].flights.push(key);
//flightsPerAirline[airlineAddress].push(key);
numRegisteredFlights = numRegisteredFlights.add(1);
}
function registerPassenger(address _airlineAddress, string _name, address _passengerAddress, bytes32 key, uint256 amount)
external
payable
isOperational
{
passengers[_passengerAddress] = Passenger({
name: _name,
passengerAddress: _passengerAddress,
isRegistered: true,
credit: 0
});
uint256 balance = airlines[_airlineAddress].balances[_passengerAddress][key];
passengersPerFlight[key].push(_passengerAddress);
//flights[key].passengers.push(_passengerAddress);
airlines[_airlineAddress].balances[_passengerAddress][key] = balance.add(amount);
numRegisteredPassengers = numRegisteredPassengers.add(1);
}
function updateFlightStatusCode(bytes32 key, uint8 _statusCode)
external
isOperational
{
flights[key].statusCode = _statusCode;
}
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund(address _airline, uint256 amount)
external
isOperational
{
airlines[_airline].funds.add(amount);
}
/**
* @dev Buy insurance for a flight
*
*/
function buyInsurance(address _passengerAddress, address _airlineAddress, bytes32 key, uint256 amount)
external
payable
isOperational
{
airlines[_airlineAddress].balances[_passengerAddress][key].add(amount);
}
/**
* @dev Credits payouts to insuree
*/
function creditInsuree(address _passengerAddress, bytes32 key, uint factor)
internal
onlyInsuredPassenger(_passengerAddress, key)
{
uint256 _credit = airlines[msg.sender].balances[_passengerAddress][key].mul(factor);
airlines[msg.sender].balances[_passengerAddress][key] = 0;
passengers[_passengerAddress].credit.add(_credit);
}
function creditAllInsureesPerFlight(bytes32 key, uint factor)
external
{
address[] storage listOfPassengersAddress = passengersPerFlight[key];
for (uint i=0; i < listOfPassengersAddress.length; i++) {
creditInsuree(listOfPassengersAddress[i], key, factor);
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function withdraw()
external
payable
{
address targetAddress = msg.sender;
targetAddress.transfer(passengers[msg.sender].credit);
passengers[msg.sender].credit = 0;
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
}
function getTotalBalance()
external
view
returns(uint256)
{
return address(this).balance;
}
function getPassengerData(address _address)
external
view
isOperational
returns(string, bool, uint256)
{
Passenger storage passenger = passengers[_address];
return (passenger.name, passenger.isRegistered, passenger.credit);
}
function getFlightDetails(bytes32 key)
external
view
isOperational
returns(string, bool, uint8, string, string)
{
Flight storage flight = flights[key];
return (flight.number,
flight.isRegistered,
flight.statusCode,
flight.updatedTimeStamp,
flight.airline.name);
}
function getInsuranceStatus(address _passengerAddress, bytes32 flighKey)
external
view
isOperational
returns(bool)
{
return isInsured[_passengerAddress][flighKey];
}
function getAirlineData(address _airlineAddress)
external
view
isOperational
returns(string, bool, bool, uint256)
{
Airline storage airline = airlines[_airlineAddress];
return(airline.name, airline.isRegistered, airline.canParticipate, airline.funds);
}
function setParticipationStatus(address airlineAddress, bool status)
external
isOperational
{
airlines[airlineAddress].canParticipate = status;
}
function checkPassengerInsuranceStatus(address passengerAddress, bytes32 flightKey)
external
isOperational
view
returns(bool)
{
return isInsured[passengerAddress][flightKey];
}
}
| *******************************************************************************************/ DATA VARIABLES */*******************************************************************************************/bytes32[] flights; List of scheduled flights per airline | struct Airline {
string name;
bool isRegistered;
bool canParticipate;
uint256 funds;
address airlineAddress;
}
| 14,068,995 | [
1,
19,
4766,
4202,
8730,
22965,
55,
19694,
368,
3890,
1578,
8526,
1183,
10730,
31,
4766,
2868,
987,
434,
9755,
1183,
10730,
1534,
23350,
1369,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
432,
481,
1369,
288,
203,
3639,
533,
508,
31,
203,
3639,
1426,
353,
10868,
31,
203,
3639,
1426,
848,
1988,
24629,
340,
31,
203,
3639,
2254,
5034,
284,
19156,
31,
203,
3639,
1758,
23350,
1369,
1887,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.13;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/utils/cryptography/ECDSA.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
// ███████ █████ ██ ████████ ██ ██ ███████ ██ ██████ ███████ ███ ██ ██████ ██████ ███████ ██ ██
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ████ ██ ██ ██ ██ ██ ██ ██
// ███████ ███████ ██ ██ ████ ███████ ██ ██████ █████ ██ ██ ██ ██ ██████ █████ ██ █ ██
// ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ███ ██
// ███████ ██ ██ ███████ ██ ██ ███████ ██ ██ ██ ███████ ██ ████ ██████ ██ ██ ███████ ███ ███
// By the Salty Pirate Crew: 0x7a4b1a8bb6e40cbce837fb72603c8a4a20d0b3e1
contract SaltySirenCrew is ERC721, Ownable, ReentrancyGuard {
using Counters for Counters.Counter;
using ECDSA for bytes32;
uint256 public constant MAX_SUPPLY = 1200;
uint256 public constant STARTING_INDEX = 58;
uint256 public constant AIRDROP_BUFFER = 143;
Counters.Counter private _totalSupply;
address private _signer;
string public baseURI;
enum ContractState { PAUSED, UNLOCKONLY, AIRDROPONLY, UNLOCKAIRDROP }
ContractState public currentState = ContractState.PAUSED;
constructor(address __signer, string memory _URI) ERC721("SaltySirenCrew", "SSC") {
_signer = __signer;
baseURI = _URI;
}
function setBaseURI(string memory _URI) public onlyOwner {
baseURI = _URI;
}
// Sets a new contract state: PAUSED, UNLOCKONLY, AIRDROPONLY, UNLOCKAIRDROP
function setContractState(ContractState _newState) external onlyOwner {
currentState = _newState;
}
// Returns the total supply minted
function totalSupply() public view returns (uint256) {
return _totalSupply.current();
}
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
// Verifies that the sender is whitelisted
function _verifySignature(
bytes calldata signature,
uint256 tokenId,
address caller
) internal view returns (bool) {
return keccak256(abi.encodePacked(tokenId, caller))
.toEthSignedMessageHash()
.recover(signature) == _signer;
}
function unlockSiren(bytes calldata signature, uint256 _tokenId) public nonReentrant {
require(
_tokenId >= STARTING_INDEX && _tokenId <= MAX_SUPPLY - AIRDROP_BUFFER,
"Outside of unlock range"
);
require(
_verifySignature(
signature,
_tokenId,
msg.sender),
"Signature is invalid"
);
require(
currentState == ContractState.UNLOCKONLY || currentState == ContractState.UNLOCKAIRDROP,
"Contract cannot unlock Siren"
);
require(!_exists(_tokenId), "Token cannot exist");
_safeMint(msg.sender, _tokenId);
_totalSupply.increment();
}
function airdrop(uint256 tokenId, address to) public onlyOwner nonReentrant {
require(
tokenId > MAX_SUPPLY - AIRDROP_BUFFER && tokenId < MAX_SUPPLY,
"Outside of airdrop range");
require(
currentState == ContractState.AIRDROPONLY || currentState == ContractState.UNLOCKAIRDROP,
"Contract cannot airdrop"
);
require(!_exists(tokenId), "Token cannot exist");
_safeMint(to, tokenId);
_totalSupply.increment();
}
function airdropSpecial(uint256 tokenId, address to) public onlyOwner nonReentrant {
require(
tokenId >= 0 && tokenId < STARTING_INDEX,
"Outside of airdrop range"
);
require(
currentState == ContractState.AIRDROPONLY || currentState == ContractState.UNLOCKAIRDROP,
"Contract cannot airdrop"
);
require(!_exists(tokenId), "Token cannot exist");
_safeMint(to, tokenId);
_totalSupply.increment();
}
// Withdraw funds
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
Address.sendValue(payable(msg.sender), balance);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol)
pragma solidity ^0.8.0;
import "../Strings.sol";
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff);
uint8 v = uint8((uint256(vs) >> 255) + 27);
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Message, created from `s`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
} | Verifies that the sender is whitelisted | function _verifySignature(
bytes calldata signature,
uint256 tokenId,
address caller
) internal view returns (bool) {
return keccak256(abi.encodePacked(tokenId, caller))
.toEthSignedMessageHash()
.recover(signature) == _signer;
}
| 11,825,930 | [
1,
19802,
716,
326,
5793,
353,
26944,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
8705,
5374,
12,
203,
3639,
1731,
745,
892,
3372,
16,
7010,
3639,
2254,
5034,
1147,
548,
16,
7010,
3639,
1758,
4894,
203,
565,
262,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
3639,
327,
417,
24410,
581,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
2316,
548,
16,
4894,
3719,
203,
5411,
263,
869,
41,
451,
12294,
1079,
2310,
1435,
203,
5411,
263,
266,
3165,
12,
8195,
13,
422,
389,
2977,
264,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "truffle/Assert.sol";
import "truffle/DeployedAddresses.sol";
import "../contracts/Delivery.sol";
contract TestDelivery {
// The address of the delivery contract to be tested
Delivery delivery = Delivery(DeployedAddresses.Delivery());
// test that the first modifier is working
function testVerifySenderMod() public {
address owner = delivery.getOwner();
Assert.notEqual(address(this), owner, "The sender is the owner");
}
// test that the second modifier is working
function testVerifyCallerMod() public {
Assert.notEqual(address(this), msg.sender, "The sender is the caller");
}
// test for trying to ship an item that is not marked Sold
function testBasketIsCorrectlyNotarized() public{
uint basketID = 0;
delivery.addBasket("test basket", 10);
bytes32 proof = delivery.proofFor(basketID);
bytes32 referenceProof = sha256(abi.encodePacked(delivery.farmName));
Assert.equal(proof, referenceProof, "The basket has been notarized with an incorrect farm name");
}
/**
Test Section of the circuit breaker
*/
function testCircuitBreaker() public {
delivery.toggleContractActive();
bool status = delivery.deposit();
Assert.equal(status, true, "Circuit breaker should be activated");
}
// The id of the buyer that will be used for testing
uint expectedBuyerId = 8;
// The expected seller is this contract
address expectedSeller = address(this);
}
| The address of the delivery contract to be tested test that the first modifier is working | contract TestDelivery {
Delivery delivery = Delivery(DeployedAddresses.Delivery());
function testVerifySenderMod() public {
address owner = delivery.getOwner();
Assert.notEqual(address(this), owner, "The sender is the owner");
}
function testVerifyCallerMod() public {
Assert.notEqual(address(this), msg.sender, "The sender is the caller");
}
function testBasketIsCorrectlyNotarized() public{
uint basketID = 0;
delivery.addBasket("test basket", 10);
bytes32 proof = delivery.proofFor(basketID);
bytes32 referenceProof = sha256(abi.encodePacked(delivery.farmName));
Assert.equal(proof, referenceProof, "The basket has been notarized with an incorrect farm name");
}
Test Section of the circuit breaker
function testCircuitBreaker() public {
delivery.toggleContractActive();
bool status = delivery.deposit();
Assert.equal(status, true, "Circuit breaker should be activated");
}
uint expectedBuyerId = 8;
address expectedSeller = address(this);
}
| 7,275,106 | [
1,
1986,
1758,
434,
326,
7912,
6835,
358,
506,
18432,
1842,
716,
326,
1122,
9606,
353,
5960,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
7766,
8909,
288,
203,
21281,
225,
17390,
7912,
273,
17390,
12,
31954,
7148,
18,
8909,
10663,
203,
203,
225,
445,
1842,
8097,
12021,
1739,
1435,
1071,
288,
203,
565,
1758,
3410,
273,
7912,
18,
588,
5541,
5621,
203,
565,
5452,
18,
902,
5812,
12,
2867,
12,
2211,
3631,
3410,
16,
315,
1986,
5793,
353,
326,
3410,
8863,
203,
225,
289,
203,
203,
225,
445,
1842,
8097,
11095,
1739,
1435,
1071,
288,
203,
565,
5452,
18,
902,
5812,
12,
2867,
12,
2211,
3631,
1234,
18,
15330,
16,
315,
1986,
5793,
353,
326,
4894,
8863,
203,
225,
289,
21281,
203,
225,
445,
1842,
11324,
2520,
16147,
715,
1248,
297,
1235,
1435,
1071,
95,
203,
565,
2254,
12886,
734,
273,
374,
31,
203,
565,
7912,
18,
1289,
11324,
2932,
3813,
12886,
3113,
1728,
1769,
203,
565,
1731,
1578,
14601,
273,
7912,
18,
24207,
1290,
12,
26219,
734,
1769,
203,
565,
1731,
1578,
2114,
20439,
273,
6056,
5034,
12,
21457,
18,
3015,
4420,
329,
12,
15703,
18,
74,
4610,
461,
10019,
203,
203,
565,
5452,
18,
9729,
12,
24207,
16,
2114,
20439,
16,
315,
1986,
12886,
711,
2118,
486,
297,
1235,
598,
392,
11332,
284,
4610,
508,
8863,
203,
225,
289,
203,
203,
225,
7766,
10092,
434,
326,
12937,
898,
264,
203,
225,
445,
1842,
21719,
22660,
1435,
1071,
288,
203,
565,
7912,
18,
14401,
8924,
3896,
5621,
203,
565,
1426,
1267,
273,
7912,
18,
323,
1724,
5621,
203,
203,
565,
5452,
18,
9729,
12,
2327,
16,
638,
16,
315,
21719,
898,
264,
1410,
506,
14892,
8863,
2
] |
pragma solidity ^0.5.5;
library strings {
struct slice {
uint _len;
uint _ptr;
}
function MEMCPY184(uint dest, uint src, uint len) private pure { //inject NONSTANDARD NAMING
// Copy word-length chunks while possible
for(; len >= 32; len -= 32) {
assembly {
mstore(dest, mload(src))
}
dest += 32;
src += 32;
}
// Copy remaining bytes
uint mask = 256 ** (32 - len) - 1;
assembly {
let srcpart := and(mload(src), not(mask))
let destpart := and(mload(dest), mask)
mstore(dest, or(destpart, srcpart))
}
}
function TOSLICE667(string memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr;
assembly {
ptr := add(self, 0x20)
}
return slice(bytes(self).length, ptr);
}
function LEN420(bytes32 self) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint ret;
if (self == 0)
return 0;
if (uint(self) & 0xffffffffffffffffffffffffffffffff == 0) {
ret += 16;
self = bytes32(uint(self) / 0x100000000000000000000000000000000);
}
if (uint(self) & 0xffffffffffffffff == 0) {
ret += 8;
self = bytes32(uint(self) / 0x10000000000000000);
}
if (uint(self) & 0xffffffff == 0) {
ret += 4;
self = bytes32(uint(self) / 0x100000000);
}
if (uint(self) & 0xffff == 0) {
ret += 2;
self = bytes32(uint(self) / 0x10000);
}
if (uint(self) & 0xff == 0) {
ret += 1;
}
return 32 - ret;
}
function TOSLICEB32242(bytes32 self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING
// Allocate space for `self` in memory, copy it there, and point ret at it
assembly {
let ptr := mload(0x40)
mstore(0x40, add(ptr, 0x20))
mstore(ptr, self)
mstore(add(ret, 0x20), ptr)
}
ret._len = LEN420(self);
}
function COPY737(slice memory self) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
return slice(self._len, self._ptr);
}
function TOSTRING824(slice memory self) internal pure returns (string memory) { //inject NONSTANDARD NAMING
string memory ret = new string(self._len);
uint retptr;
assembly { retptr := add(ret, 32) }
MEMCPY184(retptr, self._ptr, self._len);
return ret;
}
function LEN420(slice memory self) internal pure returns (uint l) { //inject NONSTANDARD NAMING
// Starting at ptr-31 means the LSB will be the byte we care about
uint ptr = self._ptr - 31;
uint end = ptr + self._len;
for (l = 0; ptr < end; l++) {
uint8 b;
assembly { b := and(mload(ptr), 0xFF) }
if (b < 0x80) {
ptr += 1;
} else if(b < 0xE0) {
ptr += 2;
} else if(b < 0xF0) {
ptr += 3;
} else if(b < 0xF8) {
ptr += 4;
} else if(b < 0xFC) {
ptr += 5;
} else {
ptr += 6;
}
}
}
function EMPTY246(slice memory self) internal pure returns (bool) { //inject NONSTANDARD NAMING
return self._len == 0;
}
function COMPARE76(slice memory self, slice memory other) internal pure returns (int) { //inject NONSTANDARD NAMING
uint shortest = self._len;
if (other._len < self._len)
shortest = other._len;
uint selfptr = self._ptr;
uint otherptr = other._ptr;
for (uint idx = 0; idx < shortest; idx += 32) {
uint a;
uint b;
assembly {
a := mload(selfptr)
b := mload(otherptr)
}
if (a != b) {
// Mask out irrelevant bytes and check again
uint256 mask = uint256(-1); // 0xffff...
if(shortest < 32) {
mask = ~(2 ** (8 * (32 - shortest + idx)) - 1);
}
uint256 diff = (a & mask) - (b & mask);
if (diff != 0)
return int(diff);
}
selfptr += 32;
otherptr += 32;
}
return int(self._len) - int(other._len);
}
function EQUALS848(slice memory self, slice memory other) internal pure returns (bool) { //inject NONSTANDARD NAMING
return COMPARE76(self, other) == 0;
}
function NEXTRUNE884(slice memory self, slice memory rune) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
rune._ptr = self._ptr;
if (self._len == 0) {
rune._len = 0;
return rune;
}
uint l;
uint b;
// Load the first byte of the rune into the LSBs of b
assembly { b := and(mload(sub(mload(add(self, 32)), 31)), 0xFF) }
if (b < 0x80) {
l = 1;
} else if(b < 0xE0) {
l = 2;
} else if(b < 0xF0) {
l = 3;
} else {
l = 4;
}
// Check for truncated codepoints
if (l > self._len) {
rune._len = self._len;
self._ptr += self._len;
self._len = 0;
return rune;
}
self._ptr += l;
self._len -= l;
rune._len = l;
return rune;
}
function NEXTRUNE884(slice memory self) internal pure returns (slice memory ret) { //inject NONSTANDARD NAMING
NEXTRUNE884(self, ret);
}
function ORD412(slice memory self) internal pure returns (uint ret) { //inject NONSTANDARD NAMING
if (self._len == 0) {
return 0;
}
uint word;
uint length;
uint divisor = 2 ** 248;
// Load the rune into the MSBs of b
assembly { word:= mload(mload(add(self, 32))) }
uint b = word / divisor;
if (b < 0x80) {
ret = b;
length = 1;
} else if(b < 0xE0) {
ret = b & 0x1F;
length = 2;
} else if(b < 0xF0) {
ret = b & 0x0F;
length = 3;
} else {
ret = b & 0x07;
length = 4;
}
// Check for truncated codepoints
if (length > self._len) {
return 0;
}
for (uint i = 1; i < length; i++) {
divisor = divisor / 256;
b = (word / divisor) & 0xFF;
if (b & 0xC0 != 0x80) {
// Invalid UTF-8 sequence
return 0;
}
ret = (ret * 64) | (b & 0x3F);
}
return ret;
}
function KECCAK7(slice memory self) internal pure returns (bytes32 ret) { //inject NONSTANDARD NAMING
assembly {
ret := keccak256(mload(add(self, 32)), mload(self))
}
}
function STARTSWITH158(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return false;
}
if (self._ptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
function BEYOND684(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return self;
}
bool equal = true;
if (self._ptr != needle._ptr) {
assembly {
let length := mload(needle)
let selfptr := mload(add(self, 0x20))
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
self._ptr += needle._len;
}
return self;
}
function ENDSWITH884(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return false;
}
uint selfptr = self._ptr + self._len - needle._len;
if (selfptr == needle._ptr) {
return true;
}
bool equal;
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
return equal;
}
function UNTIL972(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
if (self._len < needle._len) {
return self;
}
uint selfptr = self._ptr + self._len - needle._len;
bool equal = true;
if (selfptr != needle._ptr) {
assembly {
let length := mload(needle)
let needleptr := mload(add(needle, 0x20))
equal := eq(keccak256(selfptr, length), keccak256(needleptr, length))
}
}
if (equal) {
self._len -= needle._len;
}
return self;
}
// Returns the memory address of the first byte of the first occurrence of
// `needle` in `self`, or the first byte after `self` if not found.
function FINDPTR600(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING
uint ptr = selfptr;
uint idx;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
uint end = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr >= end)
return selfptr + selflen;
ptr++;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
for (idx = 0; idx <= selflen - needlelen; idx++) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr;
ptr += 1;
}
}
}
return selfptr + selflen;
}
// Returns the memory address of the first byte after the last occurrence of
// `needle` in `self`, or the address of `self` if not found.
function RFINDPTR373(uint selflen, uint selfptr, uint needlelen, uint needleptr) private pure returns (uint) { //inject NONSTANDARD NAMING
uint ptr;
if (needlelen <= selflen) {
if (needlelen <= 32) {
bytes32 mask = bytes32(~(2 ** (8 * (32 - needlelen)) - 1));
bytes32 needledata;
assembly { needledata := and(mload(needleptr), mask) }
ptr = selfptr + selflen - needlelen;
bytes32 ptrdata;
assembly { ptrdata := and(mload(ptr), mask) }
while (ptrdata != needledata) {
if (ptr <= selfptr)
return selfptr;
ptr--;
assembly { ptrdata := and(mload(ptr), mask) }
}
return ptr + needlelen;
} else {
// For long needles, use hashing
bytes32 hash;
assembly { hash := keccak256(needleptr, needlelen) }
ptr = selfptr + (selflen - needlelen);
while (ptr >= selfptr) {
bytes32 testHash;
assembly { testHash := keccak256(ptr, needlelen) }
if (hash == testHash)
return ptr + needlelen;
ptr -= 1;
}
}
}
return selfptr;
}
function FIND686(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr);
self._len -= ptr - self._ptr;
self._ptr = ptr;
return self;
}
function RFIND966(slice memory self, slice memory needle) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr);
self._len = ptr - self._ptr;
return self;
}
function SPLIT752(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = self._ptr;
token._len = ptr - self._ptr;
if (ptr == self._ptr + self._len) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
self._ptr = ptr + needle._len;
}
return token;
}
function SPLIT752(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING
SPLIT752(self, needle, token);
}
function RSPLIT98(slice memory self, slice memory needle, slice memory token) internal pure returns (slice memory) { //inject NONSTANDARD NAMING
uint ptr = RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr);
token._ptr = ptr;
token._len = self._len - (ptr - self._ptr);
if (ptr == self._ptr) {
// Not found
self._len = 0;
} else {
self._len -= token._len + needle._len;
}
return token;
}
function RSPLIT98(slice memory self, slice memory needle) internal pure returns (slice memory token) { //inject NONSTANDARD NAMING
RSPLIT98(self, needle, token);
}
function COUNT317(slice memory self, slice memory needle) internal pure returns (uint cnt) { //inject NONSTANDARD NAMING
uint ptr = FINDPTR600(self._len, self._ptr, needle._len, needle._ptr) + needle._len;
while (ptr <= self._ptr + self._len) {
cnt++;
ptr = FINDPTR600(self._len - (ptr - self._ptr), ptr, needle._len, needle._ptr) + needle._len;
}
}
function CONTAINS145(slice memory self, slice memory needle) internal pure returns (bool) { //inject NONSTANDARD NAMING
return RFINDPTR373(self._len, self._ptr, needle._len, needle._ptr) != self._ptr;
}
function CONCAT154(slice memory self, slice memory other) internal pure returns (string memory) { //inject NONSTANDARD NAMING
string memory ret = new string(self._len + other._len);
uint retptr;
assembly { retptr := add(ret, 32) }
MEMCPY184(retptr, self._ptr, self._len);
MEMCPY184(retptr + self._len, other._ptr, other._len);
return ret;
}
function JOIN989(slice memory self, slice[] memory parts) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (parts.length == 0)
return "";
uint length = self._len * (parts.length - 1);
for(uint i = 0; i < parts.length; i++)
length += parts[i]._len;
string memory ret = new string(length);
uint retptr;
assembly { retptr := add(ret, 32) }
for(uint i = 0; i < parts.length; i++) {
MEMCPY184(retptr, parts[i]._ptr, parts[i]._len);
retptr += parts[i]._len;
if (i < parts.length - 1) {
MEMCPY184(retptr, self._ptr, self._len);
retptr += self._len;
}
}
return ret;
}
}
interface IERC165 {
function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool); //inject NONSTANDARD NAMING
}
contract IERC721 is IERC165 {
event TRANSFER150(address indexed from, address indexed to, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVAL578(address indexed owner, address indexed approved, uint256 indexed tokenId); //inject NONSTANDARD NAMING
event APPROVALFORALL29(address indexed owner, address indexed operator, bool approved); //inject NONSTANDARD NAMING
function BALANCEOF194(address owner) public view returns (uint256 balance); //inject NONSTANDARD NAMING
function OWNEROF501(uint256 tokenId) public view returns (address owner); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function TRANSFERFROM196(address from, address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function APPROVE594(address to, uint256 tokenId) public; //inject NONSTANDARD NAMING
function GETAPPROVED68(uint256 tokenId) public view returns (address operator); //inject NONSTANDARD NAMING
function SETAPPROVALFORALL944(address operator, bool _approved) public; //inject NONSTANDARD NAMING
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool); //inject NONSTANDARD NAMING
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory data) public; //inject NONSTANDARD NAMING
}
contract IERC721Metadata is IERC721 {
function NAME560() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL235() external view returns (string memory); //inject NONSTANDARD NAMING
function TOKENURI443(uint256 tokenId) external view returns (string memory); //inject NONSTANDARD NAMING
}
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 _MSGSENDER492() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA8() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract IERC721Enumerable is IERC721 {
function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256 tokenId); //inject NONSTANDARD NAMING
function TOKENBYINDEX294(uint256 index) public view returns (uint256); //inject NONSTANDARD NAMING
}
contract IERC721Receiver {
function ONERC721RECEIVED434(address operator, address from, uint256 tokenId, bytes memory data) //inject NONSTANDARD NAMING
public returns (bytes4);
}
library SafeMath {
function ADD556(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB290(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB290(a, b, "SafeMath: subtraction overflow");
}
function SUB290(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL948(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV752(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV752(a, b, "SafeMath: division by zero");
}
function DIV752(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD555(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD555(a, b, "SafeMath: modulo by zero");
}
function MOD555(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT48(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
function TOPAYABLE256(address account) internal pure returns (address payable) { //inject NONSTANDARD NAMING
return address(uint160(account));
}
}
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function CURRENT546(Counter storage counter) internal view returns (uint256) { //inject NONSTANDARD NAMING
return counter._value;
}
function INCREMENT933(Counter storage counter) internal { //inject NONSTANDARD NAMING
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function DECREMENT749(Counter storage counter) internal { //inject NONSTANDARD NAMING
counter._value = counter._value.SUB290(1);
}
}
contract ERC165 is IERC165 {
bytes4 private constant _interface_id_erc165217 = 0x01ffc9a7; //inject NONSTANDARD NAMING
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_REGISTERINTERFACE617(_interface_id_erc165217);
}
function SUPPORTSINTERFACE706(bytes4 interfaceId) external view returns (bool) { //inject NONSTANDARD NAMING
return _supportedInterfaces[interfaceId];
}
function _REGISTERINTERFACE617(bytes4 interfaceId) internal { //inject NONSTANDARD NAMING
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
contract ERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721781);
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT546();
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF501(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL578(owner, to, tokenId);
}
function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER492(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER492()][to] = approved;
emit APPROVALFORALL29(_MSGSENDER492(), to, approved);
}
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM267(from, to, tokenId);
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM763(from, to, tokenId, "");
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM629(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM267(from, to, tokenId);
require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF501(tokenId);
return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender));
}
function _SAFEMINT616(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
_SAFEMINT616(to, tokenId, "");
}
function _SAFEMINT616(address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_MINT975(to, tokenId);
require(_CHECKONERC721RECEIVED542(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS310(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT933();
emit TRANSFER150(address(0), to, tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[owner].DECREMENT749();
_tokenOwner[tokenId] = address(0);
emit TRANSFER150(owner, address(0), tokenId);
}
function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN381(OWNEROF501(tokenId), tokenId);
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[from].DECREMENT749();
_ownedTokensCount[to].INCREMENT933();
_tokenOwner[tokenId] = to;
emit TRANSFER150(from, to, tokenId);
}
function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT48()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data);
return (retval == _erc721_received995);
}
function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract ERC721Enumerable is Context, ERC165, ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_enumerable707);
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _allTokens.length;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._TRANSFERFROM267(from, to, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(from, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
}
function _MINT975(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._MINT975(to, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
_ADDTOKENTOALLTOKENSENUMERATION66(tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId);
}
function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING
return _ownedTokens[owner];
}
function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.SUB290(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING
// 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.SUB290(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract Ownable is Context {
address private _owner;
event OWNERSHIPTRANSFERRED55(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
constructor () internal {
address msgSender = _MSGSENDER492();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED55(address(0), msgSender);
}
function OWNER824() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER845() { //inject NONSTANDARD NAMING
require(ISOWNER804(), "Ownable: caller is not the owner");
_;
}
function ISOWNER804() public view returns (bool) { //inject NONSTANDARD NAMING
return _MSGSENDER492() == _owner;
}
function RENOUNCEOWNERSHIP585() public ONLYOWNER845 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED55(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP274(address newOwner) public ONLYOWNER845 { //inject NONSTANDARD NAMING
_TRANSFEROWNERSHIP356(newOwner);
}
function _TRANSFEROWNERSHIP356(address newOwner) internal { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED55(_owner, newOwner);
_owner = newOwner;
}
}
contract NoMintERC721 is Context, ERC165, IERC721 {
using SafeMath for uint256;
using Address for address;
using Counters for Counters.Counter;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _erc721_received995 = 0x150b7a02; //inject NONSTANDARD NAMING
// Mapping from token ID to owner
mapping (uint256 => address) private _tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => Counters.Counter) private _ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
bytes4 private constant _interface_id_erc721781 = 0x80ac58cd; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721781);
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return _ownedTokensCount[owner].CURRENT546();
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
function APPROVE594(address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
address owner = OWNEROF501(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_MSGSENDER492() == owner || ISAPPROVEDFORALL189(owner, _MSGSENDER492()),
"ERC721: approve caller is not owner nor approved for all"
);
_tokenApprovals[tokenId] = to;
emit APPROVAL578(owner, to, tokenId);
}
function GETAPPROVED68(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
function SETAPPROVALFORALL944(address to, bool approved) public { //inject NONSTANDARD NAMING
require(to != _MSGSENDER492(), "ERC721: approve to caller");
_operatorApprovals[_MSGSENDER492()][to] = approved;
emit APPROVALFORALL29(_MSGSENDER492(), to, approved);
}
function ISAPPROVEDFORALL189(address owner, address operator) public view returns (bool) { //inject NONSTANDARD NAMING
return _operatorApprovals[owner][operator];
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
//solhint-disable-next-line max-line-length
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_TRANSFERFROM267(from, to, tokenId);
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
SAFETRANSFERFROM763(from, to, tokenId, "");
}
function SAFETRANSFERFROM763(address from, address to, uint256 tokenId, bytes memory _data) public { //inject NONSTANDARD NAMING
require(_ISAPPROVEDOROWNER717(_MSGSENDER492(), tokenId), "ERC721: transfer caller is not owner nor approved");
_SAFETRANSFERFROM629(from, to, tokenId, _data);
}
function _SAFETRANSFERFROM629(address from, address to, uint256 tokenId, bytes memory _data) internal { //inject NONSTANDARD NAMING
_TRANSFERFROM267(from, to, tokenId);
require(_CHECKONERC721RECEIVED542(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
function _EXISTS310(uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
address owner = _tokenOwner[tokenId];
return owner != address(0);
}
function _ISAPPROVEDOROWNER717(address spender, uint256 tokenId) internal view returns (bool) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721: operator query for nonexistent token");
address owner = OWNEROF501(tokenId);
return (spender == owner || GETAPPROVED68(tokenId) == spender || ISAPPROVEDFORALL189(owner, spender));
}
function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(to != address(0), "ERC721: mint to the zero address");
require(!_EXISTS310(tokenId), "ERC721: token already minted");
_tokenOwner[tokenId] = to;
_ownedTokensCount[to].INCREMENT933();
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == owner, "ERC721: burn of token that is not own");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[owner].DECREMENT749();
_tokenOwner[tokenId] = address(0);
emit TRANSFER150(owner, address(0), tokenId);
}
function _BURN381(uint256 tokenId) internal { //inject NONSTANDARD NAMING
_BURN381(OWNEROF501(tokenId), tokenId);
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
require(OWNEROF501(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_CLEARAPPROVAL18(tokenId);
_ownedTokensCount[from].DECREMENT749();
_ownedTokensCount[to].INCREMENT933();
_tokenOwner[tokenId] = to;
emit TRANSFER150(from, to, tokenId);
}
function _CHECKONERC721RECEIVED542(address from, address to, uint256 tokenId, bytes memory _data) //inject NONSTANDARD NAMING
internal returns (bool)
{
if (!to.ISCONTRACT48()) {
return true;
}
bytes4 retval = IERC721Receiver(to).ONERC721RECEIVED434(_MSGSENDER492(), from, tokenId, _data);
return (retval == _erc721_received995);
}
function _CLEARAPPROVAL18(uint256 tokenId) private { //inject NONSTANDARD NAMING
if (_tokenApprovals[tokenId] != address(0)) {
_tokenApprovals[tokenId] = address(0);
}
}
}
contract NoMintERC721Enumerable is Context, ERC165, NoMintERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
bytes4 private constant _interface_id_erc721_enumerable707 = 0x780e9d63; //inject NONSTANDARD NAMING
constructor () public {
// register the supported interface to conform to ERC721Enumerable via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_enumerable707);
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < BALANCEOF194(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _allTokens.length;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
require(index < TOTALSUPPLY60(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
function _TRANSFERFROM267(address from, address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._TRANSFERFROM267(from, to, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(from, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
}
function _ADDTOKENTO735(address to, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._ADDTOKENTO735(to, tokenId);
_ADDTOKENTOOWNERENUMERATION485(to, tokenId);
_ADDTOKENTOALLTOKENSENUMERATION66(tokenId);
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
_REMOVETOKENFROMOWNERENUMERATION42(owner, tokenId);
// Since tokenId will be deleted, we can clear its slot in _ownedTokensIndex to trigger a gas refund
_ownedTokensIndex[tokenId] = 0;
_REMOVETOKENFROMALLTOKENSENUMERATION970(tokenId);
}
function _TOKENSOFOWNER469(address owner) internal view returns (uint256[] storage) { //inject NONSTANDARD NAMING
return _ownedTokens[owner];
}
function _ADDTOKENTOOWNERENUMERATION485(address to, uint256 tokenId) private { //inject NONSTANDARD NAMING
_ownedTokensIndex[tokenId] = _ownedTokens[to].length;
_ownedTokens[to].push(tokenId);
}
function _ADDTOKENTOALLTOKENSENUMERATION66(uint256 tokenId) private { //inject NONSTANDARD NAMING
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
function _REMOVETOKENFROMOWNERENUMERATION42(address from, uint256 tokenId) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _ownedTokens[from].length.SUB290(1);
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
_ownedTokens[from].length--;
// Note that _ownedTokensIndex[tokenId] hasn't been cleared: it still points to the old slot (now occupied by
// lastTokenId, or just over the end of the array if the token was the last one).
}
function _REMOVETOKENFROMALLTOKENSENUMERATION970(uint256 tokenId) private { //inject NONSTANDARD NAMING
// 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.SUB290(1);
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
_allTokens.length--;
_allTokensIndex[tokenId] = 0;
}
}
contract OveridableERC721Metadata is Context, ERC165, NoMintERC721, IERC721Metadata {
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
bytes4 private constant _interface_id_erc721_metadata259 = 0x5b5e139f; //inject NONSTANDARD NAMING
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_REGISTERINTERFACE617(_interface_id_erc721_metadata259);
}
function NAME560() external view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL235() external view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721Metadata: URI query for nonexistent token");
return _tokenURIs[tokenId];
}
function _SETTOKENURI639(uint256 tokenId, string memory uri) internal { //inject NONSTANDARD NAMING
require(_EXISTS310(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = uri;
}
function _BURN381(address owner, uint256 tokenId) internal { //inject NONSTANDARD NAMING
super._BURN381(owner, tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
contract GunToken is NoMintERC721, NoMintERC721Enumerable, OveridableERC721Metadata, Ownable {
using strings for *;
address internal factory;
uint16 public constant maxallocation33 = 4000; //inject NONSTANDARD NAMING
uint256 public lastAllocation = 0;
event BATCHTRANSFER76(address indexed from, address indexed to, uint256 indexed batchIndex); //inject NONSTANDARD NAMING
struct Batch {
address owner;
uint16 size;
uint8 category;
uint256 startId;
uint256 startTokenId;
}
Batch[] public allBatches;
mapping(address => uint256) unactivatedBalance;
mapping(uint256 => bool) isActivated;
mapping(uint256 => bool) public outOfBatch;
//Used for enumeration
mapping(address => Batch[]) public batchesOwned;
//Batch index to owner batch index
mapping(uint256 => uint256) public ownedBatchIndex;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
uint256 internal _totalSupply;
modifier ONLYFACTORY168 { //inject NONSTANDARD NAMING
require(msg.sender == factory, "Not authorized");
_;
}
constructor(address factoryAddress) public OveridableERC721Metadata("WarRiders Gun", "WRG") {
factory = factoryAddress;
}
function CATEGORYTYPETOID957(uint8 category, uint256 categoryId) public view returns (uint256) { //inject NONSTANDARD NAMING
for (uint i = 0; i < allBatches.length; i++) {
Batch memory a = allBatches[i];
if (a.category != category)
continue;
uint256 endId = a.startId + a.size;
if (categoryId >= a.startId && categoryId < endId) {
uint256 dif = categoryId - a.startId;
return a.startTokenId + dif;
}
}
revert();
}
function FALLBACKCOUNT353(address __owner) public view returns (uint256) { //inject NONSTANDARD NAMING
}
function FALLBACKINDEX7(address __owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
}
function MIGRATE859(uint256 count) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
//Empty for interface
}
function MIGRATESINGLE765() public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
//Empty for interface
}
function RECOVERBATCH2175(uint256 index, uint256 tokenStart, uint256 tokenEnd) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function MIGRATEBATCH628(uint256 index) public ONLYOWNER845 returns (uint256) { //inject NONSTANDARD NAMING
}
function RECOVERBATCH1434(uint256 index) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function TOKENOFOWNERBYINDEX536(address owner, uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
return TOKENOFOWNER723(owner)[index];
}
function GETBATCHCOUNT927(address owner) public view returns(uint256) { //inject NONSTANDARD NAMING
return batchesOwned[owner].length;
}
function UPDATEGUNFACTORY282(address _factory) public ONLYOWNER845 { //inject NONSTANDARD NAMING
}
function GETTOKENSINBATCH347(address owner, uint256 index) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
Batch memory a = batchesOwned[owner][index];
uint256[] memory result = new uint256[](a.size);
uint256 pos = 0;
uint end = a.startTokenId + a.size;
for (uint i = a.startTokenId; i < end; i++) {
if (isActivated[i] && super.OWNEROF501(i) != owner) {
continue;
}
result[pos] = i;
pos++;
}
require(pos > 0);
uint256 subAmount = a.size - pos;
assembly { mstore(result, sub(mload(result), subAmount)) }
return result;
}
function TOKENBYINDEX294(uint256 index) public view returns (uint256) { //inject NONSTANDARD NAMING
return ALLTOKENS936()[index];
}
function ALLTOKENS936() public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
uint256[] memory result = new uint256[](TOTALSUPPLY60());
uint pos = 0;
for (uint i = 0; i < allBatches.length; i++) {
Batch memory a = allBatches[i];
uint end = a.startTokenId + a.size;
for (uint j = a.startTokenId; j < end; j++) {
result[pos] = j;
pos++;
}
}
return result;
}
function TOKENOFOWNER723(address owner) public view returns (uint256[] memory) { //inject NONSTANDARD NAMING
uint256[] memory result = new uint256[](BALANCEOF194(owner));
uint pos = 0;
for (uint i = 0; i < batchesOwned[owner].length; i++) {
Batch memory a = batchesOwned[owner][i];
uint end = a.startTokenId + a.size;
for (uint j = a.startTokenId; j < end; j++) {
if (isActivated[j] && super.OWNEROF501(j) != owner) {
continue;
}
result[pos] = j;
pos++;
}
}
uint256[] memory fallbackOwned = _TOKENSOFOWNER469(owner);
for (uint i = 0; i < fallbackOwned.length; i++) {
result[pos] = fallbackOwned[i];
pos++;
}
return result;
}
function BALANCEOF194(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC721: balance query for the zero address");
return super.BALANCEOF194(owner) + unactivatedBalance[owner];
}
function OWNEROF501(uint256 tokenId) public view returns (address) { //inject NONSTANDARD NAMING
require(EXISTS127(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.OWNEROF501(tokenId);
}
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
return a.owner;
}
function EXISTS127(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
if (isActivated[_tokenId]) {
return super._EXISTS310(_tokenId);
} else {
uint256 index = GETBATCHINDEX786(_tokenId);
if (index < allBatches.length) {
Batch memory a = allBatches[index];
uint end = a.startTokenId + a.size;
return _tokenId < end;
}
return false;
}
}
function TOTALSUPPLY60() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function CLAIMALLOCATION316(address to, uint16 size, uint8 category) public ONLYFACTORY168 returns (uint) { //inject NONSTANDARD NAMING
require(size < maxallocation33, "Size must be smaller than maxAllocation");
allBatches.push(Batch({
owner: to,
size: size,
category: category,
startId: totalGunsMintedByCategory[category],
startTokenId: lastAllocation
}));
uint end = lastAllocation + size;
for (uint i = lastAllocation; i < end; i++) {
emit TRANSFER150(address(0), to, i);
}
lastAllocation += maxallocation33;
unactivatedBalance[to] += size;
totalGunsMintedByCategory[category] += size;
_ADDBATCHTOOWNER461(to, allBatches[allBatches.length - 1]);
_totalSupply += size;
return lastAllocation;
}
function TRANSFERFROM196(address from, address to, uint256 tokenId) public { //inject NONSTANDARD NAMING
if (!isActivated[tokenId]) {
ACTIVATE8(tokenId);
}
super.TRANSFERFROM196(from, to, tokenId);
}
function ACTIVATE8(uint256 tokenId) public { //inject NONSTANDARD NAMING
require(!isActivated[tokenId], "Token already activated");
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
require(tokenId < a.startTokenId + a.size);
isActivated[tokenId] = true;
ADDTOKENTO758(a.owner, tokenId);
unactivatedBalance[a.owner]--;
}
function GETBATCHINDEX786(uint256 tokenId) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 index = (tokenId / maxallocation33);
return index;
}
function CATEGORYFORTOKEN792(uint256 tokenId) public view returns (uint8) { //inject NONSTANDARD NAMING
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
return a.category;
}
function CATEGORYIDFORTOKEN949(uint256 tokenId) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 index = GETBATCHINDEX786(tokenId);
require(index < allBatches.length, "Token batch doesn't exist");
Batch memory a = allBatches[index];
uint256 categoryId = (tokenId % maxallocation33) + a.startId;
return categoryId;
}
function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (v == 0) {
return "0";
}
uint j = v;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function TOKENURI443(uint256 tokenId) public view returns (string memory) { //inject NONSTANDARD NAMING
require(EXISTS127(tokenId), "Token doesn't exist!");
if (isActivated[tokenId]) {
return super.TOKENURI443(tokenId);
} else {
//Predict the token URI
uint8 category = CATEGORYFORTOKEN792(tokenId);
uint256 _categoryId = CATEGORYIDFORTOKEN949(tokenId);
string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667());
return _metadata;
}
}
function ADDTOKENTO758(address _to, uint256 _tokenId) internal { //inject NONSTANDARD NAMING
//Predict the token URI
uint8 category = CATEGORYFORTOKEN792(_tokenId);
uint256 _categoryId = CATEGORYIDFORTOKEN949(_tokenId);
string memory id = UINTTOSTRING328(category).TOSLICE667().CONCAT154("/".TOSLICE667()).TOSLICE667().CONCAT154(UINTTOSTRING328(_categoryId).TOSLICE667().CONCAT154(".json".TOSLICE667()).TOSLICE667());
string memory _base = "https://vault.warriders.com/guns/";
//Final URL: https://vault.warriders.com/guns/<category>/<category_id>.json
string memory _metadata = _base.TOSLICE667().CONCAT154(id.TOSLICE667());
super._ADDTOKENTO735(_to, _tokenId);
super._SETTOKENURI639(_tokenId, _metadata);
}
function CEIL247(uint a, uint m) internal pure returns (uint ) { //inject NONSTANDARD NAMING
return ((a + m - 1) / m) * m;
}
function _REMOVEBATCHFROMOWNER136(address from, Batch memory batch) private { //inject NONSTANDARD NAMING
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId);
uint256 lastBatchIndex = batchesOwned[from].length.SUB290(1);
uint256 batchIndex = ownedBatchIndex[globalIndex];
// When the token to delete is the last token, the swap operation is unnecessary
if (batchIndex != lastBatchIndex) {
Batch memory lastBatch = batchesOwned[from][lastBatchIndex];
uint256 lastGlobalIndex = GETBATCHINDEX786(lastBatch.startTokenId);
batchesOwned[from][batchIndex] = lastBatch; // Move the last batch to the slot of the to-delete batch
ownedBatchIndex[lastGlobalIndex] = batchIndex; // Update the moved batch's index
}
// This also deletes the contents at the last position of the array
batchesOwned[from].length--;
// Note that ownedBatchIndex[batch] hasn't been cleared: it still points to the old slot (now occupied by
// lastBatch, or just over the end of the array if the batch was the last one).
}
function _ADDBATCHTOOWNER461(address to, Batch memory batch) private { //inject NONSTANDARD NAMING
uint256 globalIndex = GETBATCHINDEX786(batch.startTokenId);
ownedBatchIndex[globalIndex] = batchesOwned[to].length;
batchesOwned[to].push(batch);
}
function BATCHTRANSFER268(uint256 batchIndex, address to) public { //inject NONSTANDARD NAMING
Batch storage a = allBatches[batchIndex];
address previousOwner = a.owner;
require(a.owner == msg.sender);
_REMOVEBATCHFROMOWNER136(previousOwner, a);
a.owner = to;
_ADDBATCHTOOWNER461(to, a);
emit BATCHTRANSFER76(previousOwner, to, batchIndex);
//Now to need to emit a bunch of transfer events
uint end = a.startTokenId + a.size;
uint256 unActivated = 0;
for (uint i = a.startTokenId; i < end; i++) {
if (isActivated[i]) {
if (OWNEROF501(i) != previousOwner)
continue; //The previous owner didn't own this token, don't emit an event
} else {
unActivated++;
}
emit TRANSFER150(previousOwner, to, i);
}
unactivatedBalance[to] += unActivated;
unactivatedBalance[previousOwner] -= unActivated;
}
}
contract ApproveAndCallFallBack {
function RECEIVEAPPROVAL438(address from, uint256 tokens, address token, bytes memory data) public payable returns (bool); //inject NONSTANDARD NAMING
}
contract ERC20Basic {
function TOTALSUPPLY60() public view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF194(address who) public view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER702(address to, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event TRANSFER150(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
}
contract ERC20 is ERC20Basic {
function ALLOWANCE798(address owner, address spender) //inject NONSTANDARD NAMING
public view returns (uint256);
function TRANSFERFROM196(address from, address to, uint256 value) //inject NONSTANDARD NAMING
public returns (bool);
function APPROVE594(address spender, uint256 value) public returns (bool); //inject NONSTANDARD NAMING
event APPROVAL578( //inject NONSTANDARD NAMING
address indexed owner,
address indexed spender,
uint256 value
);
}
contract BurnableToken is ERC20 {
event BURN595(address indexed burner, uint256 value); //inject NONSTANDARD NAMING
function BURN840(uint256 _value) public; //inject NONSTANDARD NAMING
}
contract StandardBurnableToken is BurnableToken {
function BURNFROM813(address _from, uint256 _value) public; //inject NONSTANDARD NAMING
}
interface BZNFeed {
function CONVERT77(uint256 usd) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract SimpleBZNFeed is BZNFeed, Ownable {
uint256 private conversion;
function UPDATECONVERSION150(uint256 conversionRate) public ONLYOWNER845 { //inject NONSTANDARD NAMING
conversion = conversionRate;
}
function CONVERT77(uint256 usd) external view returns (uint256) { //inject NONSTANDARD NAMING
return usd * conversion;
}
}
interface IDSValue {
function PEEK123() external view returns (bytes32, bool); //inject NONSTANDARD NAMING
function READ988() external view returns (bytes32); //inject NONSTANDARD NAMING
function POKE435(bytes32 wut) external; //inject NONSTANDARD NAMING
function VOID212() external; //inject NONSTANDARD NAMING
}
library BytesLib {
function CONCAT154( //inject NONSTANDARD NAMING
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function CONCATSTORAGE572(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING
assembly {
// Read the first 32 bytes of _preBytes storage, which is the length
// of the array. (We don't need to use the offset into the slot
// because arrays use the entire slot.)
let fslot := sload(_preBytes_slot)
// Arrays of 31 bytes or less have an even value in their slot,
// while longer arrays have an odd value. The actual length is
// the slot divided by two for odd values, and the lowest order
// byte divided by two for even values.
// If the slot is even, bitwise and the slot with 255 and divide by
// two to get the length. If the slot is odd, bitwise and the slot
// with -1 and divide by two.
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
// Since the new array still fits in the slot, we just need to
// update the contents of the slot.
// uint256(bytes_storage) = uint256(bytes_storage) + uint256(bytes_memory) + new_length
sstore(
_preBytes_slot,
// all the modifications to the slot are inside this
// next block
add(
// we can just add to the slot contents because the
// bytes we want to change are the LSBs
fslot,
add(
mul(
div(
// load the bytes from memory
mload(add(_postBytes, 0x20)),
// zero all bytes to the right
exp(0x100, sub(32, mlength))
),
// and now shift left the number of bytes to
// leave space for the length in the slot
exp(0x100, sub(32, newlength))
),
// increase length by the double of the memory
// bytes length
mul(mlength, 2)
)
)
)
}
case 1 {
// The stored value fits in the slot, but the combined value
// will exceed it.
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// The contents of the _postBytes array start 32 bytes into
// the structure. Our first read should obtain the `submod`
// bytes that can fit into the unused space in the last word
// of the stored array. To get this, we read 32 bytes starting
// from `submod`, so the data we read overlaps with the array
// contents by `submod` bytes. Masking the lowest-order
// `submod` bytes allows us to add that value directly to the
// stored value.
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
// Start copying to the last used word of the stored array.
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
// save new length
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
// Copy over the first `submod` bytes of the new data as in
// case 1 above.
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function SLICE625( //inject NONSTANDARD NAMING
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function TOADDRESS210(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function TOUINT8119(bytes memory _bytes, uint _start) internal pure returns (uint8) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function TOUINT16152(bytes memory _bytes, uint _start) internal pure returns (uint16) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function TOUINT32393(bytes memory _bytes, uint _start) internal pure returns (uint32) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function TOUINT64646(bytes memory _bytes, uint _start) internal pure returns (uint64) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function TOUINT96427(bytes memory _bytes, uint _start) internal pure returns (uint96) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function TOUINT12878(bytes memory _bytes, uint _start) internal pure returns (uint128) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function TOUINT505(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function TOBYTES32154(bytes memory _bytes, uint _start) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function EQUAL770(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let length := mload(_preBytes)
// if lengths don't match the arrays are not equal
switch eq(length, mload(_postBytes))
case 1 {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// if any of these checks fails then arrays are not equal
if iszero(eq(mload(mc), mload(cc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
function EQUALSTORAGE902( //inject NONSTANDARD NAMING
bytes storage _preBytes,
bytes memory _postBytes
)
internal
view
returns (bool)
{
bool success = true;
assembly {
// we know _preBytes_offset is 0
let fslot := sload(_preBytes_slot)
// Decode the length of the stored array like in concatStorage().
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
// if lengths don't match the arrays are not equal
switch eq(slength, mlength)
case 1 {
// slength can contain both the length and contents of the array
// if length < 32 bytes so let's prepare for that
// v. http://solidity.readthedocs.io/en/latest/miscellaneous.html#layout-of-state-variables-in-storage
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
// blank the last byte which is the length
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
// unsuccess:
success := 0
}
}
default {
// cb is a circuit breaker in the for loop since there's
// no said feature for inline assembly loops
// cb = 1 - don't breaker
// cb = 0 - break
let cb := 1
// get the keccak hash to get the contents of the array
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
// the next line is the loop condition:
// while(uint(mc < end) + cb == 2)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
// unsuccess:
success := 0
cb := 0
}
}
}
}
}
default {
// unsuccess:
success := 0
}
}
return success;
}
}
contract GunPreOrder is Ownable, ApproveAndCallFallBack {
using BytesLib for bytes;
using SafeMath for uint256;
//Event for when a bulk buy order has been placed
event CONSUMERBULKBUY355(uint8 category, uint256 quanity, address reserver); //inject NONSTANDARD NAMING
//Event for when a gun has been bought
event GUNSBOUGHT917(uint256 gunId, address owner, uint8 category); //inject NONSTANDARD NAMING
//Event for when ether is taken out of this contract
event WITHDRAWAL910(uint256 amount); //inject NONSTANDARD NAMING
//Default referal commision percent
uint256 public constant commission_percent82 = 5; //inject NONSTANDARD NAMING
//Whether category is open
mapping(uint8 => bool) public categoryExists;
mapping(uint8 => bool) public categoryOpen;
mapping(uint8 => bool) public categoryKilled;
//The additional referal commision percent for any given referal address (default is 0)
mapping(address => uint256) internal commissionRate;
//How many guns in a given category an address has reserved
mapping(uint8 => mapping(address => uint256)) public categoryReserveAmount;
//Opensea buy address
address internal constant opensea308 = 0x5b3256965e7C3cF26E11FCAf296DfC8807C01073; //inject NONSTANDARD NAMING
//The percent increase and percent base for a given category
mapping(uint8 => uint256) public categoryPercentIncrease;
mapping(uint8 => uint256) public categoryPercentBase;
//Price of a givevn category in USD WEI
mapping(uint8 => uint256) public categoryPrice;
//The percent of ether required for buying in BZN
mapping(uint8 => uint256) public requiredEtherPercent;
mapping(uint8 => uint256) public requiredEtherPercentBase;
bool public allowCreateCategory = true;
//The gun token contract
GunToken public token;
//The gun factory contract
GunFactory internal factory;
//The BZN contract
StandardBurnableToken internal bzn;
//The Maker ETH/USD price feed
IDSValue public ethFeed;
BZNFeed public bznFeed;
//The gamepool address
address internal gamePool;
//Require the skinned/regular shop to be opened
modifier ENSURESHOPOPEN328(uint8 category) { //inject NONSTANDARD NAMING
require(categoryExists[category], "Category doesn't exist!");
require(categoryOpen[category], "Category is not open!");
_;
}
//Allow a function to accept ETH payment
modifier PAYINETH352(address referal, uint8 category, address new_owner, uint16 quanity) { //inject NONSTANDARD NAMING
uint256 usdPrice;
uint256 totalPrice;
(usdPrice, totalPrice) = PRICEFOR73(category, quanity);
require(usdPrice > 0, "Price not yet set");
categoryPrice[category] = usdPrice; //Save last price
uint256 price = CONVERT77(totalPrice, false);
require(msg.value >= price, "Not enough Ether sent!");
_;
if (msg.value > price) {
uint256 change = msg.value - price;
msg.sender.transfer(change);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
uint256 totalCommision = commission_percent82 + commissionRate[referal];
uint256 commision = (price * totalCommision) / 100;
address payable _referal = address(uint160(referal));
_referal.transfer(commision);
}
}
//Allow function to accept BZN payment
modifier PAYINBZN388(address referal, uint8 category, address payable new_owner, uint16 quanity) { //inject NONSTANDARD NAMING
uint256[] memory prices = new uint256[](4); //Hack to work around local var limit (usdPrice, bznPrice, commision, totalPrice)
(prices[0], prices[3]) = PRICEFOR73(category, quanity);
require(prices[0] > 0, "Price not yet set");
categoryPrice[category] = prices[0];
prices[1] = CONVERT77(prices[3], true); //Convert the totalPrice to BZN
//The commissionRate map adds any partner bonuses, or 0 if a normal user referral
if (referal != address(0)) {
prices[2] = (prices[1] * (commission_percent82 + commissionRate[referal])) / 100;
}
uint256 requiredEther = (CONVERT77(prices[3], false) * requiredEtherPercent[category]) / requiredEtherPercentBase[category];
require(msg.value >= requiredEther, "Buying with BZN requires some Ether!");
bzn.BURNFROM813(new_owner, (((prices[1] - prices[2]) * 30) / 100));
bzn.TRANSFERFROM196(new_owner, gamePool, prices[1] - prices[2] - (((prices[1] - prices[2]) * 30) / 100));
_;
if (msg.value > requiredEther) {
new_owner.transfer(msg.value - requiredEther);
}
if (referal != address(0)) {
require(referal != msg.sender, "The referal cannot be the sender");
require(referal != tx.origin, "The referal cannot be the tranaction origin");
require(referal != new_owner, "The referal cannot be the new owner");
bzn.TRANSFERFROM196(new_owner, referal, prices[2]);
prices[2] = (requiredEther * (commission_percent82 + commissionRate[referal])) / 100;
address payable _referal = address(uint160(referal));
_referal.transfer(prices[2]);
}
}
//Constructor
constructor(
address tokenAddress,
address tokenFactory,
address gp,
address isd,
address bzn_address
) public {
token = GunToken(tokenAddress);
factory = GunFactory(tokenFactory);
ethFeed = IDSValue(isd);
bzn = StandardBurnableToken(bzn_address);
gamePool = gp;
//Set percent increases
categoryPercentIncrease[1] = 100035;
categoryPercentBase[1] = 100000;
categoryPercentIncrease[2] = 100025;
categoryPercentBase[2] = 100000;
categoryPercentIncrease[3] = 100015;
categoryPercentBase[3] = 100000;
commissionRate[opensea308] = 10;
}
function CREATECATEGORY817(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(allowCreateCategory);
categoryExists[category] = true;
}
function DISABLECREATECATEGORIES112() public ONLYOWNER845 { //inject NONSTANDARD NAMING
allowCreateCategory = false;
}
//Set the referal commision rate for an address
function SETCOMMISSION914(address referral, uint256 percent) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(percent > commission_percent82);
require(percent < 95);
percent = percent - commission_percent82;
commissionRate[referral] = percent;
}
//Set the price increase/base for skinned or regular guns
function SETPERCENTINCREASE775(uint256 increase, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(increase > base);
categoryPercentIncrease[category] = increase;
categoryPercentBase[category] = base;
}
function SETETHERPERCENT411(uint256 percent, uint256 base, uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
requiredEtherPercent[category] = percent;
requiredEtherPercentBase[category] = base;
}
function KILLCATEGORY428(uint8 category) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(!categoryKilled[category]);
categoryOpen[category] = false;
categoryKilled[category] = true;
}
//Open/Close the skinned or regular guns shop
function SETSHOPSTATE191(uint8 category, bool open) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(category == 1 || category == 2 || category == 3);
require(!categoryKilled[category]);
require(categoryExists[category]);
categoryOpen[category] = open;
}
function SETPRICE360(uint8 category, uint256 price, bool inWei) public ONLYOWNER845 { //inject NONSTANDARD NAMING
uint256 multiply = 1e18;
if (inWei) {
multiply = 1;
}
categoryPrice[category] = price * multiply;
}
function WITHDRAW154(uint256 amount) public ONLYOWNER845 { //inject NONSTANDARD NAMING
uint256 balance = address(this).balance;
require(amount <= balance, "Requested to much");
address payable _owner = address(uint160(OWNER824()));
_owner.transfer(amount);
emit WITHDRAWAL910(amount);
}
function SETBZNFEEDCONTRACT654(address new_bzn_feed) public ONLYOWNER845 { //inject NONSTANDARD NAMING
bznFeed = BZNFeed(new_bzn_feed);
}
//Buy many skinned or regular guns with BZN. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function BUYWITHBZN846(address referal, uint8 category, address payable new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINBZN388(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING
factory.MINTFOR528(new_owner, quanity, category);
return true;
}
//Buy many skinned or regular guns with ETH. This will reserve the amount of guns and allows the new_owner to invoke claimGuns for free
function BUYWITHETHER108(address referal, uint8 category, address new_owner, uint16 quanity) ENSURESHOPOPEN328(category) PAYINETH352(referal, category, new_owner, quanity) public payable returns (bool) { //inject NONSTANDARD NAMING
factory.MINTFOR528(new_owner, quanity, category);
return true;
}
function CONVERT77(uint256 usdValue, bool isBZN) public view returns (uint256) { //inject NONSTANDARD NAMING
if (isBZN) {
return bznFeed.CONVERT77(usdValue);
} else {
bool temp;
bytes32 aaa;
(aaa, temp) = ethFeed.PEEK123();
uint256 priceForEtherInUsdWei = uint256(aaa);
return usdValue / (priceForEtherInUsdWei / 1e18);
}
}
function PRICEFOR73(uint8 category, uint16 quanity) public view returns (uint256, uint256) { //inject NONSTANDARD NAMING
require(quanity > 0);
uint256 percent = categoryPercentIncrease[category];
uint256 base = categoryPercentBase[category];
uint256 currentPrice = categoryPrice[category];
uint256 nextPrice = currentPrice;
uint256 totalPrice = 0;
//We can't use exponents because we'll overflow quickly
//Only for loop :(
for (uint i = 0; i < quanity; i++) {
nextPrice = (currentPrice * percent) / base;
currentPrice = nextPrice;
totalPrice += nextPrice;
}
//Return the next price, as this is the true price
return (nextPrice, totalPrice);
}
//Determine if a tokenId exists (has been sold)
function SOLD957(uint256 _tokenId) public view returns (bool) { //inject NONSTANDARD NAMING
return token.EXISTS127(_tokenId);
}
function RECEIVEAPPROVAL438(address from, uint256 tokenAmount, address tokenContract, bytes memory data) public payable returns (bool) { //inject NONSTANDARD NAMING
address referal;
uint8 category;
uint16 quanity;
(referal, category, quanity) = abi.decode(data, (address, uint8, uint16));
require(quanity >= 1);
address payable _from = address(uint160(from));
BUYWITHBZN846(referal, category, _from, quanity);
return true;
}
}
contract GunFactory is Ownable {
using strings for *;
uint8 public constant premium_category760 = 1; //inject NONSTANDARD NAMING
uint8 public constant midgrade_category818 = 2; //inject NONSTANDARD NAMING
uint8 public constant regular_category63 = 3; //inject NONSTANDARD NAMING
uint256 public constant one_month568 = 2628000; //inject NONSTANDARD NAMING
uint256 public mintedGuns = 0;
address preOrderAddress;
GunToken token;
mapping(uint8 => uint256) internal gunsMintedByCategory;
mapping(uint8 => uint256) internal totalGunsMintedByCategory;
mapping(uint8 => uint256) internal firstMonthLimit;
mapping(uint8 => uint256) internal secondMonthLimit;
mapping(uint8 => uint256) internal thirdMonthLimit;
uint256 internal startTime;
mapping(uint8 => uint256) internal currentMonthEnd;
uint256 internal monthOneEnd;
uint256 internal monthTwoEnd;
modifier ONLYPREORDER406 { //inject NONSTANDARD NAMING
require(msg.sender == preOrderAddress, "Not authorized");
_;
}
modifier ISINITIALIZED13 { //inject NONSTANDARD NAMING
require(preOrderAddress != address(0), "No linked preorder");
require(address(token) != address(0), "No linked token");
_;
}
constructor() public {
firstMonthLimit[premium_category760] = 5000;
firstMonthLimit[midgrade_category818] = 20000;
firstMonthLimit[regular_category63] = 30000;
secondMonthLimit[premium_category760] = 2500;
secondMonthLimit[midgrade_category818] = 10000;
secondMonthLimit[regular_category63] = 15000;
thirdMonthLimit[premium_category760] = 600;
thirdMonthLimit[midgrade_category818] = 3000;
thirdMonthLimit[regular_category63] = 6000;
startTime = block.timestamp;
monthOneEnd = startTime + one_month568;
monthTwoEnd = startTime + one_month568 + one_month568;
currentMonthEnd[premium_category760] = monthOneEnd;
currentMonthEnd[midgrade_category818] = monthOneEnd;
currentMonthEnd[regular_category63] = monthOneEnd;
}
function UINTTOSTRING328(uint v) internal pure returns (string memory) { //inject NONSTANDARD NAMING
if (v == 0) {
return "0";
}
uint j = v;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (v != 0) {
bstr[k--] = byte(uint8(48 + v % 10));
v /= 10;
}
return string(bstr);
}
function MINTFOR528(address newOwner, uint16 size, uint8 category) public ONLYPREORDER406 ISINITIALIZED13 returns (uint256) { //inject NONSTANDARD NAMING
GunPreOrder preOrder = GunPreOrder(preOrderAddress);
require(preOrder.categoryExists(category), "Invalid category");
require(!HASREACHEDLIMIT199(category), "The monthly limit has been reached");
token.CLAIMALLOCATION316(newOwner, size, category);
mintedGuns++;
gunsMintedByCategory[category] = gunsMintedByCategory[category] + 1;
totalGunsMintedByCategory[category] = totalGunsMintedByCategory[category] + 1;
}
function HASREACHEDLIMIT199(uint8 category) internal returns (bool) { //inject NONSTANDARD NAMING
uint256 currentTime = block.timestamp;
uint256 limit = CURRENTLIMIT394(category);
uint256 monthEnd = currentMonthEnd[category];
//If the current block time is greater than or equal to the end of the month
if (currentTime >= monthEnd) {
//It's a new month, reset all limits
//gunsMintedByCategory[PREMIUM_CATEGORY] = 0;
//gunsMintedByCategory[MIDGRADE_CATEGORY] = 0;
//gunsMintedByCategory[REGULAR_CATEGORY] = 0;
gunsMintedByCategory[category] = 0;
//Set next month end to be equal one month in advance
//do this while the current time is greater than the next month end
while (currentTime >= monthEnd) {
monthEnd = monthEnd + one_month568;
}
//Finally, update the limit
limit = CURRENTLIMIT394(category);
currentMonthEnd[category] = monthEnd;
}
//Check if the limit has been reached
return gunsMintedByCategory[category] >= limit;
}
function REACHEDLIMIT389(uint8 category) public view returns (bool) { //inject NONSTANDARD NAMING
uint256 limit = CURRENTLIMIT394(category);
return gunsMintedByCategory[category] >= limit;
}
function CURRENTLIMIT394(uint8 category) public view returns (uint256) { //inject NONSTANDARD NAMING
uint256 currentTime = block.timestamp;
uint256 limit;
if (currentTime < monthOneEnd) {
limit = firstMonthLimit[category];
} else if (currentTime < monthTwoEnd) {
limit = secondMonthLimit[category];
} else {
limit = thirdMonthLimit[category];
}
return limit;
}
function SETCATEGORYLIMIT220(uint8 category, uint256 firstLimit, uint256 secondLimit, uint256 thirdLimit) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(firstMonthLimit[category] == 0);
require(secondMonthLimit[category] == 0);
require(thirdMonthLimit[category] == 0);
firstMonthLimit[category] = firstLimit;
secondMonthLimit[category] = secondLimit;
thirdMonthLimit[category] = thirdLimit;
}
function ATTACHPREORDER925(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(preOrderAddress == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunPreOrder preOrder = GunPreOrder(dst);
preOrderAddress = address(preOrder);
}
function ATTACHTOKEN953(address dst) public ONLYOWNER845 { //inject NONSTANDARD NAMING
require(address(token) == address(0));
require(dst != address(0));
//Enforce that address is indeed a preorder
GunToken ct = GunToken(dst);
token = ct;
}
} | inject NONSTANDARD NAMING
| uint8 public constant premium_category760 = 1; | 6,432,033 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
28,
1071,
5381,
23020,
5077,
67,
4743,
27,
4848,
273,
404,
31,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/*
Copyright 2020 Crosspoly ZOO.
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity 0.6.9;
pragma experimental ABIEncoderV2;
import {ReentrancyGuard} from "../../lib/ReentrancyGuard.sol";
import {SafeMath} from "../../lib/SafeMath.sol";
import {CrosspolyMath} from "../../lib/CrosspolyMath.sol";
import {DecimalMath} from "../../lib/DecimalMath.sol";
import {IFeeRateModel} from "../../lib/FeeRateModel.sol";
import {IERC20} from "../../intf/IERC20.sol";
import {PMMPricing} from "../../lib/PMMPricing.sol";
contract DVMStorage is ReentrancyGuard {
using SafeMath for uint256;
bool public _IS_OPEN_TWAP_ = false;
bool internal _DVM_INITIALIZED_;
// ============ Core Address ============
address public _MAINTAINER_;
IERC20 public _BASE_TOKEN_;
IERC20 public _QUOTE_TOKEN_;
uint112 public _BASE_RESERVE_;
uint112 public _QUOTE_RESERVE_;
uint32 public _BLOCK_TIMESTAMP_LAST_;
uint256 public _BASE_PRICE_CUMULATIVE_LAST_;
// ============ Shares (ERC20) ============
string public symbol;
uint8 public decimals;
string public name;
uint256 public totalSupply;
mapping(address => uint256) internal _SHARES_;
mapping(address => mapping(address => uint256)) internal _ALLOWED_;
// ================= Permit ======================
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint256) public nonces;
// ============ Variables for Pricing ============
uint256 public _LP_FEE_RATE_;
IFeeRateModel public _MT_FEE_RATE_MODEL_;
uint256 public _K_;
uint256 public _I_;
// ============ Helper Functions ============
function getPMMState() public view returns (PMMPricing.PMMState memory state) {
state.i = _I_;
state.K = _K_;
state.B = _BASE_RESERVE_;
state.Q = _QUOTE_RESERVE_;
state.B0 = 0; // will be calculated in adjustedTarget
state.Q0 = 0;
state.R = PMMPricing.RState.ABOVE_ONE;
PMMPricing.adjustedTarget(state);
}
function getPMMStateForCall()
external
view
returns (
uint256 i,
uint256 K,
uint256 B,
uint256 Q,
uint256 B0,
uint256 Q0,
uint256 R
)
{
PMMPricing.PMMState memory state = getPMMState();
i = state.i;
K = state.K;
B = state.B;
Q = state.Q;
B0 = state.B0;
Q0 = state.Q0;
R = uint256(state.R);
}
function getMidPrice() public view returns (uint256 midPrice) {
return PMMPricing.getMidPrice(getPMMState());
}
}
| will be calculated in adjustedTarget
| state.B0 = 0; | 1,038,818 | [
1,
20194,
506,
8894,
316,
13940,
2326,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
919,
18,
38,
20,
273,
374,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param 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);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// 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;
/**
* @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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | @notice Executes a non-liquidity token trade @param account the initiator of the trade @param cashGroup parameters for the trade @param market market memory location to use @param trade bytes32 encoding of the particular trade @param blockTime the current block time @return maturity of the asset that was traded @return cashAmount - a positive or negative cash amount accrued to the account @return fCashAmount - a positive or negative fCash amount accrued to the account This is a little ugly but required to deal with stack issues. We know the market is loaded with the proper maturity inside _executeLendBorrowTrade | function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
revert("Invalid trade type");
}
}
| 11,949 | [
1,
9763,
279,
1661,
17,
549,
372,
24237,
1147,
18542,
225,
2236,
326,
26030,
434,
326,
18542,
225,
276,
961,
1114,
1472,
364,
326,
18542,
225,
13667,
13667,
3778,
2117,
358,
999,
225,
18542,
1731,
1578,
2688,
434,
326,
6826,
18542,
225,
1203,
950,
326,
783,
1203,
813,
327,
29663,
434,
326,
3310,
716,
1703,
1284,
785,
327,
276,
961,
6275,
300,
279,
6895,
578,
6092,
276,
961,
3844,
4078,
86,
5957,
358,
326,
2236,
327,
284,
39,
961,
6275,
300,
279,
6895,
578,
6092,
284,
39,
961,
3844,
4078,
86,
5957,
358,
326,
2236,
1220,
353,
279,
12720,
26920,
1496,
1931,
358,
10490,
598,
2110,
8296,
18,
1660,
5055,
326,
13667,
353,
4203,
598,
326,
5338,
29663,
4832,
389,
8837,
48,
409,
38,
15318,
22583,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
8837,
22583,
12,
203,
3639,
1758,
2236,
16,
203,
3639,
385,
961,
1114,
2402,
3778,
276,
961,
1114,
16,
203,
3639,
6622,
278,
2402,
3778,
13667,
16,
203,
3639,
1731,
1578,
18542,
16,
203,
3639,
2254,
5034,
1203,
950,
203,
565,
262,
203,
3639,
3238,
203,
3639,
1135,
261,
203,
5411,
2254,
5034,
29663,
16,
203,
5411,
509,
5034,
276,
961,
6275,
16,
203,
5411,
509,
5034,
284,
39,
961,
6275,
203,
3639,
262,
203,
565,
288,
203,
3639,
2197,
323,
26995,
18542,
559,
273,
2197,
323,
26995,
12,
11890,
5034,
12,
11890,
28,
12,
3890,
21,
12,
20077,
3719,
10019,
203,
3639,
309,
261,
20077,
559,
422,
2197,
323,
26995,
18,
23164,
50,
1345,
607,
5557,
13,
288,
203,
5411,
261,
7373,
2336,
16,
276,
961,
6275,
16,
284,
39,
961,
6275,
13,
273,
389,
12688,
12104,
50,
1345,
607,
5557,
12,
203,
7734,
2236,
16,
203,
7734,
276,
961,
1114,
16,
203,
7734,
1203,
950,
16,
203,
7734,
18542,
203,
5411,
11272,
203,
5411,
261,
7373,
2336,
16,
276,
961,
6275,
16,
284,
39,
961,
6275,
13,
273,
389,
542,
5929,
39,
961,
758,
23602,
12,
4631,
16,
276,
961,
1114,
16,
1203,
950,
16,
18542,
1769,
203,
5411,
261,
71,
961,
6275,
16,
284,
39,
961,
6275,
13,
273,
389,
8837,
48,
409,
38,
15318,
22583,
12,
203,
7734,
276,
961,
1114,
16,
203,
7734,
13667,
16,
203,
7734,
18542,
559,
16,
203,
7734,
1203,
950,
16,
203,
7734,
18542,
203,
5411,
11272,
203,
203,
5411,
29663,
273,
2
] |
./partial_match/1/0xC0205e203F423Bcd8B2a4d6f8C8A154b0Aa60F19/sources/ConverterRegistry.sol | * @dev checks whether or not a given value is a liquidity pool @param _value value @return true if the given value is a liquidity pool, false if not/ | function isLiquidityPool(address _value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isLiquidityPool(_value);
}
| 3,607,123 | [
1,
12366,
2856,
578,
486,
279,
864,
460,
353,
279,
4501,
372,
24237,
2845,
225,
389,
1132,
460,
327,
638,
309,
326,
864,
460,
353,
279,
4501,
372,
24237,
2845,
16,
629,
309,
486,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
28601,
18988,
24237,
2864,
12,
2867,
389,
1132,
13,
1071,
1476,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
327,
467,
5072,
4243,
751,
12,
2867,
951,
12,
2248,
2204,
2560,
67,
5937,
25042,
67,
4883,
13,
2934,
291,
48,
18988,
24237,
2864,
24899,
1132,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "./V2Keep3rJob.sol";
contract TendV2Keep3rJob is V2Keep3rJob {
constructor(
address _mechanicsRegistry,
address _keep3rProxyJob,
address _v2Keeper,
address _keep3r,
address _keep3rHelper,
address _slidingOracle
) public V2Keep3rJob(_mechanicsRegistry, _keep3rProxyJob, _v2Keeper, _keep3r, _keep3rHelper, _slidingOracle, 0, 0) {}
function _workable(address _strategy) internal view override returns (bool) {
if (!super._workable(_strategy)) return false;
(, uint256 _ethCallCost) = _getCallCosts(_strategy);
return IBaseStrategy(_strategy).tendTrigger(_ethCallCost);
}
function _work(address _strategy) internal override {
V2Keeper.tend(_strategy);
}
// Keep3r actions
function work(bytes memory _workData) external override notPaused onlyProxyJob {
_workInternal(_workData);
}
// Mechanics Setters
function setMaxCredits(uint256 _maxCredits) external override onlyGovernorOrMechanic {
_maxCredits; // shh
revert("TendV2Keep3rJob::setMaxCredits:not-implemented");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@lbertenasco/contract-utils/contracts/abstract/MachineryReady.sol";
import "../../proxy-job/Keep3rJob.sol";
import "../../interfaces/jobs/v2/IV2Keeper.sol";
import "../../interfaces/jobs/v2/IV2Keep3rJob.sol";
import "../../interfaces/keep3r/IKeep3rV1Helper.sol";
import "../../interfaces/yearn/IBaseStrategy.sol";
import "../../interfaces/keep3r/IUniswapV2SlidingOracle.sol";
abstract contract V2Keep3rJob is MachineryReady, Keep3rJob, IV2Keep3rJob {
using SafeMath for uint256;
address public constant KP3R = address(0x1cEB5cB57C4D4E2b2433641b95Dd330A33185A44);
address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
IV2Keeper public V2Keeper;
address public keep3rHelper;
address public slidingOracle;
EnumerableSet.AddressSet internal _availableStrategies;
mapping(address => uint256) public requiredAmount;
mapping(address => uint256) public lastWorkAt;
uint256 public workCooldown;
constructor(
address _mechanicsRegistry,
address _keep3rProxyJob,
address _v2Keeper,
address _keep3r,
address _keep3rHelper,
address _slidingOracle,
uint256 _workCooldown,
uint256 _maxCredits
) public MachineryReady(_mechanicsRegistry) Keep3rJob(_keep3rProxyJob) {
V2Keeper = IV2Keeper(_v2Keeper);
keep3r = _keep3r;
keep3rHelper = _keep3rHelper;
slidingOracle = _slidingOracle;
if (_workCooldown > 0) _setWorkCooldown(_workCooldown);
if (_maxCredits > 0) _setMaxCredits(_maxCredits);
}
// Setters
function setWorkCooldown(uint256 _workCooldown) external override onlyGovernorOrMechanic {
_setWorkCooldown(_workCooldown);
}
function _setWorkCooldown(uint256 _workCooldown) internal {
require(_workCooldown > 0, "V2Keep3rJob::set-work-cooldown:should-not-be-zero");
workCooldown = _workCooldown;
}
// Governor
function addStrategies(address[] calldata _strategies, uint256[] calldata _requiredAmounts) external override onlyGovernorOrMechanic {
require(_strategies.length == _requiredAmounts.length, "V2Keep3rJob::add-strategies:strategies-required-works-different-length");
for (uint256 i; i < _strategies.length; i++) {
_addStrategy(_strategies[i], _requiredAmounts[i]);
}
}
function addStrategy(address _strategy, uint256 _requiredAmount) external override onlyGovernorOrMechanic {
_addStrategy(_strategy, _requiredAmount);
}
function _addStrategy(address _strategy, uint256 _requiredAmount) internal {
require(_requiredAmount > 0, "V2Keep3rJob::add-strategy:required-amount-not-0");
require(requiredAmount[_strategy] == 0, "V2Keep3rJob::add-strategy:strategy-already-added");
_setRequiredAmount(_strategy, _requiredAmount);
emit StrategyAdded(_strategy, _requiredAmount);
_availableStrategies.add(_strategy);
}
function updateRequiredAmount(address _strategy, uint256 _requiredAmount) external override onlyGovernorOrMechanic {
require(requiredAmount[_strategy] > 0, "V2Keep3rJob::update-required-amount:strategy-not-added");
_setRequiredAmount(_strategy, _requiredAmount);
emit StrategyModified(_strategy, _requiredAmount);
}
function removeStrategy(address _strategy) external override onlyGovernorOrMechanic {
require(requiredAmount[_strategy] > 0, "V2Keep3rJob::remove-strategy:strategy-not-added");
delete requiredAmount[_strategy];
_availableStrategies.remove(_strategy);
emit StrategyRemoved(_strategy);
}
function _setRequiredAmount(address _strategy, uint256 _requiredAmount) internal {
require(_requiredAmount > 0, "V2Keep3rJob::set-required-work:should-not-be-zero");
requiredAmount[_strategy] = _requiredAmount;
}
// Getters
function strategies() public view override returns (address[] memory _strategies) {
_strategies = new address[](_availableStrategies.length());
for (uint256 i; i < _availableStrategies.length(); i++) {
_strategies[i] = _availableStrategies.at(i);
}
}
// Job actions
function getWorkData() public override returns (bytes memory _workData) {
for (uint256 i; i < _availableStrategies.length(); i++) {
address _strategy = _availableStrategies.at(i);
if (_workable(_strategy)) return abi.encode(_strategy);
}
}
function decodeWorkData(bytes memory _workData) public pure returns (address _strategy) {
return abi.decode(_workData, (address));
}
function workable() public override notPaused returns (bool) {
for (uint256 i; i < _availableStrategies.length(); i++) {
if (_workable(_availableStrategies.at(i))) return true;
}
return false;
}
function _workable(address _strategy) internal view virtual returns (bool) {
require(requiredAmount[_strategy] > 0, "V2Keep3rJob::workable:strategy-not-added");
if (block.timestamp > lastWorkAt[_strategy].add(workCooldown)) return false;
}
// Get eth costs
function _getCallCosts(address _strategy) internal view returns (uint256 _kp3rCallCost, uint256 _ethCallCost) {
_kp3rCallCost = IKeep3rV1Helper(keep3rHelper).getQuoteLimit(requiredAmount[_strategy]);
_ethCallCost = IUniswapV2SlidingOracle(slidingOracle).current(KP3R, _kp3rCallCost, WETH);
}
// Keep3r actions
function _workInternal(bytes memory _workData) internal {
address _strategy = decodeWorkData(_workData);
require(_workable(_strategy), "V2Keep3rJob::work:not-workable");
_work(_strategy);
emit Worked(_strategy);
}
// Mechanics keeper bypass
function forceWork(address _strategy) external override onlyGovernorOrMechanic {
_work(_strategy);
emit ForceWorked(_strategy);
}
function _work(address _strategy) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import './UtilsReady.sol';
import '../utils/Machinery.sol';
abstract
contract MachineryReady is UtilsReady, Machinery {
constructor(address _mechanicsRegistry) public Machinery(_mechanicsRegistry) UtilsReady() {
}
// Machinery: restricted-access
function setMechanicsRegistry(address _mechanicsRegistry) external override onlyGovernor {
_setMechanicsRegistry(_mechanicsRegistry);
}
// Machinery: modifiers
modifier onlyGovernorOrMechanic() {
require(isGovernor(msg.sender) || isMechanic(msg.sender), "Machinery::onlyGovernorOrMechanic:invalid-msg-sender");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@lbertenasco/contract-utils/interfaces/utils/IGovernable.sol";
import "@lbertenasco/contract-utils/interfaces/keep3r/IKeep3rV1.sol";
import "../interfaces/proxy-job/IKeep3rProxyJob.sol";
import "../interfaces/proxy-job/IKeep3rJob.sol";
import "../interfaces/keep3r/IChainLinkFeed.sol";
abstract contract Keep3rJob is IKeep3rJob, IGovernable {
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
IChainLinkFeed public constant FASTGAS = IChainLinkFeed(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C);
address public override keep3r;
uint256 public override usedCredits;
uint256 public override maxCredits;
uint256 public override maxGasPrice;
IKeep3rProxyJob internal Keep3rProxyJob;
constructor(address _keep3rProxyJob) public {
Keep3rProxyJob = IKeep3rProxyJob(_keep3rProxyJob);
keep3r = Keep3rProxyJob.keep3r();
}
modifier onlyProxyJob() {
require(msg.sender == address(Keep3rProxyJob), "Keep3rJob::onlyProxyJob:invalid-msg-sender");
_;
}
// view
function keep3rProxyJob() external view override returns (address _keep3rProxyJob) {
return address(Keep3rProxyJob);
}
// Credits
function _setMaxCredits(uint256 _maxCredits) internal {
usedCredits = 0;
maxCredits = _maxCredits;
}
modifier updateCredits() {
uint256 _beforeCredits = IKeep3rV1(keep3r).credits(address(Keep3rProxyJob), keep3r);
_;
uint256 _afterCredits = IKeep3rV1(keep3r).credits(address(Keep3rProxyJob), keep3r);
usedCredits = usedCredits.add(_beforeCredits.sub(_afterCredits));
require(usedCredits <= maxCredits, "Keep3rJob::update-credits:used-credits-exceed-max-credits");
}
// MaxGasPrice
function _setMaxGasPrice(uint256 _maxGasPrice) internal {
maxGasPrice = _maxGasPrice;
}
modifier limitGasPrice() {
require(uint256(FASTGAS.latestAnswer()) <= maxGasPrice, "Keep3rJob::limit-gas-price:gas-price-exceed-max");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IV2Keeper {
// Getters
function jobs() external view returns (address[] memory);
event JobAdded(address _job);
event JobRemoved(address _job);
// Setters
function addJobs(address[] calldata _jobs) external;
function addJob(address _job) external;
function removeJob(address _job) external;
// Jobs actions
function tend(address _strategy) external;
function harvest(address _strategy) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.8;
interface IV2Keep3rJob {
event Keep3rSet(address keep3r);
event Keep3rHelperSet(address keep3rHelper);
event SlidingOracleSet(address slidingOracle);
// Actions by Keeper
event Worked(address _strategy);
// Actions forced by governor
event ForceWorked(address _strategy);
// Getters
function strategies() external view returns (address[] memory);
event StrategyAdded(address _strategy, uint256 _requiredAmount);
event StrategyModified(address _strategy, uint256 _requiredAmount);
event StrategyRemoved(address _strategy);
// Setters
function setWorkCooldown(uint256 _workCooldown) external;
function addStrategies(address[] calldata _strategy, uint256[] calldata _requiredAmount) external;
function addStrategy(address _strategy, uint256 _requiredAmount) external;
function updateRequiredAmount(address _strategy, uint256 _requiredAmount) external;
function removeStrategy(address _strategy) external;
// Mechanics Setters
function setMaxCredits(uint256 _maxCredits) external;
// Mechanics keeper bypass
function forceWork(address _strategy) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3rV1Helper {
function getQuoteLimit(uint256 gasUsed) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IBaseStrategy {
function vault() external view returns (address _vault);
function strategist() external view returns (address _strategist);
function rewards() external view returns (address _rewards);
function keeper() external view returns (address _keeper);
function want() external view returns (address _want);
function name() external view returns (string memory _name);
// Setters
function setStrategist(address _strategist) external;
function setKeeper(address _keeper) external;
function setRewards(address _rewards) external;
function tendTrigger(uint256 callCost) external view returns (bool);
function tend() external;
function harvestTrigger(uint256 callCost) external view returns (bool);
function harvest() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IUniswapV2SlidingOracle {
function current(
address tokenIn,
uint256 amountIn,
address tokenOut
) external view returns (uint256);
function updatePair(address pair) external returns (bool);
function workable(address pair) external view returns (bool);
function workForFree() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../utils/Governable.sol';
import '../utils/CollectableDust.sol';
import '../utils/Pausable.sol';
abstract
contract UtilsReady is Governable, CollectableDust, Pausable {
constructor() public Governable(msg.sender) {
}
// Governable: restricted-access
function setPendingGovernor(address _pendingGovernor) external override onlyGovernor {
_setPendingGovernor(_pendingGovernor);
}
function acceptGovernor() external override onlyPendingGovernor {
_acceptGovernor();
}
// Collectable Dust: restricted-access
function sendDust(
address _to,
address _token,
uint256 _amount
) external override virtual onlyGovernor {
_sendDust(_to, _token, _amount);
}
// Pausable: restricted-access
function pause(bool _paused) external override onlyGovernor {
_pause(_paused);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import '../../interfaces/utils/IMachinery.sol';
import '../../interfaces/mechanics/IMechanicsRegistry.sol';
abstract
contract Machinery is IMachinery {
using EnumerableSet for EnumerableSet.AddressSet;
IMechanicsRegistry internal MechanicsRegistry;
constructor(address _mechanicsRegistry) public {
_setMechanicsRegistry(_mechanicsRegistry);
}
function _setMechanicsRegistry(address _mechanicsRegistry) internal {
MechanicsRegistry = IMechanicsRegistry(_mechanicsRegistry);
}
// View helpers
function mechanicsRegistry() external view override returns (address _mechanicRegistry) {
return address(MechanicsRegistry);
}
function isMechanic(address _mechanic) public view override returns (bool _isMechanic) {
return MechanicsRegistry.isMechanic(_mechanic);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../../interfaces/utils/IGovernable.sol';
abstract
contract Governable is IGovernable {
address public override governor;
address public override pendingGovernor;
constructor(address _governor) public {
require(_governor != address(0), 'governable/governor-should-not-be-zero-address');
governor = _governor;
}
function _setPendingGovernor(address _pendingGovernor) internal {
require(_pendingGovernor != address(0), 'governable/pending-governor-should-not-be-zero-addres');
pendingGovernor = _pendingGovernor;
emit PendingGovernorSet(_pendingGovernor);
}
function _acceptGovernor() internal {
governor = pendingGovernor;
pendingGovernor = address(0);
emit GovernorAccepted();
}
function isGovernor(address _account) public view override returns (bool _isGovernor) {
return _account == governor;
}
modifier onlyGovernor {
require(isGovernor(msg.sender), 'governable/only-governor');
_;
}
modifier onlyPendingGovernor {
require(msg.sender == pendingGovernor, 'governable/only-pending-governor');
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/EnumerableSet.sol';
import '@openzeppelin/contracts/token/ERC20/IERC20.sol';
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import '../../interfaces/utils/ICollectableDust.sol';
abstract
contract CollectableDust is ICollectableDust {
using SafeERC20 for IERC20;
using EnumerableSet for EnumerableSet.AddressSet;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
EnumerableSet.AddressSet internal protocolTokens;
constructor() public {}
function _addProtocolToken(address _token) internal {
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
protocolTokens.add(_token);
}
function _removeProtocolToken(address _token) internal {
require(protocolTokens.contains(_token), 'collectable-dust/token-not-part-of-the-protocol');
protocolTokens.remove(_token);
}
function _sendDust(
address _to,
address _token,
uint256 _amount
) internal {
require(_to != address(0), 'collectable-dust/cant-send-dust-to-zero-address');
require(!protocolTokens.contains(_token), 'collectable-dust/token-is-part-of-the-protocol');
if (_token == ETH_ADDRESS) {
payable(_to).transfer(_amount);
} else {
IERC20(_token).safeTransfer(_to, _amount);
}
emit DustSent(_to, _token, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import '../../interfaces/utils/IPausable.sol';
abstract
contract Pausable is IPausable {
bool public paused;
constructor() public {}
modifier notPaused() {
require(!paused, 'paused');
_;
}
function _pause(bool _paused) internal {
require(paused != _paused, 'no-change');
paused = _paused;
emit Paused(_paused);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IGovernable {
event PendingGovernorSet(address pendingGovernor);
event GovernorAccepted();
function setPendingGovernor(address _pendingGovernor) external;
function acceptGovernor() external;
function governor() external view returns (address _governor);
function pendingGovernor() external view returns (address _pendingGovernor);
function isGovernor(address _account) external view returns (bool _isGovernor);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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;
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.12;
interface ICollectableDust {
event DustSent(address _to, address token, uint256 amount);
function sendDust(address _to, address _token, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IPausable {
event Paused(bool _paused);
function pause(bool _paused) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IMachinery {
// View helpers
function mechanicsRegistry() external view returns (address _mechanicsRegistry);
function isMechanic(address mechanic) external view returns (bool _isMechanic);
// Setters
function setMechanicsRegistry(address _mechanicsRegistry) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IMechanicsRegistry {
event MechanicAdded(address _mechanic);
event MechanicRemoved(address _mechanic);
function addMechanic(address _mechanic) external;
function removeMechanic(address _mechanic) external;
function mechanics() external view returns (address[] memory _mechanicsList);
function isMechanic(address mechanic) external view returns (bool _isMechanic);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3rV1 {
function name() external returns (string memory);
function isKeeper(address _keeper) external returns (bool);
function isMinKeeper(address _keeper, uint256 _minBond, uint256 _earned, uint256 _age) external returns (bool);
function isBondedKeeper(address _keeper, address bond, uint256 _minBond, uint256 _earned, uint256 _age) external returns (bool);
function addKPRCredit(address _job, uint256 _amount) external;
function addJob(address _job) external;
function worked(address _keeper) external;
function workReceipt(address _keeper, uint256 _amount) external;
function receipt(address credit, address _keeper, uint256 _amount) external;
function receiptETH(address _keeper, uint256 _amount) external;
function addLiquidityToJob(address liquidity, address job, uint amount) external;
function applyCreditToJob(address provider, address liquidity, address job) external;
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external;
function removeLiquidityFromJob(address liquidity, address job) external;
function credits(address _job, address _credit) external view returns (uint256 _amount);
function liquidityProvided(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityApplied(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityAmount(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityUnbonding(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
function liquidityAmountsUnbonding(address _provider, address _liquidity, address _job) external view returns (uint256 _amount);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@lbertenasco/contract-utils/interfaces/keep3r/IKeep3r.sol";
interface IKeep3rProxyJob is IKeep3r {
event Worked(address _job, address _keeper);
function jobs() external view returns (address[] memory validJobs);
function work(address _job, bytes calldata _workData) external;
// use callStatic
function workable(address _job) external returns (bool _workable);
function isValidJob(address _job) external view returns (bool _valid);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3rJob {
function keep3r() external view returns (address _keep3r);
function keep3rProxyJob() external view returns (address _keep3rProxyJob);
function usedCredits() external view returns (uint256 _usedCredits);
function maxCredits() external view returns (uint256 _maxCredits);
function maxGasPrice() external view returns (uint256 _maxGasPrice);
function work(bytes calldata _workData) external;
// use callStatic for the following functions:
function workable() external returns (bool);
function getWorkData() external returns (bytes memory _workData);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IChainLinkFeed {
function latestAnswer() external view returns (int256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
interface IKeep3r {
event Keep3rSet(address _keep3r);
event Keep3rRequirementsSet(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA);
function keep3r() external view returns (address _keep3r);
function setKeep3r(address _keep3r) external;
function setKeep3rRequirements(address _bond, uint256 _minBond, uint256 _earned, uint256 _age, bool _onlyEOA) external;
} | Mechanics keeper bypass | function forceWork(address _strategy) external override onlyGovernorOrMechanic {
_work(_strategy);
emit ForceWorked(_strategy);
}
| 5,989,256 | [
1,
4667,
7472,
2102,
417,
9868,
17587,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2944,
2421,
12,
2867,
389,
14914,
13,
3903,
3849,
1338,
43,
1643,
29561,
1162,
4667,
7472,
335,
288,
203,
3639,
389,
1252,
24899,
14914,
1769,
203,
3639,
3626,
11889,
2421,
329,
24899,
14914,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
//Address: 0x7268f9c2bc9c9e65b4a16888cb5672531ce8e945
//Contract name: DayToken
//Balance: 0 Ether
//Verification Date: 9/15/2017
//Transacion Count: 4246
// CODE STARTS HERE
pragma solidity ^0.4.13;
////////////////// >>>>> Wallet Contract <<<<< ///////////////////
/// @title Multisignature wallet - Allows multiple parties to agree on transactions before execution.
/// @author Stefan George - <[email protected]>
contract MultiSigWallet {
uint constant public MAX_OWNER_COUNT = 50;
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event RequirementChange(uint required);
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
modifier onlyWallet() {
if (msg.sender != address(this))
throw;
_;
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
throw;
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
throw;
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
throw;
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
throw;
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
throw;
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
throw;
_;
}
modifier notNull(address _address) {
if (_address == 0)
throw;
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
throw;
_;
}
/// @dev Fallback function allows to deposit ether.
function()
payable
{
if (msg.value > 0)
Deposit(msg.sender, msg.value);
}
/*
* Public functions
*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
function MultiSigWallet(address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
throw;
isOwner[_owners[i]] = true;
}
owners = _owners;
required = _required;
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
OwnerRemoval(owner);
OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction tx = transactions[transactionId];
tx.executed = true;
if (tx.destination.call.value(tx.value)(tx.data))
Execution(transactionId);
else {
ExecutionFailure(transactionId);
tx.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*
* Internal functions
*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if ( pending && !transactions[i].executed
|| executed && transactions[i].executed)
{
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
}
////////////////// >>>>> Library Contracts <<<<< ///////////////////
contract SafeMathLib {
function safeMul(uint a, uint b) constant returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeSub(uint a, uint b) constant returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) constant returns (uint) {
uint 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;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
////////////////// >>>>> Token Contracts <<<<< ///////////////////
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Basic {
uint public totalSupply;
function balanceOf(address _owner) constant returns (uint balance);
function transfer(address _to, uint _value) returns (bool success);
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) constant returns (uint remaining);
function transferFrom(address _from, address _to, uint _value) returns (bool success);
function approve(address _spender, uint _value) returns (bool success);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
/**
* Standard ERC20 token with Short Hand Attack and approve() race condition mitigation.
*
* Based on code by FirstBlood:
* https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, SafeMathLib {
/* Token supply got increased and a new owner received these tokens */
event Minted(address receiver, uint amount);
/* Actual balances of token holders */
mapping(address => uint) balances;
/* approve() allowances */
mapping (address => mapping (address => uint)) allowed;
function transfer(address _to, uint _value) returns (bool success) {
if (balances[msg.sender] >= _value
&& _value > 0
&& balances[_to] + _value > balances[_to]
) {
balances[msg.sender] = safeSub(balances[msg.sender],_value);
balances[_to] = safeAdd(balances[_to],_value);
Transfer(msg.sender, _to, _value);
return true;
}
else{
return false;
}
}
function transferFrom(address _from, address _to, uint _value) returns (bool success) {
uint _allowance = allowed[_from][msg.sender];
if (balances[_from] >= _value // From a/c has balance
&& _allowance >= _value // Transfer approved
&& _value > 0 // Non-zero transfer
&& balances[_to] + _value > balances[_to] // Overflow check
){
balances[_to] = safeAdd(balances[_to],_value);
balances[_from] = safeSub(balances[_from],_value);
allowed[_from][msg.sender] = safeSub(_allowance,_value);
Transfer(_from, _to, _value);
return true;
}
else {
return false;
}
}
function balanceOf(address _owner) constant returns (uint balance) {
return balances[_owner];
}
function approve(address _spender, uint _value) returns (bool success) {
// 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;
}
function allowance(address _owner, address _spender) constant returns (uint remaining) {
return allowed[_owner][_spender];
}
}
/**
* A token that can increase its supply by another contract.
*
* This allows uncapped crowdsale by dynamically increasing the supply when money pours in.
* Only mint agents, contracts whitelisted by owner, can mint new tokens.
*
*/
contract MintableToken is StandardToken, Ownable {
bool public mintingFinished = false;
/** List of agents that are allowed to create new tokens */
mapping (address => bool) public mintAgents;
event MintingAgentChanged(address addr, bool state );
/**
* Create new tokens and allocate them to an address..
*
* Only callably by a crowdsale contract (mint agent).
*/
function mint(address receiver, uint amount) onlyMintAgent canMint public {
totalSupply = safeAdd(totalSupply, amount);
balances[receiver] = safeAdd(balances[receiver], amount);
// This will make the mint transaction apper in EtherScan.io
// We can remove this after there is a standardized minting event
Transfer(0, receiver, amount);
}
/**
* Owner can allow a crowdsale contract to mint new tokens.
*/
function setMintAgent(address addr, bool state) onlyOwner canMint public {
mintAgents[addr] = state;
MintingAgentChanged(addr, state);
}
modifier onlyMintAgent() {
// Only crowdsale contracts are allowed to mint new tokens
require(mintAgents[msg.sender]);
_;
}
/** Make sure we are not done yet. */
modifier canMint() {
require(!mintingFinished);
_;
}
}
/**
* Define interface for releasing the token transfer after a successful crowdsale.
*/
contract ReleasableToken is ERC20, Ownable {
/* The finalizer contract that allows unlift the transfer limits on this token */
address public releaseAgent;
/** A crowdsale contract can release us to the wild if ICO success.
* If false we are are in transfer lock up period.
*/
bool public released = false;
/** Map of agents that are allowed to transfer tokens regardless of the lock down period.
* These are crowdsale contracts and possible the team multisig itself.
*/
mapping (address => bool) public transferAgents;
/**
* Limit token transfer until the crowdsale is over.
*/
modifier canTransfer(address _sender) {
if (!released) {
require(transferAgents[_sender]);
}
_;
}
/**
* Set the contract that can call release and make the token transferable.
*
* Design choice. Allow reset the release agent to fix fat finger mistakes.
*/
function setReleaseAgent(address addr) onlyOwner inReleaseState(false) public {
// We don't do interface check here as we might want to a normal wallet address to act as a release agent
releaseAgent = addr;
}
/**
* Owner can allow a particular address (a crowdsale contract) to transfer tokens despite the lock up period.
*/
function setTransferAgent(address addr, bool state) onlyOwner inReleaseState(false) public {
transferAgents[addr] = state;
}
/**
* One way function to release the tokens to the wild.
*
* Can be called only from the release agent that is the final ICO contract.
* It is only called if the crowdsale has been success (first milestone reached).
*/
function releaseTokenTransfer() public onlyReleaseAgent {
released = true;
}
/** The function can be called only before or after the tokens have been releasesd */
modifier inReleaseState(bool releaseState) {
require(releaseState == released);
_;
}
/** The function can be called only by a whitelisted release agent. */
modifier onlyReleaseAgent() {
require(msg.sender == releaseAgent);
_;
}
function transfer(address _to, uint _value) canTransfer(msg.sender) returns (bool success) {
// Call StandardToken.transfer()
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) canTransfer(_from) returns (bool success) {
// Call StandardToken.transferForm()
return super.transferFrom(_from, _to, _value);
}
}
/**
* Upgrade agent interface inspired by Lunyr.
*
* Upgrade agent transfers tokens to a new contract.
* Upgrade agent itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract UpgradeAgent {
uint public originalSupply;
/** Interface marker */
function isUpgradeAgent() public constant returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public;
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*/
contract UpgradeableToken is StandardToken {
/** Contract / person who can set the upgrade path.
* This can be the same as team multisig wallet, as what it is with its default value.
*/
address public upgradeMaster;
/** The next contract where the tokens will be migrated. */
UpgradeAgent public upgradeAgent;
/** How many tokens we have upgraded by now. */
uint256 public totalUpgraded;
/**
* Upgrade states.
*
* - NotAllowed: The child contract has not reached a condition where the upgrade can bgun
* - WaitingForAgent: Token allows upgrade, but we don't have a new agent yet
* - ReadyToUpgrade: The agent is set, but not a single token has been upgraded yet
* - Upgrading: Upgrade agent is set and the balance holders can upgrade their tokens
*
*/
enum UpgradeState {Unknown, NotAllowed, WaitingForAgent, ReadyToUpgrade, Upgrading}
/**
* Somebody has upgraded some of their tokens.
*/
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
/**
* New upgrade agent available.
*/
event UpgradeAgentSet(address agent);
/**
* Do not allow construction without upgrade master set.
*/
function UpgradeableToken(address _upgradeMaster) {
upgradeMaster = _upgradeMaster;
}
/**
* Allow the token holder to upgrade some of their tokens to a new contract.
*/
function upgrade(uint256 value) public {
UpgradeState state = getUpgradeState();
require((state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading));
// Validate input value.
require(value!=0);
balances[msg.sender] = safeSub(balances[msg.sender],value);
// Take tokens out from circulation
totalSupply = safeSub(totalSupply,value);
totalUpgraded = safeAdd(totalUpgraded,value);
// Upgrade agent reissues the tokens
upgradeAgent.upgradeFrom(msg.sender, value);
Upgrade(msg.sender, upgradeAgent, value);
}
/**
* Set an upgrade agent that handles
*/
function setUpgradeAgent(address agent) external {
require(canUpgrade());
require(agent != 0x0);
// Only a master can designate the next agent
require(msg.sender == upgradeMaster);
// Upgrade has already begun for an agent
require(getUpgradeState() != UpgradeState.Upgrading);
upgradeAgent = UpgradeAgent(agent);
// Bad interface
require(upgradeAgent.isUpgradeAgent());
// Make sure that token supplies match in source and target
require(upgradeAgent.originalSupply() == totalSupply);
UpgradeAgentSet(upgradeAgent);
}
/**
* Get the state of the token upgrade.
*/
function getUpgradeState() public constant returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if(address(upgradeAgent) == 0x00) return UpgradeState.WaitingForAgent;
else if(totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
/**
* Change the upgrade master.
*
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address master) public {
require(master != 0x0);
require(msg.sender == upgradeMaster);
upgradeMaster = master;
}
/**
* Child contract can enable to provide the condition when the upgrade can begun.
*/
function canUpgrade() public constant returns(bool) {
return true;
}
}
/**
* A crowdsale token.
*
* An ERC-20 token designed specifically for crowdsales with investor protection and
* further development path.
*
* - The token transfer() is disabled until the crowdsale is over
* - The token contract gives an opt-in upgrade path to a new contract
* - The same token can be part of several crowdsales through approve() mechanism
* - The token can be capped (supply set in the constructor)
* or uncapped (crowdsale contract can mint new tokens)
*/
contract DayToken is ReleasableToken, MintableToken, UpgradeableToken {
enum sellingStatus {NOTONSALE, EXPIRED, ONSALE}
/** Basic structure for a contributor with a minting Address
* adr address of the contributor
* initialContributionDay initial contribution of the contributor in wei
* lastUpdatedOn day count from Minting Epoch when the account balance was last updated
* mintingPower Initial Minting power of the address
* expiryBlockNumber Variable to mark end of Minting address sale. Set by user
* minPriceInDay minimum price of Minting address in Day tokens. Set by user
* status Selling status Variable for transfer Minting address.
* sellingPriceInDay Variable for transfer Minting address. Price at which the address is actually sold
*/
struct Contributor {
address adr;
uint256 initialContributionDay;
uint256 lastUpdatedOn; //Day from Minting Epoch
uint256 mintingPower;
uint expiryBlockNumber;
uint256 minPriceInDay;
sellingStatus status;
}
/* Stores maximum days for which minting will happen since minting epoch */
uint256 public maxMintingDays = 1095;
/* Mapping to store id of each minting address */
mapping (address => uint) public idOf;
/* Mapping from id of each minting address to their respective structures */
mapping (uint256 => Contributor) public contributors;
/* mapping to store unix timestamp of when the minting address is issued to each team member */
mapping (address => uint256) public teamIssuedTimestamp;
mapping (address => bool) public soldAddresses;
mapping (address => uint256) public sellingPriceInDayOf;
/* Stores the id of the first contributor */
uint256 public firstContributorId;
/* Stores total Pre + Post ICO TimeMints */
uint256 public totalNormalContributorIds;
/* Stores total Normal TimeMints allocated */
uint256 public totalNormalContributorIdsAllocated = 0;
/* Stores the id of the first team TimeMint */
uint256 public firstTeamContributorId;
/* Stores the total team TimeMints */
uint256 public totalTeamContributorIds;
/* Stores total team TimeMints allocated */
uint256 public totalTeamContributorIdsAllocated = 0;
/* Stores the id of the first Post ICO contributor (for auctionable TimeMints) */
uint256 public firstPostIcoContributorId;
/* Stores total Post ICO TimeMints (for auction) */
uint256 public totalPostIcoContributorIds;
/* Stores total Auction TimeMints allocated */
uint256 public totalPostIcoContributorIdsAllocated = 0;
/* Maximum number of address */
uint256 public maxAddresses;
/* Min Minting power with 19 decimals: 0.5% : 5000000000000000000 */
uint256 public minMintingPower;
/* Max Minting power with 19 decimals: 1% : 10000000000000000000 */
uint256 public maxMintingPower;
/* Halving cycle in days (88) */
uint256 public halvingCycle;
/* Unix timestamp when minting is to be started */
uint256 public initialBlockTimestamp;
/* Flag to prevent setting initialBlockTimestamp more than once */
bool public isInitialBlockTimestampSet;
/* number of decimals in minting power */
uint256 public mintingDec;
/* Minimum Balance in Day tokens required to sell a minting address */
uint256 public minBalanceToSell;
/* Team address lock down period from issued time, in seconds */
uint256 public teamLockPeriodInSec; //Initialize and set function
/* Duration in secs that we consider as a day. (For test deployment purposes,
if we want to decrease length of a day. default: 84600)*/
uint256 public DayInSecs;
event UpdatedTokenInformation(string newName, string newSymbol);
event MintingAdrTransferred(uint id, address from, address to);
event ContributorAdded(address adr, uint id);
event TimeMintOnSale(uint id, address seller, uint minPriceInDay, uint expiryBlockNumber);
event TimeMintSold(uint id, address buyer, uint offerInDay);
event PostInvested(address investor, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId);
event TeamAddressAdded(address teamAddress, uint id);
// Tell us invest was success
event Invested(address receiver, uint weiAmount, uint tokenAmount, uint customerId, uint contributorId);
modifier onlyContributor(uint id){
require(isValidContributorId(id));
_;
}
string public name;
string public symbol;
uint8 public decimals;
/**
* Construct the token.
*
* This token must be created through a team multisig wallet, so that it is owned by that wallet.
*
* @param _name Token name
* @param _symbol Token symbol - should be all caps
* @param _initialSupply How many tokens we start with
* @param _decimals Number of decimal places
* _mintable Are new tokens created over the crowdsale or do we distribute only the initial supply?
*/
function DayToken(string _name, string _symbol, uint _initialSupply, uint8 _decimals,
bool _mintable, uint _maxAddresses, uint _firstTeamContributorId, uint _totalTeamContributorIds,
uint _totalPostIcoContributorIds, uint256 _minMintingPower, uint256 _maxMintingPower, uint _halvingCycle,
uint256 _minBalanceToSell, uint256 _dayInSecs, uint256 _teamLockPeriodInSec)
UpgradeableToken(msg.sender) {
// Create any address, can be transferred
// to team multisig via changeOwner(),
// also remember to call setUpgradeMaster()
owner = msg.sender;
name = _name;
symbol = _symbol;
totalSupply = _initialSupply;
decimals = _decimals;
// Create initially all balance on the team multisig
balances[owner] = totalSupply;
maxAddresses = _maxAddresses;
require(maxAddresses > 1); // else division by zero will occur in setInitialMintingPowerOf
firstContributorId = 1;
totalNormalContributorIds = maxAddresses - _totalTeamContributorIds - _totalPostIcoContributorIds;
// check timeMint total is sane
require(totalNormalContributorIds >= 1);
firstTeamContributorId = _firstTeamContributorId;
totalTeamContributorIds = _totalTeamContributorIds;
totalPostIcoContributorIds = _totalPostIcoContributorIds;
// calculate first contributor id to be auctioned post ICO
firstPostIcoContributorId = maxAddresses - totalPostIcoContributorIds + 1;
minMintingPower = _minMintingPower;
maxMintingPower = _maxMintingPower;
halvingCycle = _halvingCycle;
// setting future date far far away, year 2020,
// call setInitialBlockTimestamp to set proper timestamp
initialBlockTimestamp = 1577836800;
isInitialBlockTimestampSet = false;
// use setMintingDec to change this
mintingDec = 19;
minBalanceToSell = _minBalanceToSell;
DayInSecs = _dayInSecs;
teamLockPeriodInSec = _teamLockPeriodInSec;
if (totalSupply > 0) {
Minted(owner, totalSupply);
}
if (!_mintable) {
mintingFinished = true;
require(totalSupply != 0);
}
}
/**
* Used to set timestamp at which minting power of TimeMints is activated
* Can be called only by owner
* @param _initialBlockTimestamp timestamp to be set.
*/
function setInitialBlockTimestamp(uint _initialBlockTimestamp) internal onlyOwner {
require(!isInitialBlockTimestampSet);
isInitialBlockTimestampSet = true;
initialBlockTimestamp = _initialBlockTimestamp;
}
/**
* check if mintining power is activated and Day token and Timemint transfer is enabled
*/
function isDayTokenActivated() constant returns (bool isActivated) {
return (block.timestamp >= initialBlockTimestamp);
}
/**
* to check if an id is a valid contributor
* @param _id contributor id to check.
*/
function isValidContributorId(uint _id) constant returns (bool isValidContributor) {
return (_id > 0 && _id <= maxAddresses && contributors[_id].adr != 0
&& idOf[contributors[_id].adr] == _id); // cross checking
}
/**
* to check if an address is a valid contributor
* @param _address contributor address to check.
*/
function isValidContributorAddress(address _address) constant returns (bool isValidContributor) {
return isValidContributorId(idOf[_address]);
}
/**
* In case of Team address check if lock-in period is over (returns true for all non team addresses)
* @param _address team address to check lock in period for.
*/
function isTeamLockInPeriodOverIfTeamAddress(address _address) constant returns (bool isLockInPeriodOver) {
isLockInPeriodOver = true;
if (teamIssuedTimestamp[_address] != 0) {
if (block.timestamp - teamIssuedTimestamp[_address] < teamLockPeriodInSec)
isLockInPeriodOver = false;
}
return isLockInPeriodOver;
}
/**
* Used to set mintingDec
* Can be called only by owner
* @param _mintingDec bounty to be set.
*/
function setMintingDec(uint256 _mintingDec) onlyOwner {
require(!isInitialBlockTimestampSet);
mintingDec = _mintingDec;
}
/**
* When token is released to be transferable, enforce no new tokens can be created.
*/
function releaseTokenTransfer() public onlyOwner {
require(isInitialBlockTimestampSet);
mintingFinished = true;
super.releaseTokenTransfer();
}
/**
* Allow upgrade agent functionality kick in only if the crowdsale was success.
*/
function canUpgrade() public constant returns(bool) {
return released && super.canUpgrade();
}
/**
* Owner can update token information here
*/
function setTokenInformation(string _name, string _symbol) onlyOwner {
name = _name;
symbol = _symbol;
UpdatedTokenInformation(name, symbol);
}
/**
* Returns the current phase.
* Note: Phase starts with 1
* @param _day Number of days since Minting Epoch
*/
function getPhaseCount(uint _day) public constant returns (uint phase) {
phase = (_day/halvingCycle) + 1;
return (phase);
}
/**
* Returns current day number since minting epoch
* or zero if initialBlockTimestamp is in future or its DayZero.
*/
function getDayCount() public constant returns (uint daySinceMintingEpoch) {
daySinceMintingEpoch = 0;
if (isDayTokenActivated())
daySinceMintingEpoch = (block.timestamp - initialBlockTimestamp)/DayInSecs;
return daySinceMintingEpoch;
}
/**
* Calculates and Sets the minting power of a particular id.
* Called before Minting Epoch by constructor
* @param _id id of the address whose minting power is to be set.
*/
function setInitialMintingPowerOf(uint256 _id) internal onlyContributor(_id) {
contributors[_id].mintingPower =
(maxMintingPower - ((_id-1) * (maxMintingPower - minMintingPower)/(maxAddresses-1)));
}
/**
* Returns minting power of a particular id.
* @param _id Contribution id whose minting power is to be returned
*/
function getMintingPowerById(uint _id) public constant returns (uint256 mintingPower) {
return contributors[_id].mintingPower/(2**(getPhaseCount(getDayCount())-1));
}
/**
* Returns minting power of a particular address.
* @param _adr Address whose minting power is to be returned
*/
function getMintingPowerByAddress(address _adr) public constant returns (uint256 mintingPower) {
return getMintingPowerById(idOf[_adr]);
}
/**
* Calculates and returns the balance based on the minting power, day and phase.
* Can only be called internally
* Can calculate balance based on last updated.
* @param _id id whose balnce is to be calculated
* @param _dayCount day count upto which balance is to be updated
*/
function availableBalanceOf(uint256 _id, uint _dayCount) internal returns (uint256) {
uint256 balance = balances[contributors[_id].adr];
uint maxUpdateDays = _dayCount < maxMintingDays ? _dayCount : maxMintingDays;
uint i = contributors[_id].lastUpdatedOn + 1;
while(i <= maxUpdateDays) {
uint phase = getPhaseCount(i);
uint phaseEndDay = phase * halvingCycle - 1; // as first day is 0
uint constantFactor = contributors[_id].mintingPower / 2**(phase-1);
for (uint j = i; j <= phaseEndDay && j <= maxUpdateDays; j++) {
balance = safeAdd( balance, constantFactor * balance / 10**(mintingDec + 2) );
}
i = j;
}
return balance;
}
/**
* Updates the balance of the specified id in its structure and also in the balances[] mapping.
* returns true if successful.
* Only for internal calls. Not public.
* @param _id id whose balance is to be updated.
*/
function updateBalanceOf(uint256 _id) internal returns (bool success) {
// check if its contributor
if (isValidContributorId(_id)) {
uint dayCount = getDayCount();
// proceed only if not already updated today
if (contributors[_id].lastUpdatedOn != dayCount && contributors[_id].lastUpdatedOn < maxMintingDays) {
address adr = contributors[_id].adr;
uint oldBalance = balances[adr];
totalSupply = safeSub(totalSupply, oldBalance);
uint newBalance = availableBalanceOf(_id, dayCount);
balances[adr] = newBalance;
totalSupply = safeAdd(totalSupply, newBalance);
contributors[_id].lastUpdatedOn = dayCount;
Transfer(0, adr, newBalance - oldBalance);
return true;
}
}
return false;
}
/**
* Standard ERC20 function overridden.
* Returns the balance of the specified address.
* Calculates the balance on fly only if it is a minting address else
* simply returns balance from balances[] mapping.
* For public calls.
* @param _adr address whose balance is to be returned.
*/
function balanceOf(address _adr) constant returns (uint balance) {
uint id = idOf[_adr];
if (id != 0)
return balanceById(id);
else
return balances[_adr];
}
/**
* Standard ERC20 function overridden.
* Returns the balance of the specified id.
* Calculates the balance on fly only if it is a minting address else
* simply returns balance from balances[] mapping.
* For public calls.
* @param _id address whose balance is to be returned.
*/
function balanceById(uint _id) public constant returns (uint256 balance) {
address adr = contributors[_id].adr;
if (isDayTokenActivated()) {
if (isValidContributorId(_id)) {
return ( availableBalanceOf(_id, getDayCount()) );
}
}
return balances[adr];
}
/**
* Returns totalSupply of DAY tokens.
*/
function getTotalSupply() public constant returns (uint) {
return totalSupply;
}
/** Function to update balance of a Timemint
* returns true if balance updated, false otherwise
* @param _id TimeMint to update
*/
function updateTimeMintBalance(uint _id) public returns (bool) {
require(isDayTokenActivated());
return updateBalanceOf(_id);
}
/** Function to update balance of sender's Timemint
* returns true if balance updated, false otherwise
*/
function updateMyTimeMintBalance() public returns (bool) {
require(isDayTokenActivated());
return updateBalanceOf(idOf[msg.sender]);
}
/**
* Standard ERC20 function overidden.
* Used to transfer day tokens from caller's address to another
* @param _to address to which Day tokens are to be transferred
* @param _value Number of Day tokens to be transferred
*/
function transfer(address _to, uint _value) public returns (bool success) {
require(isDayTokenActivated());
// if Team address, check if lock-in period is over
require(isTeamLockInPeriodOverIfTeamAddress(msg.sender));
updateBalanceOf(idOf[msg.sender]);
// Check sender account has enough balance and transfer amount is non zero
require ( balanceOf(msg.sender) >= _value && _value != 0 );
updateBalanceOf(idOf[_to]);
balances[msg.sender] = safeSub(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* Standard ERC20 Standard Token function overridden. Added Team address vesting period lock.
*/
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(isDayTokenActivated());
// if Team address, check if lock-in period is over
require(isTeamLockInPeriodOverIfTeamAddress(_from));
uint _allowance = allowed[_from][msg.sender];
updateBalanceOf(idOf[_from]);
// Check from account has enough balance, transfer amount is non zero
// and _value is allowed to be transferred
require ( balanceOf(_from) >= _value && _value != 0 && _value <= _allowance);
updateBalanceOf(idOf[_to]);
allowed[_from][msg.sender] = safeSub(_allowance, _value);
balances[_from] = safeSub(balances[_from], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(_from, _to, _value);
return true;
}
/**
* Add any contributor structure (For every kind of contributors: Team/Pre-ICO/ICO/Test)
* @param _adr Address of the contributor to be added
* @param _initialContributionDay Initial Contribution of the contributor to be added
*/
function addContributor(uint contributorId, address _adr, uint _initialContributionDay) internal onlyOwner {
require(contributorId <= maxAddresses);
//address should not be an existing contributor
require(!isValidContributorAddress(_adr));
//TimeMint should not be already allocated
require(!isValidContributorId(contributorId));
contributors[contributorId].adr = _adr;
idOf[_adr] = contributorId;
setInitialMintingPowerOf(contributorId);
contributors[contributorId].initialContributionDay = _initialContributionDay;
contributors[contributorId].lastUpdatedOn = getDayCount();
ContributorAdded(_adr, contributorId);
contributors[contributorId].status = sellingStatus.NOTONSALE;
}
/** Function to be called by minting addresses in order to sell their address
* @param _minPriceInDay Minimum price in DAY tokens set by the seller
* @param _expiryBlockNumber Expiry Block Number set by the seller
*/
function sellMintingAddress(uint256 _minPriceInDay, uint _expiryBlockNumber) public returns (bool) {
require(isDayTokenActivated());
require(_expiryBlockNumber > block.number);
// if Team address, check if lock-in period is over
require(isTeamLockInPeriodOverIfTeamAddress(msg.sender));
uint id = idOf[msg.sender];
require(contributors[id].status == sellingStatus.NOTONSALE);
// update balance of sender address before checking for minimum required balance
updateBalanceOf(id);
require(balances[msg.sender] >= minBalanceToSell);
contributors[id].minPriceInDay = _minPriceInDay;
contributors[id].expiryBlockNumber = _expiryBlockNumber;
contributors[id].status = sellingStatus.ONSALE;
balances[msg.sender] = safeSub(balances[msg.sender], minBalanceToSell);
balances[this] = safeAdd(balances[this], minBalanceToSell);
Transfer(msg.sender, this, minBalanceToSell);
TimeMintOnSale(id, msg.sender, contributors[id].minPriceInDay, contributors[id].expiryBlockNumber);
return true;
}
/** Function to be called by minting address in order to cancel the sale of their TimeMint
*/
function cancelSaleOfMintingAddress() onlyContributor(idOf[msg.sender]) public {
uint id = idOf[msg.sender];
// TimeMint should be on sale
require(contributors[id].status == sellingStatus.ONSALE);
contributors[id].status = sellingStatus.EXPIRED;
}
/** Function to be called by any user to get a list of all On Sale TimeMints
*/
function getOnSaleIds() constant public returns(uint[]) {
uint[] memory idsOnSale = new uint[](maxAddresses);
uint j = 0;
for(uint i=1; i <= maxAddresses; i++) {
if ( isValidContributorId(i) &&
block.number <= contributors[i].expiryBlockNumber &&
contributors[i].status == sellingStatus.ONSALE ) {
idsOnSale[j] = i;
j++;
}
}
return idsOnSale;
}
/** Function to be called by any user to get status of a Time Mint.
* returns status 0 - Not on sale, 1 - Expired, 2 - On sale,
* @param _id ID number of the Time Mint
*/
function getSellingStatus(uint _id) constant public returns(sellingStatus status) {
require(isValidContributorId(_id));
status = contributors[_id].status;
if ( block.number > contributors[_id].expiryBlockNumber &&
status == sellingStatus.ONSALE )
status = sellingStatus.EXPIRED;
return status;
}
/** Function to be called by any user to buy a onsale address by offering an amount
* @param _offerId ID number of the address to be bought by the buyer
* @param _offerInDay Offer given by the buyer in number of DAY tokens
*/
function buyMintingAddress(uint _offerId, uint256 _offerInDay) public returns(bool) {
if (contributors[_offerId].status == sellingStatus.ONSALE
&& block.number > contributors[_offerId].expiryBlockNumber)
{
contributors[_offerId].status = sellingStatus.EXPIRED;
}
address soldAddress = contributors[_offerId].adr;
require(contributors[_offerId].status == sellingStatus.ONSALE);
require(_offerInDay >= contributors[_offerId].minPriceInDay);
// prevent seller from cancelling sale in between
contributors[_offerId].status = sellingStatus.NOTONSALE;
// first get the offered DayToken in the token contract &
// then transfer the total sum (minBalanceToSend+_offerInDay) to the seller
balances[msg.sender] = safeSub(balances[msg.sender], _offerInDay);
balances[this] = safeAdd(balances[this], _offerInDay);
Transfer(msg.sender, this, _offerInDay);
if(transferMintingAddress(contributors[_offerId].adr, msg.sender)) {
//mark the offer as sold & let seller pull the proceed to their own account.
sellingPriceInDayOf[soldAddress] = _offerInDay;
soldAddresses[soldAddress] = true;
TimeMintSold(_offerId, msg.sender, _offerInDay);
}
return true;
}
/**
* Transfer minting address from one user to another
* Gives the transfer-to address, the id of the original address
* returns true if successful and false if not.
* @param _to address of the user to which minting address is to be tranferred
*/
function transferMintingAddress(address _from, address _to) internal onlyContributor(idOf[_from]) returns (bool) {
require(isDayTokenActivated());
// _to should be non minting address
require(!isValidContributorAddress(_to));
uint id = idOf[_from];
// update balance of from address before transferring minting power
updateBalanceOf(id);
contributors[id].adr = _to;
idOf[_to] = id;
idOf[_from] = 0;
contributors[id].initialContributionDay = 0;
// needed as id is assigned to new address
contributors[id].lastUpdatedOn = getDayCount();
contributors[id].expiryBlockNumber = 0;
contributors[id].minPriceInDay = 0;
MintingAdrTransferred(id, _from, _to);
return true;
}
/** Function to allow seller to get back their deposited amount of day tokens(minBalanceToSell) and
* offer made by buyer after successful sale.
* Throws if sale is not successful
*/
function fetchSuccessfulSaleProceed() public returns(bool) {
require(soldAddresses[msg.sender] == true);
// to prevent re-entrancy attack
soldAddresses[msg.sender] = false;
uint saleProceed = safeAdd(minBalanceToSell, sellingPriceInDayOf[msg.sender]);
balances[this] = safeSub(balances[this], saleProceed);
balances[msg.sender] = safeAdd(balances[msg.sender], saleProceed);
Transfer(this, msg.sender, saleProceed);
return true;
}
/** Function that lets a seller get their deposited day tokens (minBalanceToSell) back, if no buyer turns up.
* Allowed only after expiryBlockNumber
* Throws if any other state other than EXPIRED
*/
function refundFailedAuctionAmount() onlyContributor(idOf[msg.sender]) public returns(bool){
uint id = idOf[msg.sender];
if(block.number > contributors[id].expiryBlockNumber && contributors[id].status == sellingStatus.ONSALE)
{
contributors[id].status = sellingStatus.EXPIRED;
}
require(contributors[id].status == sellingStatus.EXPIRED);
// reset selling status
contributors[id].status = sellingStatus.NOTONSALE;
balances[this] = safeSub(balances[this], minBalanceToSell);
// update balance of seller address before refunding
updateBalanceOf(id);
balances[msg.sender] = safeAdd(balances[msg.sender], minBalanceToSell);
contributors[id].minPriceInDay = 0;
contributors[id].expiryBlockNumber = 0;
Transfer(this, msg.sender, minBalanceToSell);
return true;
}
/** Function to add a team address as a contributor and store it's time issued to calculate vesting period
* Called by owner
*/
function addTeamTimeMints(address _adr, uint _id, uint _tokens, bool _isTest) public onlyOwner {
//check if Id is in range of team Ids
require(_id >= firstTeamContributorId && _id < firstTeamContributorId + totalTeamContributorIds);
require(totalTeamContributorIdsAllocated < totalTeamContributorIds);
addContributor(_id, _adr, 0);
totalTeamContributorIdsAllocated++;
// enforce lockin period if not test address
if(!_isTest) teamIssuedTimestamp[_adr] = block.timestamp;
mint(_adr, _tokens);
TeamAddressAdded(_adr, _id);
}
/** Function to add reserved aution TimeMints post-ICO. Only by owner
* @param _receiver Address of the minting to be added
* @param _customerId Server side id of the customer
* @param _id contributorId
*/
function postAllocateAuctionTimeMints(address _receiver, uint _customerId, uint _id) public onlyOwner {
//check if Id is in range of Auction Ids
require(_id >= firstPostIcoContributorId && _id < firstPostIcoContributorId + totalPostIcoContributorIds);
require(totalPostIcoContributorIdsAllocated < totalPostIcoContributorIds);
require(released == true);
addContributor(_id, _receiver, 0);
totalPostIcoContributorIdsAllocated++;
PostInvested(_receiver, 0, 0, _customerId, _id);
}
/** Function to add all contributors except team, test and Auctions TimeMints. Only by owner
* @param _receiver Address of the minting to be added
* @param _customerId Server side id of the customer
* @param _id contributor id
* @param _tokens day tokens to allocate
* @param _weiAmount ether invested in wei
*/
function allocateNormalTimeMints(address _receiver, uint _customerId, uint _id, uint _tokens, uint _weiAmount) public onlyOwner {
// check if Id is in range of Normal Ids
require(_id >= firstContributorId && _id <= totalNormalContributorIds);
require(totalNormalContributorIdsAllocated < totalNormalContributorIds);
addContributor(_id, _receiver, _tokens);
totalNormalContributorIdsAllocated++;
mint(_receiver, _tokens);
Invested(_receiver, _weiAmount, _tokens, _customerId, _id);
}
/** Function to release token
* Called by owner
*/
function releaseToken(uint _initialBlockTimestamp) public onlyOwner {
require(!released); // check not already released
setInitialBlockTimestamp(_initialBlockTimestamp);
// Make token transferable
releaseTokenTransfer();
}
}
| * to check if an address is a valid contributor @param _address contributor address to check./ | function isValidContributorAddress(address _address) constant returns (bool isValidContributor) {
return isValidContributorId(idOf[_address]);
}
| 1,800,528 | [
1,
869,
866,
309,
392,
1758,
353,
279,
923,
31123,
225,
389,
2867,
225,
31123,
1758,
358,
866,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4908,
442,
19293,
1887,
12,
2867,
389,
2867,
13,
5381,
1135,
261,
6430,
4908,
442,
19293,
13,
288,
203,
3639,
327,
4908,
442,
19293,
548,
12,
350,
951,
63,
67,
2867,
19226,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.21;
/*
Owned contract interface
*/
contract IOwned {
// this function isn't abstract since the compiler emits automatically generated getter functions as external
function owner() public view returns (address) {}
function transferOwnership(address _newOwner) public;
function acceptOwnership() public;
}
/*
Bancor Formula interface
*/
contract IBancorFormula {
function calculatePurchaseReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _depositAmount) public view returns (uint256);
function calculateSaleReturn(uint256 _supply, uint256 _connectorBalance, uint32 _connectorWeight, uint256 _sellAmount) public view returns (uint256);
function calculateCrossConnectorReturn(uint256 _fromConnectorBalance, uint32 _fromConnectorWeight, uint256 _toConnectorBalance, uint32 _toConnectorWeight, uint256 _amount) public view returns (uint256);
}
/*
Contract Registry interface
*/
contract IContractRegistry {
function getAddress(bytes32 _contractName) public view returns (address);
}
/*
Contract Features interface
*/
contract IContractFeatures {
function isSupported(address _contract, uint256 _features) public view returns (bool);
function enableFeatures(uint256 _features, bool _enable) public;
}
/*
Whitelist interface
*/
contract IWhitelist {
function isWhitelisted(address _address) public view returns (bool);
}
/*
ERC20 Standard Token interface
*/
contract IERC20Token {
// these functions aren't abstract since the compiler emits automatically generated getter functions as external
function name() public view returns (string) {}
function symbol() public view returns (string) {}
function decimals() public view returns (uint8) {}
function totalSupply() public view returns (uint256) {}
function balanceOf(address _owner) public view returns (uint256) { _owner; }
function allowance(address _owner, address _spender) public view returns (uint256) { _owner; _spender; }
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
}
/*
Smart Token interface
*/
contract ISmartToken is IOwned, IERC20Token {
function disableTransfers(bool _disable) public;
function issue(address _to, uint256 _amount) public;
function destroy(address _from, uint256 _amount) public;
}
/*
Bancor Network interface
*/
contract IBancorNetwork {
function convert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn) public payable returns (uint256);
function convertFor(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for) public payable returns (uint256);
function convertForPrioritized(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s)
public payable returns (uint256);
}
/*
Token Holder interface
*/
contract ITokenHolder is IOwned {
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount) public;
}
/*
Utilities & Common Modifiers
*/
contract Utils {
/**
constructor
*/
function Utils() public {
}
// verifies that an amount is greater than zero
modifier greaterThanZero(uint256 _amount) {
require(_amount > 0);
_;
}
// validates an address - currently only checks that it isn't null
modifier validAddress(address _address) {
require(_address != address(0));
_;
}
// verifies that the address is different than this contract address
modifier notThis(address _address) {
require(_address != address(this));
_;
}
// Overflow protected math functions
/**
@dev returns the sum of _x and _y, asserts if the calculation overflows
@param _x value 1
@param _y value 2
@return sum
*/
function safeAdd(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x + _y;
assert(z >= _x);
return z;
}
/**
@dev returns the difference of _x minus _y, asserts if the subtraction results in a negative number
@param _x minuend
@param _y subtrahend
@return difference
*/
function safeSub(uint256 _x, uint256 _y) internal pure returns (uint256) {
assert(_x >= _y);
return _x - _y;
}
/**
@dev returns the product of multiplying _x by _y, asserts if the calculation overflows
@param _x factor 1
@param _y factor 2
@return product
*/
function safeMul(uint256 _x, uint256 _y) internal pure returns (uint256) {
uint256 z = _x * _y;
assert(_x == 0 || z / _x == _y);
return z;
}
}
/*
Provides support and utilities for contract ownership
*/
contract Owned is IOwned {
address public owner;
address public newOwner;
event OwnerUpdate(address indexed _prevOwner, address indexed _newOwner);
/**
@dev constructor
*/
function Owned() public {
owner = msg.sender;
}
// allows execution by the owner only
modifier ownerOnly {
assert(msg.sender == owner);
_;
}
/**
@dev allows transferring the contract ownership
the new owner still needs to accept the transfer
can only be called by the contract owner
@param _newOwner new contract owner
*/
function transferOwnership(address _newOwner) public ownerOnly {
require(_newOwner != owner);
newOwner = _newOwner;
}
/**
@dev used by a new owner to accept an ownership transfer
*/
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnerUpdate(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/*
Provides support and utilities for contract management
Note that a managed contract must also have an owner
*/
contract Managed is Owned {
address public manager;
address public newManager;
event ManagerUpdate(address indexed _prevManager, address indexed _newManager);
/**
@dev constructor
*/
function Managed() public {
manager = msg.sender;
}
// allows execution by the manager only
modifier managerOnly {
assert(msg.sender == manager);
_;
}
// allows execution by either the owner or the manager only
modifier ownerOrManagerOnly {
require(msg.sender == owner || msg.sender == manager);
_;
}
/**
@dev allows transferring the contract management
the new manager still needs to accept the transfer
can only be called by the contract manager
@param _newManager new contract manager
*/
function transferManagement(address _newManager) public ownerOrManagerOnly {
require(_newManager != manager);
newManager = _newManager;
}
/**
@dev used by a new manager to accept a management transfer
*/
function acceptManagement() public {
require(msg.sender == newManager);
emit ManagerUpdate(manager, newManager);
manager = newManager;
newManager = address(0);
}
}
/**
Id definitions for bancor contracts
Can be used in conjunction with the contract registry to get contract addresses
*/
contract ContractIds {
bytes32 public constant BANCOR_NETWORK = "BancorNetwork";
bytes32 public constant BANCOR_FORMULA = "BancorFormula";
bytes32 public constant CONTRACT_FEATURES = "ContractFeatures";
}
/**
Id definitions for bancor contract features
Can be used to query the ContractFeatures contract to check whether a certain feature is supported by a contract
*/
contract FeatureIds {
// converter features
uint256 public constant CONVERTER_CONVERSION_WHITELIST = 1 << 0;
}
/*
We consider every contract to be a 'token holder' since it's currently not possible
for a contract to deny receiving tokens.
The TokenHolder's contract sole purpose is to provide a safety mechanism that allows
the owner to send tokens that were sent to the contract by mistake back to their sender.
*/
contract TokenHolder is ITokenHolder, Owned, Utils {
/**
@dev constructor
*/
function TokenHolder() public {
}
/**
@dev withdraws tokens held by the contract and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawTokens(IERC20Token _token, address _to, uint256 _amount)
public
ownerOnly
validAddress(_token)
validAddress(_to)
notThis(_to)
{
assert(_token.transfer(_to, _amount));
}
}
/*
The smart token controller is an upgradable part of the smart token that allows
more functionality as well as fixes for bugs/exploits.
Once it accepts ownership of the token, it becomes the token's sole controller
that can execute any of its functions.
To upgrade the controller, ownership must be transferred to a new controller, along with
any relevant data.
The smart token must be set on construction and cannot be changed afterwards.
Wrappers are provided (as opposed to a single 'execute' function) for each of the token's functions, for easier access.
Note that the controller can transfer token ownership to a new controller that
doesn't allow executing any function on the token, for a trustless solution.
Doing that will also remove the owner's ability to upgrade the controller.
*/
contract SmartTokenController is TokenHolder {
ISmartToken public token; // smart token
/**
@dev constructor
*/
function SmartTokenController(ISmartToken _token)
public
validAddress(_token)
{
token = _token;
}
// ensures that the controller is the token's owner
modifier active() {
assert(token.owner() == address(this));
_;
}
// ensures that the controller is not the token's owner
modifier inactive() {
assert(token.owner() != address(this));
_;
}
/**
@dev allows transferring the token ownership
the new owner still need to accept the transfer
can only be called by the contract owner
@param _newOwner new token owner
*/
function transferTokenOwnership(address _newOwner) public ownerOnly {
token.transferOwnership(_newOwner);
}
/**
@dev used by a new owner to accept a token ownership transfer
can only be called by the contract owner
*/
function acceptTokenOwnership() public ownerOnly {
token.acceptOwnership();
}
/**
@dev disables/enables token transfers
can only be called by the contract owner
@param _disable true to disable transfers, false to enable them
*/
function disableTokenTransfers(bool _disable) public ownerOnly {
token.disableTransfers(_disable);
}
/**
@dev withdraws tokens held by the controller and sends them to an account
can only be called by the owner
@param _token ERC20 token contract address
@param _to account to receive the new amount
@param _amount amount to withdraw
*/
function withdrawFromToken(
IERC20Token _token,
address _to,
uint256 _amount
)
public
ownerOnly
{
ITokenHolder(token).withdrawTokens(_token, _to, _amount);
}
}
/*
Bancor Converter interface
*/
contract IBancorConverter {
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256);
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
function conversionWhitelist() public view returns (IWhitelist) {}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256);
}
/*
Bancor Converter v0.9
The Bancor version of the token converter, allows conversion between a smart token and other ERC20 tokens and between different ERC20 tokens and themselves.
ERC20 connector balance can be virtual, meaning that the calculations are based on the virtual balance instead of relying on
the actual connector balance. This is a security mechanism that prevents the need to keep a very large (and valuable) balance in a single contract.
The converter is upgradable (just like any SmartTokenController).
WARNING: It is NOT RECOMMENDED to use the converter with Smart Tokens that have less than 8 decimal digits
or with very small numbers because of precision loss
Open issues:
- Front-running attacks are currently mitigated by the following mechanisms:
- minimum return argument for each conversion provides a way to define a minimum/maximum price for the transaction
- gas price limit prevents users from having control over the order of execution
- gas price limit check can be skipped if the transaction comes from a trusted, whitelisted signer
Other potential solutions might include a commit/reveal based schemes
- Possibly add getters for the connector fields so that the client won't need to rely on the order in the struct
*/
contract BancorConverter is IBancorConverter, SmartTokenController, Managed, ContractIds, FeatureIds {
uint32 private constant MAX_WEIGHT = 1000000;
uint64 private constant MAX_CONVERSION_FEE = 1000000;
struct Connector {
uint256 virtualBalance; // connector virtual balance
uint32 weight; // connector weight, represented in ppm, 1-1000000
bool isVirtualBalanceEnabled; // true if virtual balance is enabled, false if not
bool isPurchaseEnabled; // is purchase of the smart token enabled with the connector, can be set by the owner
bool isSet; // used to tell if the mapping element is defined
}
string public version = '0.9';
string public converterType = 'bancor';
IContractRegistry public registry; // contract registry contract
IWhitelist public conversionWhitelist; // whitelist contract with list of addresses that are allowed to use the converter
IERC20Token[] public connectorTokens; // ERC20 standard token addresses
IERC20Token[] public quickBuyPath; // conversion path that's used in order to buy the token with ETH
mapping (address => Connector) public connectors; // connector token addresses -> connector data
uint32 private totalConnectorWeight = 0; // used to efficiently prevent increasing the total connector weight above 100%
uint32 public maxConversionFee = 0; // maximum conversion fee for the lifetime of the contract,
// represented in ppm, 0...1000000 (0 = no fee, 100 = 0.01%, 1000000 = 100%)
uint32 public conversionFee = 0; // current conversion fee, represented in ppm, 0...maxConversionFee
bool public conversionsEnabled = true; // true if token conversions is enabled, false if not
IERC20Token[] private convertPath;
// triggered when a conversion between two tokens occurs
event Conversion(
address indexed _fromToken,
address indexed _toToken,
address indexed _trader,
uint256 _amount,
uint256 _return,
int256 _conversionFee
);
// triggered after a conversion with new price data
event PriceDataUpdate(
address indexed _connectorToken,
uint256 _tokenSupply,
uint256 _connectorBalance,
uint32 _connectorWeight
);
// triggered when the conversion fee is updated
event ConversionFeeUpdate(uint32 _prevFee, uint32 _newFee);
/**
@dev constructor
@param _token smart token governed by the converter
@param _registry address of a contract registry contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
*/
function BancorConverter(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _connectorToken,
uint32 _connectorWeight
)
public
SmartTokenController(_token)
validAddress(_registry)
validMaxConversionFee(_maxConversionFee)
{
registry = _registry;
IContractFeatures features = IContractFeatures(registry.getAddress(ContractIds.CONTRACT_FEATURES));
// initialize supported features
if (features != address(0))
features.enableFeatures(FeatureIds.CONVERTER_CONVERSION_WHITELIST, true);
maxConversionFee = _maxConversionFee;
if (_connectorToken != address(0))
addConnector(_connectorToken, _connectorWeight, false);
}
// validates a connector token address - verifies that the address belongs to one of the connector tokens
modifier validConnector(IERC20Token _address) {
require(connectors[_address].isSet);
_;
}
// validates a token address - verifies that the address belongs to one of the convertible tokens
modifier validToken(IERC20Token _address) {
require(_address == token || connectors[_address].isSet);
_;
}
// validates maximum conversion fee
modifier validMaxConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= MAX_CONVERSION_FEE);
_;
}
// validates conversion fee
modifier validConversionFee(uint32 _conversionFee) {
require(_conversionFee >= 0 && _conversionFee <= maxConversionFee);
_;
}
// validates connector weight range
modifier validConnectorWeight(uint32 _weight) {
require(_weight > 0 && _weight <= MAX_WEIGHT);
_;
}
// validates a conversion path - verifies that the number of elements is odd and that maximum number of 'hops' is 10
modifier validConversionPath(IERC20Token[] _path) {
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
_;
}
// allows execution only when conversions aren't disabled
modifier conversionsAllowed {
assert(conversionsEnabled);
_;
}
// allows execution by the BancorNetwork contract only
modifier bancorNetworkOnly {
IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK));
require(msg.sender == address(bancorNetwork));
_;
}
/**
@dev returns the number of connector tokens defined
@return number of connector tokens
*/
function connectorTokenCount() public view returns (uint16) {
return uint16(connectorTokens.length);
}
/*
@dev allows the owner to update the registry contract address
@param _registry address of a bancor converter registry contract
*/
function setRegistry(IContractRegistry _registry)
public
ownerOnly
validAddress(_registry)
notThis(_registry)
{
registry = _registry;
}
/*
@dev allows the owner to update & enable the conversion whitelist contract address
when set, only addresses that are whitelisted are actually allowed to use the converter
note that the whitelist check is actually done by the BancorNetwork contract
@param _whitelist address of a whitelist contract
*/
function setConversionWhitelist(IWhitelist _whitelist)
public
ownerOnly
notThis(_whitelist)
{
conversionWhitelist = _whitelist;
}
/*
@dev allows the manager to update the quick buy path
@param _path new quick buy path, see conversion path format in the bancorNetwork contract
*/
function setQuickBuyPath(IERC20Token[] _path)
public
ownerOnly
validConversionPath(_path)
{
quickBuyPath = _path;
}
/*
@dev allows the manager to clear the quick buy path
*/
function clearQuickBuyPath() public ownerOnly {
quickBuyPath.length = 0;
}
/**
@dev returns the length of the quick buy path array
@return quick buy path length
*/
function getQuickBuyPathLength() public view returns (uint256) {
return quickBuyPath.length;
}
/**
@dev disables the entire conversion functionality
this is a safety mechanism in case of a emergency
can only be called by the manager
@param _disable true to disable conversions, false to re-enable them
*/
function disableConversions(bool _disable) public ownerOrManagerOnly {
conversionsEnabled = !_disable;
}
/**
@dev updates the current conversion fee
can only be called by the manager
@param _conversionFee new conversion fee, represented in ppm
*/
function setConversionFee(uint32 _conversionFee)
public
ownerOrManagerOnly
validConversionFee(_conversionFee)
{
emit ConversionFeeUpdate(conversionFee, _conversionFee);
conversionFee = _conversionFee;
}
/*
@dev given a return amount, returns the amount minus the conversion fee
@param _amount return amount
@param _magnitude 1 for standard conversion, 2 for cross connector conversion
@return return amount minus conversion fee
*/
function getFinalAmount(uint256 _amount, uint8 _magnitude) public view returns (uint256) {
return safeMul(_amount, (MAX_CONVERSION_FEE - conversionFee) ** _magnitude) / MAX_CONVERSION_FEE ** _magnitude;
}
/**
@dev defines a new connector for the token
can only be called by the owner while the converter is inactive
@param _token address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
*/
function addConnector(IERC20Token _token, uint32 _weight, bool _enableVirtualBalance)
public
ownerOnly
inactive
validAddress(_token)
notThis(_token)
validConnectorWeight(_weight)
{
require(_token != token && !connectors[_token].isSet && totalConnectorWeight + _weight <= MAX_WEIGHT); // validate input
connectors[_token].virtualBalance = 0;
connectors[_token].weight = _weight;
connectors[_token].isVirtualBalanceEnabled = _enableVirtualBalance;
connectors[_token].isPurchaseEnabled = true;
connectors[_token].isSet = true;
connectorTokens.push(_token);
totalConnectorWeight += _weight;
}
/**
@dev updates one of the token connectors
can only be called by the owner
@param _connectorToken address of the connector token
@param _weight constant connector weight, represented in ppm, 1-1000000
@param _enableVirtualBalance true to enable virtual balance for the connector, false to disable it
@param _virtualBalance new connector's virtual balance
*/
function updateConnector(IERC20Token _connectorToken, uint32 _weight, bool _enableVirtualBalance, uint256 _virtualBalance)
public
ownerOnly
validConnector(_connectorToken)
validConnectorWeight(_weight)
{
Connector storage connector = connectors[_connectorToken];
require(totalConnectorWeight - connector.weight + _weight <= MAX_WEIGHT); // validate input
totalConnectorWeight = totalConnectorWeight - connector.weight + _weight;
connector.weight = _weight;
connector.isVirtualBalanceEnabled = _enableVirtualBalance;
connector.virtualBalance = _virtualBalance;
}
/**
@dev disables purchasing with the given connector token in case the connector token got compromised
can only be called by the owner
note that selling is still enabled regardless of this flag and it cannot be disabled by the owner
@param _connectorToken connector token contract address
@param _disable true to disable the token, false to re-enable it
*/
function disableConnectorPurchases(IERC20Token _connectorToken, bool _disable)
public
ownerOnly
validConnector(_connectorToken)
{
connectors[_connectorToken].isPurchaseEnabled = !_disable;
}
/**
@dev returns the connector's virtual balance if one is defined, otherwise returns the actual balance
@param _connectorToken connector token contract address
@return connector balance
*/
function getConnectorBalance(IERC20Token _connectorToken)
public
view
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
return connector.isVirtualBalanceEnabled ? connector.virtualBalance : _connectorToken.balanceOf(this);
}
/**
@dev returns the expected return for converting a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@return expected conversion return amount
*/
function getReturn(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount) public view returns (uint256) {
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return getPurchaseReturn(_fromToken, _amount);
else if (_fromToken == token)
return getSaleReturn(_toToken, _amount);
// conversion between 2 connectors
return getCrossConnectorReturn(_fromToken, _toToken, _amount);
}
/**
@dev returns the expected return for buying the token for a connector token
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@return expected purchase return amount
*/
function getPurchaseReturn(IERC20Token _connectorToken, uint256 _depositAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
require(connector.isPurchaseEnabled); // validate input
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculatePurchaseReturn(tokenSupply, connectorBalance, connector.weight, _depositAmount);
// return the amount minus the conversion fee
return getFinalAmount(amount, 1);
}
/**
@dev returns the expected return for selling the token for one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@return expected sale return amount
*/
function getSaleReturn(IERC20Token _connectorToken, uint256 _sellAmount)
public
view
active
validConnector(_connectorToken)
returns (uint256)
{
Connector storage connector = connectors[_connectorToken];
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculateSaleReturn(tokenSupply, connectorBalance, connector.weight, _sellAmount);
// return the amount minus the conversion fee
return getFinalAmount(amount, 1);
}
/**
@dev returns the expected return for selling one of the connector tokens for another connector token
@param _fromConnectorToken contract address of the connector token to convert from
@param _toConnectorToken contract address of the connector token to convert to
@param _sellAmount amount to sell (in the from connector token)
@return expected sale return amount (in the to connector token)
*/
function getCrossConnectorReturn(IERC20Token _fromConnectorToken, IERC20Token _toConnectorToken, uint256 _sellAmount)
public
view
active
validConnector(_fromConnectorToken)
validConnector(_toConnectorToken)
returns (uint256)
{
Connector storage fromConnector = connectors[_fromConnectorToken];
Connector storage toConnector = connectors[_toConnectorToken];
require(toConnector.isPurchaseEnabled); // validate input
uint256 fromConnectorBalance = getConnectorBalance(_fromConnectorToken);
uint256 toConnectorBalance = getConnectorBalance(_toConnectorToken);
IBancorFormula formula = IBancorFormula(registry.getAddress(ContractIds.BANCOR_FORMULA));
uint256 amount = formula.calculateCrossConnectorReturn(fromConnectorBalance, fromConnector.weight, toConnectorBalance, toConnector.weight, _sellAmount);
// return the amount minus the conversion fee
// the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token)
return getFinalAmount(amount, 2);
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convertInternal(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn)
public
bancorNetworkOnly
conversionsAllowed
greaterThanZero(_minReturn)
returns (uint256)
{
require(_fromToken != _toToken); // validate input
// conversion between the token and one of its connectors
if (_toToken == token)
return buy(_fromToken, _amount, _minReturn);
else if (_fromToken == token)
return sell(_toToken, _amount, _minReturn);
// conversion between 2 connectors
uint256 amount = getCrossConnectorReturn(_fromToken, _toToken, _amount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
// update the source token virtual balance if relevant
Connector storage fromConnector = connectors[_fromToken];
if (fromConnector.isVirtualBalanceEnabled)
fromConnector.virtualBalance = safeAdd(fromConnector.virtualBalance, _amount);
// update the target token virtual balance if relevant
Connector storage toConnector = connectors[_toToken];
if (toConnector.isVirtualBalanceEnabled)
toConnector.virtualBalance = safeSub(toConnector.virtualBalance, amount);
// ensure that the trade won't deplete the connector balance
uint256 toConnectorBalance = getConnectorBalance(_toToken);
assert(amount < toConnectorBalance);
// transfer funds from the caller in the from connector token
assert(_fromToken.transferFrom(msg.sender, this, _amount));
// transfer funds to the caller in the to connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_toToken.transfer(msg.sender, amount));
// calculate conversion fee and dispatch the conversion event
// the fee is higher (magnitude = 2) since cross connector conversion equals 2 conversions (from / to the smart token)
uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 2));
dispatchConversionEvent(_fromToken, _toToken, _amount, amount, feeAmount);
// dispatch price data updates for the smart token / both connectors
emit PriceDataUpdate(_fromToken, token.totalSupply(), getConnectorBalance(_fromToken), fromConnector.weight);
emit PriceDataUpdate(_toToken, token.totalSupply(), getConnectorBalance(_toToken), toConnector.weight);
return amount;
}
/**
@dev converts a specific amount of _fromToken to _toToken
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount to convert, in fromToken
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return conversion return amount
*/
function convert(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
convertPath = [_fromToken, token, _toToken];
return quickConvert(convertPath, _amount, _minReturn);
}
/**
@dev buys the token by depositing one of its connector tokens
@param _connectorToken connector token contract address
@param _depositAmount amount to deposit (in the connector token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return buy return amount
*/
function buy(IERC20Token _connectorToken, uint256 _depositAmount, uint256 _minReturn) internal returns (uint256) {
uint256 amount = getPurchaseReturn(_connectorToken, _depositAmount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeAdd(connector.virtualBalance, _depositAmount);
// transfer funds from the caller in the connector token
assert(_connectorToken.transferFrom(msg.sender, this, _depositAmount));
// issue new funds to the caller in the smart token
token.issue(msg.sender, amount);
// calculate conversion fee and dispatch the conversion event
uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1));
dispatchConversionEvent(_connectorToken, token, _depositAmount, amount, feeAmount);
// dispatch price data update for the smart token/connector
emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);
return amount;
}
/**
@dev sells the token by withdrawing from one of its connector tokens
@param _connectorToken connector token contract address
@param _sellAmount amount to sell (in the smart token)
@param _minReturn if the conversion results in an amount smaller the minimum return - it is cancelled, must be nonzero
@return sell return amount
*/
function sell(IERC20Token _connectorToken, uint256 _sellAmount, uint256 _minReturn) internal returns (uint256) {
require(_sellAmount <= token.balanceOf(msg.sender)); // validate input
uint256 amount = getSaleReturn(_connectorToken, _sellAmount);
// ensure the trade gives something in return and meets the minimum requested amount
require(amount != 0 && amount >= _minReturn);
// ensure that the trade will only deplete the connector balance if the total supply is depleted as well
uint256 tokenSupply = token.totalSupply();
uint256 connectorBalance = getConnectorBalance(_connectorToken);
assert(amount < connectorBalance || (amount == connectorBalance && _sellAmount == tokenSupply));
// update virtual balance if relevant
Connector storage connector = connectors[_connectorToken];
if (connector.isVirtualBalanceEnabled)
connector.virtualBalance = safeSub(connector.virtualBalance, amount);
// destroy _sellAmount from the caller's balance in the smart token
token.destroy(msg.sender, _sellAmount);
// transfer funds to the caller in the connector token
// the transfer might fail if the actual connector balance is smaller than the virtual balance
assert(_connectorToken.transfer(msg.sender, amount));
// calculate conversion fee and dispatch the conversion event
uint256 feeAmount = safeSub(amount, getFinalAmount(amount, 1));
dispatchConversionEvent(token, _connectorToken, _sellAmount, amount, feeAmount);
// dispatch price data update for the smart token/connector
emit PriceDataUpdate(_connectorToken, token.totalSupply(), getConnectorBalance(_connectorToken), connector.weight);
return amount;
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorNetwork contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@return tokens issued in return
*/
function quickConvert(IERC20Token[] _path, uint256 _amount, uint256 _minReturn)
public
payable
validConversionPath(_path)
returns (uint256)
{
return quickConvertPrioritized(_path, _amount, _minReturn, 0x0, 0x0, 0x0, 0x0);
}
/**
@dev converts the token to any other token in the bancor network by following a predefined conversion path
note that when converting from an ERC20 token (as opposed to a smart token), allowance must be set beforehand
@param _path conversion path, see conversion path format in the BancorNetwork contract
@param _amount amount to convert from (in the initial source token)
@param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
@param _block if the current block exceeded the given parameter - it is cancelled
@param _v (signature[128:130]) associated with the signer address and helps validating if the signature is legit
@param _r (signature[0:64]) associated with the signer address and helps validating if the signature is legit
@param _s (signature[64:128]) associated with the signer address and helps validating if the signature is legit
@return tokens issued in return
*/
function quickConvertPrioritized(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, uint256 _block, uint8 _v, bytes32 _r, bytes32 _s)
public
payable
validConversionPath(_path)
returns (uint256)
{
IERC20Token fromToken = _path[0];
IBancorNetwork bancorNetwork = IBancorNetwork(registry.getAddress(ContractIds.BANCOR_NETWORK));
// we need to transfer the source tokens from the caller to the BancorNetwork contract,
// so it can execute the conversion on behalf of the caller
if (msg.value == 0) {
// not ETH, send the source tokens to the BancorNetwork contract
// if the token is the smart token, no allowance is required - destroy the tokens
// from the caller and issue them to the BancorNetwork contract
if (fromToken == token) {
token.destroy(msg.sender, _amount); // destroy _amount tokens from the caller's balance in the smart token
token.issue(bancorNetwork, _amount); // issue _amount new tokens to the BancorNetwork contract
} else {
// otherwise, we assume we already have allowance, transfer the tokens directly to the BancorNetwork contract
assert(fromToken.transferFrom(msg.sender, bancorNetwork, _amount));
}
}
// execute the conversion and pass on the ETH with the call
return bancorNetwork.convertForPrioritized.value(msg.value)(_path, _amount, _minReturn, msg.sender, _block, _v, _r, _s);
}
// deprecated, backward compatibility
function change(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _minReturn) public returns (uint256) {
return convertInternal(_fromToken, _toToken, _amount, _minReturn);
}
/**
@dev helper, dispatches the Conversion event
@param _fromToken ERC20 token to convert from
@param _toToken ERC20 token to convert to
@param _amount amount purchased/sold (in the source token)
@param _returnAmount amount returned (in the target token)
*/
function dispatchConversionEvent(IERC20Token _fromToken, IERC20Token _toToken, uint256 _amount, uint256 _returnAmount, uint256 _feeAmount) private {
// fee amount is converted to 255 bits -
// negative amount means the fee is taken from the source token, positive amount means its taken from the target token
// currently the fee is always taken from the target token
// since we convert it to a signed number, we first ensure that it's capped at 255 bits to prevent overflow
assert(_feeAmount <= 2 ** 255);
emit Conversion(_fromToken, _toToken, msg.sender, _amount, _returnAmount, int256(_feeAmount));
}
/**
@dev fallback, buys the smart token with ETH
note that the purchase will use the price at the time of the purchase
*/
function() payable public {
quickConvert(quickBuyPath, msg.value, 1);
}
}
/*
Bancor Converter Factory interface
*/
contract IBancorConverterFactory {
function createConverter(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _connectorToken,
uint32 _connectorWeight
)
public returns (address);
}
/*
Bancor Converter Factory
*/
contract BancorConverterFactory is IBancorConverterFactory {
// triggered when a new converter is created
event NewConverter(address indexed _converter, address indexed _owner);
/**
@dev constructor
*/
function BancorConverterFactory() public {
}
/**
@dev creates a new converter with the given arguments and transfers
the ownership and management to the sender.
@param _token smart token governed by the converter
@param _registry address of a contract registry contract
@param _maxConversionFee maximum conversion fee, represented in ppm
@param _connectorToken optional, initial connector, allows defining the first connector at deployment time
@param _connectorWeight optional, weight for the initial connector
@return a new converter
*/
function createConverter(
ISmartToken _token,
IContractRegistry _registry,
uint32 _maxConversionFee,
IERC20Token _connectorToken,
uint32 _connectorWeight
) public returns(address converterAddress) {
BancorConverter converter = new BancorConverter(
_token,
_registry,
_maxConversionFee,
_connectorToken,
_connectorWeight
);
converter.transferOwnership(msg.sender);
converter.transferManagement(msg.sender);
address _converterAddress = address(converter);
emit NewConverter(_converterAddress, msg.sender);
return _converterAddress;
}
} | used to tell if the mapping element is defined
| bool isSet; | 14,542 | [
1,
3668,
358,
9276,
309,
326,
2874,
930,
353,
2553,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1426,
13532,
31,
8227,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.13;
contract IAllocation {
function addShare(address _beneficiary, uint256 _proportion, uint256 _percenForFirstPart) external;
}
contract IRightAndRoles {
address[][] public wallets;
mapping(address => uint16) public roles;
event WalletChanged(address indexed newWallet, address indexed oldWallet, uint8 indexed role);
event CloneChanged(address indexed wallet, uint8 indexed role, bool indexed mod);
function changeWallet(address _wallet, uint8 _role) external;
function setManagerPowerful(bool _mode) external;
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool);
}
contract RightAndRoles is IRightAndRoles {
bool managerPowerful = true;
function RightAndRoles(address[] _roles) public {
uint8 len = uint8(_roles.length);
require(len > 0&&len <16);
wallets.length = len;
for(uint8 i = 0; i < len; i++){
wallets[i].push(_roles[i]);
roles[_roles[i]] += uint16(2)**i;
emit WalletChanged(_roles[i], address(0),i);
}
}
function changeClons(address _clon, uint8 _role, bool _mod) external {
require(wallets[_role][0] == msg.sender&&_clon != msg.sender);
emit CloneChanged(_clon,_role,_mod);
uint16 roleMask = uint16(2)**_role;
if(_mod){
require(roles[_clon]&roleMask == 0);
wallets[_role].push(_clon);
}else{
address[] storage tmp = wallets[_role];
uint8 i = 1;
for(i; i < tmp.length; i++){
if(tmp[i] == _clon) break;
}
require(i > tmp.length);
tmp[i] = tmp[tmp.length];
delete tmp[tmp.length];
}
roles[_clon] = _mod?roles[_clon]|roleMask:roles[_clon]&~roleMask;
}
// Change the address for the specified role.
// Available to any wallet owner except the observer.
// Available to the manager until the round is initialized.
// The Observer's wallet or his own manager can change at any time.
// @ Do I have to use the function no
// @ When it is possible to call depend...
// @ When it is launched automatically -
// @ Who can call the function staff (all 7+ roles)
function changeWallet(address _wallet, uint8 _role) external {
require(wallets[_role][0] == msg.sender || wallets[0][0] == msg.sender || (wallets[1][0] == msg.sender && managerPowerful));
emit WalletChanged(wallets[_role][0],_wallet,_role);
uint16 roleMask = uint16(2)**_role;
address[] storage tmp = wallets[_role];
for(uint8 i = 0; i < tmp.length; i++){
roles[tmp[i]] = roles[tmp[i]]&~roleMask;
}
delete wallets[_role];
tmp.push(_wallet);
roles[_wallet] = roles[_wallet]|roleMask;
}
function setManagerPowerful(bool _mode) external {
require(wallets[0][0] == msg.sender);
managerPowerful = _mode;
}
function onlyRoles(address _sender, uint16 _roleMask) view external returns(bool) {
return roles[_sender]&_roleMask != 0;
}
function getMainWallets() view external returns(address[]){
address[] memory _wallets = new address[](wallets.length);
for(uint8 i = 0; i<wallets.length; i++){
_wallets[i] = wallets[i][0];
}
return _wallets;
}
function getCloneWallets(uint8 _role) view external returns(address[]){
return wallets[_role];
}
}
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
contract ICreator{
IRightAndRoles public rightAndRoles;
function createAllocation(IToken _token, uint256 _unlockPart1, uint256 _unlockPart2) external returns (IAllocation);
function createFinancialStrategy() external returns(IFinancialStrategy);
function getRightAndRoles() external returns(IRightAndRoles);
}
contract MigrationAgent
{
function migrateFrom(address _from, uint256 _value) public;
}
contract IFinancialStrategy{
enum State { Active, Refunding, Closed }
State public state = State.Active;
event Deposited(address indexed beneficiary, uint256 weiAmount);
event Receive(address indexed beneficiary, uint256 weiAmount);
event Refunded(address indexed beneficiary, uint256 weiAmount);
event Started();
event Closed();
event RefundsEnabled();
function freeCash() view public returns(uint256);
function deposit(address _beneficiary) external payable;
function refund(address _investor) external;
function setup(uint8 _state, bytes32[] _params) external;
function getBeneficiaryCash() external;
function getPartnerCash(uint8 _user, address _msgsender) external;
}
contract Creator is ICreator{
function Creator() public{
address[] memory tmp = new address[](8);
//Crowdsale.
tmp[0] = address(this);
//manager
tmp[1] = msg.sender;
//beneficiary
tmp[2] = 0x07544edde0542857277188598606B32F2C28062F;
// Accountant
// Receives all the tokens for non-ETH investors (when finalizing Round1 & Round2)
tmp[3] = 0x8a91aC199440Da0B45B2E278f3fE616b1bCcC494;
// Observer
// Has only the right to call paymentsInOtherCurrency (please read the document)
tmp[4] = 0x8a91aC199440Da0B45B2E278f3fE616b1bCcC494;
// Bounty - 2% tokens
tmp[5] = 0x17194d2cA481d2533A147776BeB471DC40dc4580;
// Company - 10% tokens
tmp[6] = 0xb4D429B3240616FA67D1509c0C0E48D11900dd18;
// Team - 11% tokens, freeze 1 year
tmp[7] = 0x443f4Be0f50f973e3970343c6A50bcf1Ac66c6C3;
rightAndRoles = new RightAndRoles(tmp);
}
function createAllocation(IToken _token, uint256 _unlockPart1, uint256 _unlockPart2) external returns (IAllocation) {
Allocation allocation = new Allocation(rightAndRoles,ERC20Basic(_token),_unlockPart1,_unlockPart2);
return allocation;
}
function createFinancialStrategy() external returns(IFinancialStrategy) {
return new FinancialStrategy(rightAndRoles);
}
function getRightAndRoles() external returns(IRightAndRoles){
rightAndRoles.changeWallet(msg.sender,0);
return rightAndRoles;
}
}
contract GuidedByRoles {
IRightAndRoles public rightAndRoles;
function GuidedByRoles(IRightAndRoles _rightAndRoles) public {
rightAndRoles = _rightAndRoles;
}
}
contract MigratableToken is BasicToken,GuidedByRoles {
uint256 public totalMigrated;
address public migrationAgent;
event Migrate(address indexed _from, address indexed _to, uint256 _value);
function setMigrationAgent(address _migrationAgent) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(totalMigrated == 0);
migrationAgent = _migrationAgent;
}
function migrateInternal(address _holder) internal{
require(migrationAgent != 0x0);
uint256 value = balances[_holder];
balances[_holder] = 0;
totalSupply_ = totalSupply_.sub(value);
totalMigrated = totalMigrated.add(value);
MigrationAgent(migrationAgent).migrateFrom(_holder, value);
emit Migrate(_holder,migrationAgent,value);
}
function migrateAll(address[] _holders) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
for(uint i = 0; i < _holders.length; i++){
migrateInternal(_holders[i]);
}
}
// Reissue your tokens.
function migrate() public
{
require(balances[msg.sender] > 0);
migrateInternal(msg.sender);
}
}
contract Pausable is GuidedByRoles {
mapping (address => bool) public unpausedWallet;
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused(address _to) {
require(!paused||unpausedWallet[msg.sender]||unpausedWallet[_to]);
_;
}
function onlyAdmin() internal view {
require(rightAndRoles.onlyRoles(msg.sender,3));
}
// Add a wallet ignoring the "Exchange pause". Available to the owner of the contract.
function setUnpausedWallet(address _wallet, bool mode) public {
onlyAdmin();
unpausedWallet[_wallet] = mode;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function setPause(bool mode) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
if (!paused && mode) {
paused = true;
emit Pause();
}else
if (paused && !mode) {
paused = false;
emit Unpause();
}
}
}
contract FinancialStrategy is IFinancialStrategy, GuidedByRoles{
using SafeMath for uint256;
uint8 public step;
mapping (uint8 => mapping (address => uint256)) public deposited;
// Partner 0 Partner 1 Partner 2
uint256[0] public percent;
uint256[0] public cap; // QUINTILLIONS
uint256[0] public debt;
uint256[0] public total; // QUINTILLIONS
uint256[0] public took;
uint256[0] public ready;
address[0] public wallets;
uint256 public benTook=0;
uint256 public benReady=0;
uint256 public newCash=0;
uint256 public cashHistory=0;
address public benWallet=0;
modifier canGetCash(){
require(state == State.Closed);
_;
}
function FinancialStrategy(IRightAndRoles _rightAndRoles) GuidedByRoles(_rightAndRoles) public {
emit Started();
}
function balance() external view returns(uint256){
return address(this).balance;
}
function deposit(address _investor) external payable {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(state == State.Active);
deposited[step][_investor] = deposited[step][_investor].add(msg.value);
newCash = newCash.add(msg.value);
cashHistory += msg.value;
emit Deposited(_investor,msg.value);
}
// 0 - destruct
// 1 - close
// 2 - restart
// 3 - refund
// 4 - calc
// 5 - update Exchange
function setup(uint8 _state, bytes32[] _params) external {
require(rightAndRoles.onlyRoles(msg.sender,1));
if (_state == 0) {
require(_params.length == 1);
// call from Crowdsale.distructVault(true) for exit
// arg1 - nothing
// arg2 - nothing
selfdestruct(address(_params[0]));
}
else if (_state == 1 ) {
require(_params.length == 0);
// Call from Crowdsale.finalization()
// [1] - successfull round (goalReach)
// [3] - failed round (not enough money)
// arg1 = weiTotalRaised();
// arg2 = nothing;
require(state == State.Active);
//internalCalc(_arg1);
state = State.Closed;
emit Closed();
}
else if (_state == 2) {
require(_params.length == 0);
// Call from Crowdsale.initialization()
// arg1 = weiTotalRaised();
// arg2 = nothing;
require(state == State.Closed);
require(address(this).balance == 0);
state = State.Active;
step++;
emit Started();
}
else if (_state == 3 ) {
require(_params.length == 0);
require(state == State.Active);
state = State.Refunding;
emit RefundsEnabled();
}
else if (_state == 4) {
require(_params.length == 2);
//onlyPartnersOrAdmin(address(_params[1]));
internalCalc(uint256(_params[0]));
}
else if (_state == 5) {
// arg1 = old ETH/USD (exchange)
// arg2 = new ETH/USD (_ETHUSD)
require(_params.length == 2);
for (uint8 user=0; user<cap.length; user++) cap[user]=cap[user].mul(uint256(_params[0])).div(uint256(_params[1]));
}
}
function freeCash() view public returns(uint256){
return newCash+benReady;
}
function internalCalc(uint256 _allValue) internal {
uint256 free=newCash+benReady;
uint256 common=0;
uint256 prcSum=0;
uint256 plan=0;
uint8[] memory indexes = new uint8[](percent.length);
uint8 count = 0;
if (free==0) return;
uint8 i;
for (i =0; i <percent.length; i++) {
plan=_allValue*percent[i]/100;
if(cap[i] != 0 && plan > cap[i]) plan = cap[i];
if (total[i] >= plan) {
debt[i]=0;
continue;
}
plan -= total[i];
debt[i] = plan;
common += plan;
indexes[count++] = i;
prcSum += percent[i];
}
if(common > free){
benReady = 0;
uint8 j = 0;
while (j < count){
i = indexes[j++];
plan = free*percent[i]/prcSum;
if(plan + total[i] <= cap[i] || cap[i] ==0){
debt[i] = plan;
continue;
}
debt[i] = cap[i] - total[i]; //'total' is always less than 'cap'
free -= debt[i];
prcSum -= percent[i];
indexes[j-1] = indexes[--count];
j = 0;
}
}
common = 0;
for(i = 0; i < debt.length; i++){
total[i] += debt[i];
ready[i] += debt[i];
common += ready[i];
}
benReady = address(this).balance - common;
newCash = 0;
}
function refund(address _investor) external {
require(state == State.Refunding);
uint256 depositedValue = deposited[step][_investor];
require(depositedValue > 0);
deposited[step][_investor] = 0;
_investor.transfer(depositedValue);
emit Refunded(_investor, depositedValue);
}
// Call from Crowdsale:
function getBeneficiaryCash() external canGetCash {
require(rightAndRoles.onlyRoles(msg.sender,1));
address _beneficiary = rightAndRoles.wallets(2,0);
uint256 move=benReady;
benWallet=_beneficiary;
if (move == 0) return;
emit Receive(_beneficiary, move);
benReady = 0;
benTook += move;
_beneficiary.transfer(move);
}
// Call from Crowdsale:
function getPartnerCash(uint8 _user, address _msgsender) external canGetCash {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(_user<wallets.length);
onlyPartnersOrAdmin(_msgsender);
uint256 move=ready[_user];
if (move==0) return;
emit Receive(wallets[_user], move);
ready[_user]=0;
took[_user]+=move;
wallets[_user].transfer(move);
}
function onlyPartnersOrAdmin(address _sender) internal view {
if (!rightAndRoles.onlyRoles(_sender,65535)) {
for (uint8 i=0; i<wallets.length; i++) {
if (wallets[i]==_sender) break;
}
if (i>=wallets.length) {
revert();
}
}
}
}
contract IToken{
function setUnpausedWallet(address _wallet, bool mode) public;
function mint(address _to, uint256 _amount) public returns (bool);
function totalSupply() public view returns (uint256);
function setPause(bool mode) public;
function setMigrationAgent(address _migrationAgent) public;
function migrateAll(address[] _holders) public;
function burn(address _beneficiary, uint256 _value) public;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount);
function defrostDate(address _beneficiary) public view returns (uint256 Date);
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public;
}
contract BurnableToken is BasicToken, GuidedByRoles {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(address _beneficiary, uint256 _value) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
require(_value <= balances[_beneficiary]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_beneficiary] = balances[_beneficiary].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_beneficiary, _value);
emit Transfer(_beneficiary, address(0), _value);
}
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function minus(uint256 a, uint256 b) internal pure returns (uint256) {
if (b>=a) return 0;
return a - b;
}
}
contract Allocation is GuidedByRoles, IAllocation {
using SafeMath for uint256;
struct Share {
uint256 proportion;
uint256 forPart;
}
// How many days to freeze from the moment of finalizing ICO
uint256 public unlockPart1;
uint256 public unlockPart2;
uint256 public totalShare;
mapping(address => Share) public shares;
ERC20Basic public token;
// The contract takes the ERC20 coin address from which this contract will work and from the
// owner (Team wallet) who owns the funds.
function Allocation(IRightAndRoles _rightAndRoles,ERC20Basic _token, uint256 _unlockPart1, uint256 _unlockPart2) GuidedByRoles(_rightAndRoles) public{
unlockPart1 = _unlockPart1;
unlockPart2 = _unlockPart2;
token = _token;
}
function addShare(address _beneficiary, uint256 _proportion, uint256 _percenForFirstPart) external {
require(rightAndRoles.onlyRoles(msg.sender,1));
shares[_beneficiary] = Share(shares[_beneficiary].proportion.add(_proportion),_percenForFirstPart);
totalShare = totalShare.add(_proportion);
}
// function unlock() external {
// unlockFor(msg.sender);
// }
// If the time of freezing expired will return the funds to the owner.
function unlockFor(address _owner) public {
require(now >= unlockPart1);
uint256 share = shares[_owner].proportion;
if (now < unlockPart2) {
share = share.mul(shares[_owner].forPart)/100;
shares[_owner].forPart = 0;
}
if (share > 0) {
uint256 unlockedToken = token.balanceOf(this).mul(share).div(totalShare);
shares[_owner].proportion = shares[_owner].proportion.sub(share);
totalShare = totalShare.sub(share);
token.transfer(_owner,unlockedToken);
}
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused(_to) returns (bool) {
return super.transferFrom(_from, _to, _value);
}
}
contract FreezingToken is PausableToken {
struct freeze {
uint256 amount;
uint256 when;
}
mapping (address => freeze) freezedTokens;
function freezedTokenOf(address _beneficiary) public view returns (uint256 amount){
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.amount;
}
function defrostDate(address _beneficiary) public view returns (uint256 Date) {
freeze storage _freeze = freezedTokens[_beneficiary];
if(_freeze.when < now) return 0;
return _freeze.when;
}
function freezeTokens(address _beneficiary, uint256 _amount, uint256 _when) public {
require(rightAndRoles.onlyRoles(msg.sender,1));
freeze storage _freeze = freezedTokens[_beneficiary];
_freeze.amount = _amount;
_freeze.when = _when;
}
function masFreezedTokens(address[] _beneficiary, uint256[] _amount, uint256[] _when) public {
onlyAdmin();
require(_beneficiary.length == _amount.length && _beneficiary.length == _when.length);
for(uint16 i = 0; i < _beneficiary.length; i++){
freeze storage _freeze = freezedTokens[_beneficiary[i]];
_freeze.amount = _amount[i];
_freeze.when = _when[i];
}
}
function transferAndFreeze(address _to, uint256 _value, uint256 _when) external {
require(unpausedWallet[msg.sender]);
require(freezedTokenOf(_to) == 0);
if(_when > 0){
freeze storage _freeze = freezedTokens[_to];
_freeze.amount = _value;
_freeze.when = _when;
}
transfer(_to,_value);
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(balanceOf(msg.sender) >= freezedTokenOf(msg.sender).add(_value));
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(balanceOf(_from) >= freezedTokenOf(_from).add(_value));
return super.transferFrom( _from,_to,_value);
}
}
contract MintableToken is StandardToken, GuidedByRoles {
event Mint(address indexed to, uint256 amount);
event MintFinished();
/**
* @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 returns (bool) {
require(rightAndRoles.onlyRoles(msg.sender,1));
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
}
contract Token is IToken, FreezingToken, MintableToken, MigratableToken, BurnableToken{
function Token(ICreator _creator) GuidedByRoles(_creator.rightAndRoles()) public {}
string public constant name = "Imigize";
string public constant symbol = "IMGZ";
uint8 public constant decimals = 18;
} | Change the address for the specified role. Available to any wallet owner except the observer. Available to the manager until the round is initialized. The Observer's wallet or his own manager can change at any time. @ Do I have to use the function no @ When it is possible to call depend... @ When it is launched automatically - @ Who can call the function staff (all 7+ roles) | function changeWallet(address _wallet, uint8 _role) external {
require(wallets[_role][0] == msg.sender || wallets[0][0] == msg.sender || (wallets[1][0] == msg.sender && managerPowerful));
emit WalletChanged(wallets[_role][0],_wallet,_role);
uint16 roleMask = uint16(2)**_role;
address[] storage tmp = wallets[_role];
for(uint8 i = 0; i < tmp.length; i++){
roles[tmp[i]] = roles[tmp[i]]&~roleMask;
}
delete wallets[_role];
tmp.push(_wallet);
roles[_wallet] = roles[_wallet]|roleMask;
}
| 1,611,124 | [
1,
3043,
326,
1758,
364,
326,
1269,
2478,
18,
15633,
358,
1281,
9230,
3410,
1335,
326,
9655,
18,
15633,
358,
326,
3301,
3180,
326,
3643,
353,
6454,
18,
1021,
23290,
1807,
9230,
578,
18423,
4953,
3301,
848,
2549,
622,
1281,
813,
18,
632,
2256,
467,
1240,
358,
999,
326,
445,
1377,
1158,
632,
5203,
518,
353,
3323,
358,
745,
3639,
2447,
2777,
632,
5203,
518,
353,
28786,
6635,
225,
300,
632,
3497,
83,
848,
745,
326,
445,
1850,
28904,
261,
454,
2371,
15,
4900,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2549,
16936,
12,
2867,
389,
19177,
16,
2254,
28,
389,
4615,
13,
3903,
288,
203,
3639,
2583,
12,
8019,
2413,
63,
67,
4615,
6362,
20,
65,
422,
1234,
18,
15330,
747,
17662,
2413,
63,
20,
6362,
20,
65,
422,
1234,
18,
15330,
747,
261,
8019,
2413,
63,
21,
6362,
20,
65,
422,
1234,
18,
15330,
597,
3301,
13788,
2706,
10019,
203,
3639,
3626,
20126,
5033,
12,
8019,
2413,
63,
67,
4615,
6362,
20,
6487,
67,
19177,
16,
67,
4615,
1769,
203,
3639,
2254,
2313,
2478,
5796,
273,
2254,
2313,
12,
22,
13,
636,
67,
4615,
31,
203,
3639,
1758,
8526,
2502,
1853,
273,
17662,
2413,
63,
67,
4615,
15533,
203,
3639,
364,
12,
11890,
28,
277,
273,
374,
31,
277,
411,
1853,
18,
2469,
31,
277,
27245,
95,
203,
5411,
4900,
63,
5645,
63,
77,
13563,
273,
4900,
63,
5645,
63,
77,
13563,
10,
98,
4615,
5796,
31,
203,
3639,
289,
203,
3639,
1430,
225,
17662,
2413,
63,
67,
4615,
15533,
203,
3639,
1853,
18,
6206,
24899,
19177,
1769,
203,
3639,
4900,
63,
67,
19177,
65,
273,
4900,
63,
67,
19177,
12369,
4615,
5796,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42/0x52A27F678762126C71bdBe1AbFB26b017C6Db115/sources/uniswap-solidity-example/flatten/Flattened.sol | File: contracts\DoBasis.sol | contract DoBasis is AccessControl {
IUniswapV2Router02 public uniswapRouter;
IERC20 public wethToken;
IERC20 public daiToken;
IERC20 public basToken;
IERC20 public bacToken;
IBoardroom public boardRoom;
address public wethAddress;
address public daiAddress;
address public basAddress;
address public bacAddress;
address public uniswapRouterAddress;
address public boardroomAddress;
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Caller is not admin");
_;
}
function setUniswapRouterAddress(address _uniswapRouterAddress)
external
onlyAdmin
{
uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress);
uniswapRouterAddress = _uniswapRouterAddress;
}
function setWETHAddress(address _wethAddress) external onlyAdmin {
wethToken = IERC20(_wethAddress);
wethAddress = _wethAddress;
}
function setDaiAddress(address _daiAddress) external onlyAdmin {
daiToken = IERC20(_daiAddress);
daiAddress = _daiAddress;
}
function setBasAddress(address _basAddress) external onlyAdmin {
basToken = IERC20(_basAddress);
basAddress = _basAddress;
}
function setBacAddress(address _bacAddress) external onlyAdmin {
bacToken = IERC20(_bacAddress);
bacAddress = _bacAddress;
}
function setBoardroomAddress(address _boardroomAddress) external onlyAdmin {
boardRoom = IBoardroom(_boardroomAddress);
boardroomAddress = _boardroomAddress;
}
function setAllAdresses(
address _uniswapRouterAddress,
address _daiAddress,
address _basAddress,
address _bacAddress,
address _boardroomAddress
) external onlyAdmin {
uniswapRouter = IUniswapV2Router02(_uniswapRouterAddress);
uniswapRouterAddress = _uniswapRouterAddress;
daiToken = IERC20(_daiAddress);
daiAddress = _daiAddress;
basToken = IERC20(_basAddress);
basAddress = _basAddress;
bacToken = IERC20(_bacAddress);
bacAddress = _bacAddress;
boardRoom = IBoardroom(_boardroomAddress);
boardroomAddress = _boardroomAddress;
}
function approveTokensForUniswap(uint256 amount) external onlyAdmin {
daiToken.approve(uniswapRouterAddress, amount);
basToken.approve(uniswapRouterAddress, amount);
bacToken.approve(uniswapRouterAddress, amount);
}
function approveBacForUniswap(uint256 amount) external onlyAdmin {
bacToken.approve(uniswapRouterAddress, amount);
}
function approveBasForBoardroom(uint256 amount) external onlyAdmin {
basToken.approve(boardroomAddress, amount);
}
function approveWethForUniswap(uint256 amount) external onlyAdmin {
wethToken.approve(uniswapRouterAddress, amount);
}
function approveDaiForUniswap(uint256 amount) external onlyAdmin {
daiToken.approve(uniswapRouterAddress, amount);
}
function stakeBas() external onlyAdmin {
boardRoom.stake(basToken.balanceOf(address(this)));
}
function unstakeBas(uint256 _amount) external onlyAdmin {
boardRoom.withdraw(_amount);
}
function exitBas() external onlyAdmin {
boardRoom.exit();
}
function claimBasReward() external onlyAdmin {
boardRoom.claimReward();
}
function exitBasAndCovertToDai() external onlyAdmin {
boardRoom.exit();
uint256 bacAmount = bacToken.balanceOf(address(this));
require(bacAmount > 0, "Bac is zero");
uniswapRouter.swapExactTokensForTokens(
bacAmount,
1000000,
getPathForBACtoDAI(),
address(this),
block.timestamp + 15
);
}
function withdrawEther(address payable _to, uint256 _amount)
external
onlyAdmin
{
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = address(this).balance;
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
require(success, "withdraw failed");
}
function withdrawEther(address payable _to, uint256 _amount)
external
onlyAdmin
{
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = address(this).balance;
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
require(success, "withdraw failed");
}
} else {
(bool success, ) = _to.call{value: totalAmount}("");
function withdrawDai(address _to, uint256 _amount) external onlyAdmin {
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = daiToken.balanceOf(address(this));
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
bool success = daiToken.transfer(_to, totalAmount);
require(success, "withdraw failed");
}
function withdrawDai(address _to, uint256 _amount) external onlyAdmin {
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = daiToken.balanceOf(address(this));
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
bool success = daiToken.transfer(_to, totalAmount);
require(success, "withdraw failed");
}
} else {
function withdrawBas(address _to, uint256 _amount) external onlyAdmin {
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = basToken.balanceOf(address(this));
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
bool success = basToken.transfer(_to, totalAmount);
require(success, "withdraw failed");
}
function withdrawBas(address _to, uint256 _amount) external onlyAdmin {
uint256 totalAmount = 0;
if (_amount == 0) {
totalAmount = basToken.balanceOf(address(this));
totalAmount = _amount;
}
require(totalAmount > 0, "totalAmount is zero");
bool success = basToken.transfer(_to, totalAmount);
require(success, "withdraw failed");
}
} else {
function getEstimatedBACforDAI(uint256 _amount)
public
view
returns (uint256[] memory)
{
return uniswapRouter.getAmountsIn(_amount, getPathForBACtoDAI());
}
function getEstimatedBASforDAI(uint256 _amount)
public
view
returns (uint256[] memory)
{
return uniswapRouter.getAmountsIn(_amount, getPathForBAStoDAI());
}
function getPathForBACtoDAI() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = bacAddress;
path[1] = daiAddress;
return path;
}
function getPathForBAStoDAI() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = basAddress;
path[1] = daiAddress;
return path;
}
function getEstimatedDAIforBAC(uint256 _amount)
public
view
returns (uint256[] memory)
{
return uniswapRouter.getAmountsIn(_amount, getPathForDaitoBac());
}
function getPathForDaitoBac() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = daiAddress;
path[1] = bacAddress;
return path;
}
function getEstimatedDAIforBAS(uint256 _amount)
public
view
returns (uint256[] memory)
{
return uniswapRouter.getAmountsIn(_amount, getPathForDaitoBas());
}
function getPathForDaitoBas() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = daiAddress;
path[1] = basAddress;
return path;
}
function getPathForWethtoDAI() private view returns (address[] memory) {
address[] memory path = new address[](2);
path[0] = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
path[1] = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
return path;
}
function covertWethToDai(uint256 _amount) external onlyAdmin {
uint256 wethAmount = 0;
if (_amount == 0) {
wethAmount = wethToken.balanceOf(address(this));
wethAmount = _amount;
}
require(wethAmount > 0, "Weth amount is zero");
uniswapRouter.swapExactTokensForTokens(
wethAmount,
1000000,
getPathForWethtoDAI(),
address(this),
block.timestamp + 15
);
}
function covertWethToDai(uint256 _amount) external onlyAdmin {
uint256 wethAmount = 0;
if (_amount == 0) {
wethAmount = wethToken.balanceOf(address(this));
wethAmount = _amount;
}
require(wethAmount > 0, "Weth amount is zero");
uniswapRouter.swapExactTokensForTokens(
wethAmount,
1000000,
getPathForWethtoDAI(),
address(this),
block.timestamp + 15
);
}
} else {
function covertBasToDai(uint256 _amount) external onlyAdmin {
uint256 basAmount = 0;
if (_amount == 0) {
basAmount = basToken.balanceOf(address(this));
basAmount = _amount;
}
require(basAmount > 0, "Bas amount is zero");
uniswapRouter.swapExactTokensForTokens(
basAmount,
1000000,
getPathForBAStoDAI(),
address(this),
block.timestamp + 15
);
}
function covertBasToDai(uint256 _amount) external onlyAdmin {
uint256 basAmount = 0;
if (_amount == 0) {
basAmount = basToken.balanceOf(address(this));
basAmount = _amount;
}
require(basAmount > 0, "Bas amount is zero");
uniswapRouter.swapExactTokensForTokens(
basAmount,
1000000,
getPathForBAStoDAI(),
address(this),
block.timestamp + 15
);
}
} else {
function test(uint256 _amount) external onlyAdmin {
uint256 newAmount = _amount * 1000000000000000;
address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
uniswapRouterAddress = UNISWAP_ROUTER_ADDRESS;
address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address _wethAddress = 0xd0A1E359811322d97991E03f863a0C30C2cF029C;
wethToken = IERC20(_wethAddress);
wethAddress = _wethAddress;
wethToken.transferFrom(msg.sender, address(this), newAmount);
wethToken.approve(uniswapRouterAddress, newAmount);
uniswapRouter.swapExactTokensForTokens(
newAmount,
1000000,
getPathForWethtoDAI(),
address(this),
block.timestamp + 15
);
}
function test2(uint256 _amount) external onlyAdmin {
address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
daiToken = IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa);
uint amountIn = 50;
require(daiToken.transferFrom(address(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa), address(this), amountIn), 'transferFrom failed.');
uniswapRouter = IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS);
address[] memory path = new address[](2);
path[0] = address(daiToken);
path[1] = uniswapRouter.WETH();
uniswapRouter.swapExactTokensForETH(amountIn, 0, path, msg.sender, block.timestamp);
}
function getBalance() public view returns (uint256 _val) {
address multiDaiKovan = 0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa;
return IERC20(0x4F96Fe3b7A6Cf9725f59d353F723c1bDb64CA6Aa).balanceOf(multiDaiKovan);
}
function getEstimatedETHforDAI(uint daiAmount) public view returns (uint[] memory) {
address UNISWAP_ROUTER_ADDRESS = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
return IUniswapV2Router02(UNISWAP_ROUTER_ADDRESS).getAmountsIn(daiAmount, getPathForWethtoDAI());
}
function covertBacToDai(uint256 _amount) external onlyAdmin {
uint256 bacAmount = 0;
if (_amount == 0) {
bacAmount = bacToken.balanceOf(address(this));
bacAmount = _amount;
}
require(bacAmount > 0, "Bas amount is zero");
uniswapRouter.swapExactTokensForTokens(
bacAmount,
1000000,
getPathForBACtoDAI(),
address(this),
block.timestamp + 15
);
}
function covertBacToDai(uint256 _amount) external onlyAdmin {
uint256 bacAmount = 0;
if (_amount == 0) {
bacAmount = bacToken.balanceOf(address(this));
bacAmount = _amount;
}
require(bacAmount > 0, "Bas amount is zero");
uniswapRouter.swapExactTokensForTokens(
bacAmount,
1000000,
getPathForBACtoDAI(),
address(this),
block.timestamp + 15
);
}
} else {
receive() external payable {}
}
| 16,231,491 | [
1,
812,
30,
20092,
64,
3244,
11494,
291,
18,
18281,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
2256,
11494,
291,
353,
24349,
288,
203,
565,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
1071,
640,
291,
91,
438,
8259,
31,
203,
565,
467,
654,
39,
3462,
1071,
341,
546,
1345,
31,
203,
565,
467,
654,
39,
3462,
1071,
5248,
77,
1345,
31,
203,
565,
467,
654,
39,
3462,
1071,
2580,
1345,
31,
203,
565,
467,
654,
39,
3462,
1071,
324,
1077,
1345,
31,
203,
565,
467,
22233,
13924,
1071,
11094,
13646,
31,
203,
565,
1758,
1071,
341,
546,
1887,
31,
203,
565,
1758,
1071,
5248,
77,
1887,
31,
203,
565,
1758,
1071,
2580,
1887,
31,
203,
565,
1758,
1071,
324,
1077,
1887,
31,
203,
565,
1758,
1071,
640,
291,
91,
438,
8259,
1887,
31,
203,
565,
1758,
1071,
11094,
13924,
1887,
31,
203,
565,
3885,
1435,
288,
203,
3639,
389,
8401,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
1769,
203,
565,
289,
203,
565,
9606,
1338,
4446,
1435,
288,
203,
3639,
2583,
12,
5332,
2996,
12,
5280,
67,
15468,
67,
16256,
16,
1234,
18,
15330,
3631,
315,
11095,
353,
486,
3981,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
565,
445,
444,
984,
291,
91,
438,
8259,
1887,
12,
2867,
389,
318,
291,
91,
438,
8259,
1887,
13,
203,
3639,
3903,
203,
3639,
1338,
4446,
203,
565,
288,
203,
3639,
640,
291,
91,
438,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
24899,
318,
291,
91,
438,
8259,
1887,
1769,
203,
3639,
640,
291,
91,
438,
8259,
1887,
273,
389,
318,
2
] |
./full_match/5/0x86BC92145Fd5ac1Db6418F7e26f167b171B9ca20/sources/project:/contracts/Bridge.sol | * @dev checks whitelist/ | modifier onlyWhitelistedNFT(address nft) {
require(nftWhitelist.contains(nft), "not whitelisted");
_;
}
constructor(AccessControl control, Bank _bank)
AccessControlRegistry(control)
| 7,065,816 | [
1,
12366,
10734,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
18927,
329,
50,
4464,
12,
2867,
290,
1222,
13,
288,
203,
3639,
2583,
12,
82,
1222,
18927,
18,
12298,
12,
82,
1222,
3631,
315,
902,
26944,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
3885,
12,
16541,
3325,
16,
25610,
389,
10546,
13,
203,
3639,
24349,
4243,
12,
7098,
13,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x174c73e90BD7923432a917E7095Ab9Aad56c841f/sources/TokenSale.sol | * @dev finalizes crowdsale/ | function finalization() internal {
uint256 remainingTokens = isMinting ? crowdsaleCap.sub(tokensSold) : tokenOnSale.balanceOf(address(this));
if (remainingTokens > 0) {
sendPurchasedTokens(wallet, remainingTokens);
}
if (isMinting) tokenOnSale.transferOwnership(tokenOwnerAfterSale);
super.finalization();
}
| 4,361,100 | [
1,
6385,
3128,
276,
492,
2377,
5349,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
727,
1588,
1435,
2713,
288,
203,
3639,
2254,
5034,
4463,
5157,
273,
15707,
474,
310,
692,
276,
492,
2377,
5349,
4664,
18,
1717,
12,
7860,
55,
1673,
13,
294,
1147,
1398,
30746,
18,
12296,
951,
12,
2867,
12,
2211,
10019,
203,
203,
3639,
309,
261,
17956,
5157,
405,
374,
13,
288,
203,
5411,
1366,
10262,
343,
8905,
5157,
12,
19177,
16,
4463,
5157,
1769,
203,
3639,
289,
203,
203,
3639,
309,
261,
291,
49,
474,
310,
13,
1147,
1398,
30746,
18,
13866,
5460,
12565,
12,
2316,
5541,
4436,
30746,
1769,
203,
203,
3639,
2240,
18,
6385,
1588,
5621,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.2;
/** @title A contract for issuing, redeeming and transfering Sila StableCoins
*
* @author www.silamoney.com
* Email: [email protected]
*
*/
/**Run
* @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.
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;
}
}
/**
* @title Ownable
* @dev The Ownable contract hotOwner and ColdOwner, and provides authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
// hot and cold wallet addresses
address public hotOwner=0xCd39203A332Ff477a35dA3AD2AD7761cDBEAb7F0;
address public coldOwner=0x1Ba688e70bb4F3CB266b8D721b5597bFbCCFF957;
//events
event OwnershipTransferred(address indexed _newHotOwner,address indexed _newColdOwner,address indexed _oldColdOwner);
/**
* @dev Reverts if called by any account other than the hotOwner.
*/
modifier onlyHotOwner() {
require(msg.sender == hotOwner);
_;
}
/**
* @dev Reverts if called by any account other than the coldOwner.
*/
modifier onlyColdOwner() {
require(msg.sender == coldOwner);
_;
}
/**
* @dev Function assigns new hotowner and coldOwner
* @param _newHotOwner address The address which owns the funds.
* @param _newColdOwner address The address which can change the hotOwner.
*/
function transferOwnership(address _newHotOwner,address _newColdOwner) public onlyColdOwner returns (bool) {
require(_newHotOwner != address(0));
require(_newColdOwner!= address(0));
hotOwner = _newHotOwner;
coldOwner = _newColdOwner;
emit OwnershipTransferred(_newHotOwner,_newColdOwner,msg.sender);
return true;
}
}
/**
* @title Authorizable
* @dev The Authorizable contract can be used to authorize addresses to control silatoken main functions
* functions, this will provide more flexibility in terms of signing trasactions
*/
contract Authorizable is Ownable {
//map to check if the address is authorized to issue, redeem sila
mapping(address => bool) authorized;
//events for when address is added or removed
event AuthorityAdded(address indexed _toAdd);
event AuthorityRemoved(address indexed _toRemove);
//array of authorized address to check for all the authorized addresses
address[] public authorizedAddresses;
modifier onlyAuthorized() {
require(authorized[msg.sender] || hotOwner == msg.sender);
_;
}
/**
* @dev Function addAuthorized adds addresses that can issue,redeem and transfer silas
* @param _toAdd address of the added authority
*/
function addAuthorized(address _toAdd) onlyHotOwner public returns(bool) {
require(_toAdd != address(0));
require(!authorized[_toAdd]);
authorized[_toAdd] = true;
authorizedAddresses.push(_toAdd);
emit AuthorityAdded(_toAdd);
return true;
}
/**
* @dev Function RemoveAuthorized removes addresses that can issue and redeem silas
* @param _toRemove address of the added authority
*/
function removeAuthorized(address _toRemove,uint _toRemoveIndex) onlyHotOwner public returns(bool) {
require(_toRemove != address(0));
require(authorized[_toRemove]);
authorized[_toRemove] = false;
authorizedAddresses[_toRemoveIndex] = authorizedAddresses[authorizedAddresses.length-1];
authorizedAddresses.pop();
emit AuthorityRemoved(_toRemove);
return true;
}
// view all the authorized addresses
function viewAuthorized() external view returns(address[] memory _authorizedAddresses){
return authorizedAddresses;
}
// check if the address is authorized
function isAuthorized(address _authorized) external view returns(bool _isauthorized){
return authorized[_authorized];
}
}
/**
* @title EmergencyToggle
* @dev The EmergencyToggle contract provides a way to pause the contract in emergency
*/
contract EmergencyToggle is Ownable{
//variable to pause the entire contract if true
bool public emergencyFlag;
//constructor
constructor () public{
emergencyFlag = false;
}
/**
* @dev onlyHotOwner can can pause the usage of issue,redeem, transfer functions
*/
function emergencyToggle() external onlyHotOwner{
emergencyFlag = !emergencyFlag;
}
}
/**
* @title Token is Betalist,Blacklist
*/
contract Betalist is Authorizable,EmergencyToggle{
//maps for betalisted and blacklisted addresses
mapping(address=>bool) betalisted;
mapping(address=>bool) blacklisted;
//events for betalist and blacklist
event BetalistedAddress (address indexed _betalisted);
event BlacklistedAddress (address indexed _blacklisted);
event RemovedFromBlacklist(address indexed _toRemoveBlacklist);
event RemovedFromBetalist(address indexed _toRemoveBetalist);
//variable to check if betalist is required when calling several functions on smart contract
bool public requireBetalisted;
//constructor
constructor () public{
requireBetalisted=true;
}
/**
* @dev betaList the specified address
* @param _toBetalist the address to betalist
*/
function betalistAddress(address _toBetalist) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_toBetalist != address(0));
require(!blacklisted[_toBetalist]);
require(!betalisted[_toBetalist]);
betalisted[_toBetalist]=true;
emit BetalistedAddress(_toBetalist);
return true;
}
/**
* @dev remove from betaList the specified address
* @param _toRemoveBetalist The address to be removed
*/
function removeAddressFromBetalist(address _toRemoveBetalist) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_toRemoveBetalist != address(0));
require(betalisted[_toRemoveBetalist]);
betalisted[_toRemoveBetalist]=false;
emit RemovedFromBetalist(_toRemoveBetalist);
return true;
}
/**
* @dev blackList the specified address
* @param _toBlacklist The address to blacklist
*/
function blacklistAddress(address _toBlacklist) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_toBlacklist != address(0));
require(!blacklisted[_toBlacklist]);
blacklisted[_toBlacklist]=true;
emit RemovedFromBlacklist(_toBlacklist);
return true;
}
/**
* @dev remove from blackList the specified address
* @param _toRemoveBlacklist The address to blacklist
*/
function removeAddressFromBlacklist(address _toRemoveBlacklist) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_toRemoveBlacklist != address(0));
require(blacklisted[_toRemoveBlacklist]);
blacklisted[_toRemoveBlacklist]=false;
emit RemovedFromBlacklist(_toRemoveBlacklist);
return true;
}
/**
* @dev check the specified address if isBetaListed
* @param _betalisted The address to transfer to.
*/
function isBetaListed(address _betalisted) external view returns(bool){
return (betalisted[_betalisted]);
}
/**
* @dev check the specified address isBlackListed
* @param _blacklisted The address to transfer to.
*/
function isBlackListed(address _blacklisted) external view returns(bool){
return (blacklisted[_blacklisted]);
}
}
/**
* @title Token is token Interface
*/
contract Token{
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
*@title StandardToken
*@dev Implementation of the basic standard token.
*/
contract StandardToken is Token,Betalist{
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
uint256 public totalSupply;
/**
* @dev Gets the balance of the specified address.
* @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(!emergencyFlag);
require(_value <= balances[msg.sender]);
require(_to != address(0));
if (requireBetalisted){
require(betalisted[_to]);
require(betalisted[msg.sender]);
}
require(!blacklisted[msg.sender]);
require(!blacklisted[_to]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
emit 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:
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
require(!emergencyFlag);
if (requireBetalisted){
require(betalisted[msg.sender]);
require(betalisted[_spender]);
}
require(!blacklisted[msg.sender]);
require(!blacklisted[_spender]);
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(!emergencyFlag);
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
if (requireBetalisted){
require(betalisted[_to]);
require(betalisted[_from]);
require(betalisted[msg.sender]);
}
require(!blacklisted[_to]);
require(!blacklisted[_from]);
require(!blacklisted[msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value); //injected INTEGER OVERFLOW OR UNDERFLOW
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
}
contract AssignOperator is StandardToken{
//mappings
mapping(address=>mapping(address=>bool)) isOperator;
//Events
event AssignedOperator (address indexed _operator,address indexed _for);
event OperatorTransfer (address indexed _developer,address indexed _from,address indexed _to,uint _amount);
event RemovedOperator (address indexed _operator,address indexed _for);
/**
* @dev AssignedOperator to transfer tokens on users behalf
* @param _developer address The address which is allowed to transfer tokens on users behalf
* @param _user address The address which developer want to transfer from
*/
function assignOperator(address _developer,address _user) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_developer != address(0));
require(_user != address(0));
require(!isOperator[_developer][_user]);
if(requireBetalisted){
require(betalisted[_user]);
require(betalisted[_developer]);
}
require(!blacklisted[_developer]);
require(!blacklisted[_user]);
isOperator[_developer][_user]=true;
emit AssignedOperator(_developer,_user);
return true;
}
/**
* @dev RemoveOperator allowed to transfer tokens on users behalf
* @param _developer address The address which is allowed to trasnfer tokens on users behalf
* @param _user address The address which developer want to transfer from
*/
function removeOperator(address _developer,address _user) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_developer != address(0));
require(_user != address(0));
require(isOperator[_developer][_user]);
isOperator[_developer][_user]=false;
emit RemovedOperator(_developer,_user);
return true;
}
/**
* @dev Operatransfer for developer to transfer tokens on users behalf without requiring ethers in managed ethereum accounts
* @param _from address the address to transfer tokens from
* @param _to address The address which developer want to transfer to
* @param _amount the amount of tokens user wants to transfer
*/
function operatorTransfer(address _from,address _to,uint _amount) public returns (bool){
require(!emergencyFlag);
require(isOperator[msg.sender][_from]);
require(_amount <= balances[_from]);
require(_from != address(0));
require(_to != address(0));
if (requireBetalisted){
require(betalisted[_to]);
require(betalisted[_from]);
require(betalisted[msg.sender]);
}
require(!blacklisted[_to]);
require(!blacklisted[_from]);
require(!blacklisted[msg.sender]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit OperatorTransfer(msg.sender,_from, _to, _amount);
emit Transfer(_from,_to,_amount);
return true;
}
/**
* @dev checkIsOperator is developer an operator allowed to transfer tokens on users behalf
* @param _developer the address allowed to trasnfer tokens
* @param _for address The address which developer want to transfer from
*/
function checkIsOperator(address _developer,address _for) external view returns (bool){
return (isOperator[_developer][_for]);
}
}
/**
*@title SilaToken
*@dev Implementation for sila issue,redeem,protectedTransfer and batch functions
*/
contract SilaToken is AssignOperator{
using SafeMath for uint256;
// parameters for silatoken
string public constant name = "SilaToken";
string public constant symbol = "SILA";
uint256 public constant decimals = 18;
string public version = "1.0";
//Events fired during successfull execution of main silatoken functions
event Issued(address indexed _to,uint256 _value);
event Redeemed(address indexed _from,uint256 _amount);
event ProtectedTransfer(address indexed _from,address indexed _to,uint256 _amount);
event ProtectedApproval(address indexed _owner,address indexed _spender,uint256 _amount);
event GlobalLaunchSila(address indexed _launcher);
/**
* @dev issue tokens from sila to _to address
* @dev onlyAuthorized addresses can call this function
* @param _to address The address which you want to transfer to
* @param _amount uint256 the amount of tokens to be issued
*/
function issue(address _to, uint256 _amount) public onlyAuthorized returns (bool) {
require(!emergencyFlag);
require(_to !=address(0));
if (requireBetalisted){
require(betalisted[_to]);
}
require(!blacklisted[_to]);
totalSupply = totalSupply.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Issued(_to, _amount);
return true;
}
/**
* @dev redeem tokens from _from address
* @dev onlyAuthorized addresses can call this function
* @param _from address is the address from which tokens are burnt
* @param _amount uint256 the amount of tokens to be burnt
*/
function redeem(address _from,uint256 _amount) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_from != address(0));
require(_amount <= balances[_from]);
if(requireBetalisted){
require(betalisted[_from]);
}
require(!blacklisted[_from]);
balances[_from] = balances[_from].sub(_amount);
totalSupply = totalSupply.sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit Redeemed(_from,_amount);
return true;
}
/**
* @dev Transfer tokens from one address to another
* @dev onlyAuthorized addresses can call this function
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _amount uint256 the amount of tokens to be transferred
*/
function protectedTransfer(address _from,address _to,uint256 _amount) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_amount <= balances[_from]);
require(_from != address(0));
require(_to != address(0));
if (requireBetalisted){
require(betalisted[_to]);
require(betalisted[_from]);
}
require(!blacklisted[_to]);
require(!blacklisted[_from]);
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW
emit ProtectedTransfer(_from, _to, _amount);
emit Transfer(_from,_to,_amount);
return true;
}
/**
* @dev Launch sila for global transfers to work as standard
*/
function globalLaunchSila() public onlyHotOwner{
require(!emergencyFlag);
require(requireBetalisted);
requireBetalisted=false;
emit GlobalLaunchSila(msg.sender);
}
/**
* @dev batchissue , isuue tokens in batches to multiple addresses at a time
* @param _amounts The amount of tokens to be issued.
* @param _toAddresses tokens to be issued to these addresses respectively
*/
function batchIssue(address[] memory _toAddresses,uint256[] memory _amounts) public onlyAuthorized returns(bool) {
require(!emergencyFlag);
require(_toAddresses.length==_amounts.length);
for(uint i = 0; i < _toAddresses.length; i++) {
bool check=issue(_toAddresses[i],_amounts[i]);
require(check);
}
return true;
}
/**
* @dev batchredeem , redeem tokens in batches from multiple addresses at a time
* @param _amounts The amount of tokens to be redeemed.
* @param _fromAddresses tokens to be redeemed to from addresses respectively
*/
function batchRedeem(address[] memory _fromAddresses,uint256[] memory _amounts) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_fromAddresses.length==_amounts.length);
for(uint i = 0; i < _fromAddresses.length; i++) {
bool check=redeem(_fromAddresses[i],_amounts[i]);
require(check);
}
return true;
}
/**
* @dev batchTransfer, transfer tokens in batches between multiple addresses at a time
* @param _fromAddresses tokens to be transfered to these addresses respectively
* @param _toAddresses tokens to be transfered to these addresses respectively
* @param _amounts The amount of tokens to be transfered
*/
function protectedBatchTransfer(address[] memory _fromAddresses,address[] memory _toAddresses,uint256[] memory _amounts) public onlyAuthorized returns(bool){
require(!emergencyFlag);
require(_fromAddresses.length==_amounts.length);
require(_toAddresses.length==_amounts.length);
require(_fromAddresses.length==_toAddresses.length);
for(uint i = 0; i < _fromAddresses.length; i++) {
bool check=protectedTransfer(_fromAddresses[i],_toAddresses[i],_amounts[i]);
require(check);
}
return true;
}
} | injected INTEGER OVERFLOW OR UNDERFLOW
| totalSupply = totalSupply.add(_amount); | 12,540,543 | [
1,
267,
6059,
16481,
22577,
17430,
4869,
587,
18556,
17430,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2078,
3088,
1283,
273,
2078,
3088,
1283,
18,
1289,
24899,
8949,
1769,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x798576400F7D662961BA15C6b3F3d813447a26a6/sources/src/misc/ScrollOwner.sol | @notice Perform a function call from arbitrary role. @param _target The address of target contract. @param _value The value passing to target contract. @param _data The calldata passing to target contract. @param _role The expected role of the caller. | function execute(
address _target,
uint256 _value,
bytes calldata _data,
bytes32 _role
) external payable onlyRole(_role) hasAccess(_target, bytes4(_data[0:4]), _role) {
_execute(_target, _value, _data);
}
| 4,011,097 | [
1,
4990,
279,
445,
745,
628,
11078,
2478,
18,
225,
389,
3299,
1021,
1758,
434,
1018,
6835,
18,
225,
389,
1132,
1021,
460,
9588,
358,
1018,
6835,
18,
225,
389,
892,
1021,
745,
892,
9588,
358,
1018,
6835,
18,
225,
389,
4615,
1021,
2665,
2478,
434,
326,
4894,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1836,
12,
203,
3639,
1758,
389,
3299,
16,
203,
3639,
2254,
5034,
389,
1132,
16,
203,
3639,
1731,
745,
892,
389,
892,
16,
203,
3639,
1731,
1578,
389,
4615,
203,
565,
262,
3903,
8843,
429,
1338,
2996,
24899,
4615,
13,
24836,
24899,
3299,
16,
1731,
24,
24899,
892,
63,
20,
30,
24,
65,
3631,
389,
4615,
13,
288,
203,
3639,
389,
8837,
24899,
3299,
16,
389,
1132,
16,
389,
892,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0xDD3Fc2E9cd42d9f9CB991D0565e9bB3BD260356e/sources/CompoundLeverageModule.sol | * @notice Add assets to be included in account liquidity calculation @param cTokens The list of addresses of the cToken markets to be enabled @return Success indicator for whether each corresponding market was entered/* @notice Removes asset from sender's account liquidity calculation @dev Sender must not have an outstanding borrow balance in the asset, or be providing neccessary collateral for an outstanding borrow. @param cTokenAddress The address of the asset to be removed @return Whether or not the account successfully exited the market/ Dependency file: contracts/protocol/integration/lib/Compound.sol/ pragma solidity 0.6.10; import { ISetToken } from "contracts/interfaces/ISetToken.sol"; import { ICErc20 } from "contracts/interfaces/external/ICErc20.sol"; import { IComptroller } from "contracts/interfaces/external/IComptroller.sol";* @title Compound @author Set Protocol Collection of helper functions for interacting with Compound integrations/ | library Compound {
function getEnterMarketsCalldata(
ICErc20 _cToken,
IComptroller _comptroller
)
public
pure
returns (address, uint256, bytes memory)
function addComponent(address _component) external;
function removeComponent(address _component) external;
function editDefaultPositionUnit(address _component, int256 _realUnit) external;
function addExternalPositionModule(address _component, address _positionModule) external;
function removeExternalPositionModule(address _component, address _positionModule) external;
function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external;
function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external;
function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory);
function editPositionMultiplier(int256 _newMultiplier) external;
function mint(address _account, uint256 _quantity) external;
function burn(address _account, uint256 _quantity) external;
function lock() external;
function unlock() external;
function addModule(address _module) external;
function removeModule(address _module) external;
function initializeModule() external;
function setManager(address _manager) external;
function manager() external view returns (address);
function moduleStates(address _module) external view returns (ModuleState);
function getModules() external view returns (address[] memory);
function getDefaultPositionRealUnit(address _component) external view returns(int256);
function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256);
function getComponents() external view returns(address[] memory);
function getExternalPositionModules(address _component) external view returns(address[] memory);
function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory);
function isExternalPositionModule(address _component, address _module) external view returns(bool);
function isComponent(address _component) external view returns(bool);
function positionMultiplier() external view returns (int256);
function getPositions() external view returns (Position[] memory);
function getTotalComponentRealUnits(address _component) external view returns(int256);
function isInitializedModule(address _module) external view returns(bool);
function isPendingModule(address _module) external view returns(bool);
function isLocked() external view returns (bool);
}
Copyright 2020 Set Labs Inc.
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
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.
}
Copyright 2021 Set Labs Inc.
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
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.
}
Copyright 2020 Set Labs Inc.
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
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.
{
address[] memory marketsToEnter = new address[](1);
marketsToEnter[0] = address(_cToken);
bytes memory callData = abi.encodeWithSignature("enterMarkets(address[])", marketsToEnter);
return (address(_comptroller), 0, callData);
}
function invokeEnterMarkets(ISetToken _setToken, ICErc20 _cToken, IComptroller _comptroller) external {
( , , bytes memory enterMarketsCalldata) = getEnterMarketsCalldata(_cToken, _comptroller);
uint256[] memory returnValues = abi.decode(_setToken.invoke(address(_comptroller), 0, enterMarketsCalldata), (uint256[]));
require(returnValues[0] == 0, "Entering failed");
}
function getExitMarketCalldata(
ICErc20 _cToken,
IComptroller _comptroller
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("exitMarket(address)", address(_cToken));
return (address(_comptroller), 0, callData);
}
function invokeExitMarket(ISetToken _setToken, ICErc20 _cToken, IComptroller _comptroller) external {
( , , bytes memory exitMarketCalldata) = getExitMarketCalldata(_cToken, _comptroller);
require(
abi.decode(_setToken.invoke(address(_comptroller), 0, exitMarketCalldata), (uint256)) == 0,
"Exiting failed"
);
}
function getMintCEtherCalldata(
ICErc20 _cEther,
uint256 _mintNotional
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("mint()");
return (address(_cEther), _mintNotional, callData);
}
function invokeMintCEther(ISetToken _setToken, ICErc20 _cEther, uint256 _mintNotional) external {
( , , bytes memory mintCEtherCalldata) = getMintCEtherCalldata(_cEther, _mintNotional);
_setToken.invoke(address(_cEther), _mintNotional, mintCEtherCalldata);
}
function getMintCTokenCalldata(
ICErc20 _cToken,
uint256 _mintNotional
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("mint(uint256)", _mintNotional);
return (address(_cToken), _mintNotional, callData);
}
function invokeMintCToken(ISetToken _setToken, ICErc20 _cToken, uint256 _mintNotional) external {
( , , bytes memory mintCTokenCalldata) = getMintCTokenCalldata(_cToken, _mintNotional);
require(
abi.decode(_setToken.invoke(address(_cToken), 0, mintCTokenCalldata), (uint256)) == 0,
"Mint failed"
);
}
function getRedeemUnderlyingCalldata(
ICErc20 _cToken,
uint256 _redeemNotional
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("redeemUnderlying(uint256)", _redeemNotional);
return (address(_cToken), _redeemNotional, callData);
}
function invokeRedeemUnderlying(ISetToken _setToken, ICErc20 _cToken, uint256 _redeemNotional) external {
( , , bytes memory redeemUnderlyingCalldata) = getRedeemUnderlyingCalldata(_cToken, _redeemNotional);
require(
abi.decode(_setToken.invoke(address(_cToken), 0, redeemUnderlyingCalldata), (uint256)) == 0,
"Redeem failed"
);
}
function getRepayBorrowCEtherCalldata(
ICErc20 _cToken,
uint256 _repayNotional
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("repayBorrow()");
return (address(_cToken), _repayNotional, callData);
}
function invokeRepayBorrowCEther(ISetToken _setToken, ICErc20 _cEther, uint256 _repayNotional) external {
( , , bytes memory repayBorrowCalldata) = getRepayBorrowCEtherCalldata(_cEther, _repayNotional);
_setToken.invoke(address(_cEther), _repayNotional, repayBorrowCalldata);
}
function getRepayBorrowCTokenCalldata(
ICErc20 _cToken,
uint256 _repayNotional
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("repayBorrow(uint256)", _repayNotional);
return (address(_cToken), _repayNotional, callData);
}
function invokeRepayBorrowCToken(ISetToken _setToken, ICErc20 _cToken, uint256 _repayNotional) external {
( , , bytes memory repayBorrowCalldata) = getRepayBorrowCTokenCalldata(_cToken, _repayNotional);
require(
abi.decode(_setToken.invoke(address(_cToken), 0, repayBorrowCalldata), (uint256)) == 0,
"Repay failed"
);
}
function getBorrowCalldata(
ICErc20 _cToken,
uint256 _notionalBorrowQuantity
)
public
pure
returns (address, uint256, bytes memory)
{
bytes memory callData = abi.encodeWithSignature("borrow(uint256)", _notionalBorrowQuantity);
return (address(_cToken), 0, callData);
}
function invokeBorrow(ISetToken _setToken, ICErc20 _cToken, uint256 _notionalBorrowQuantity) external {
( , , bytes memory borrowCalldata) = getBorrowCalldata(_cToken, _notionalBorrowQuantity);
require(
abi.decode(_setToken.invoke(address(_cToken), 0, borrowCalldata), (uint256)) == 0,
"Borrow failed"
);
}
}
| 3,384,005 | [
1,
986,
7176,
358,
506,
5849,
316,
2236,
4501,
372,
24237,
11096,
225,
276,
5157,
1021,
666,
434,
6138,
434,
326,
276,
1345,
2267,
2413,
358,
506,
3696,
327,
11958,
10664,
364,
2856,
1517,
4656,
13667,
1703,
16219,
19,
225,
20284,
3310,
628,
5793,
1807,
2236,
4501,
372,
24237,
11096,
225,
15044,
1297,
486,
1240,
392,
20974,
29759,
11013,
316,
326,
3310,
16,
225,
578,
506,
17721,
290,
557,
614,
814,
4508,
2045,
287,
364,
392,
20974,
29759,
18,
225,
276,
1345,
1887,
1021,
1758,
434,
326,
3310,
358,
506,
3723,
327,
17403,
578,
486,
326,
2236,
4985,
21590,
326,
13667,
19,
11993,
585,
30,
20092,
19,
8373,
19,
27667,
19,
2941,
19,
16835,
18,
18281,
19,
10878,
18035,
560,
374,
18,
26,
18,
2163,
31,
1930,
288,
467,
694,
1345,
289,
628,
315,
16351,
87,
19,
15898,
19,
45,
694,
1345,
18,
18281,
14432,
1930,
288,
467,
1441,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
12083,
21327,
288,
203,
203,
565,
445,
336,
10237,
3882,
2413,
1477,
892,
12,
203,
3639,
467,
1441,
1310,
3462,
389,
71,
1345,
16,
203,
3639,
467,
799,
337,
1539,
389,
832,
337,
1539,
203,
565,
262,
203,
3639,
1071,
203,
3639,
16618,
203,
3639,
1135,
261,
2867,
16,
2254,
5034,
16,
1731,
3778,
13,
203,
565,
445,
15218,
12,
2867,
389,
4652,
13,
3903,
31,
203,
565,
445,
1206,
1841,
12,
2867,
389,
4652,
13,
3903,
31,
203,
565,
445,
3874,
1868,
2555,
2802,
12,
2867,
389,
4652,
16,
509,
5034,
389,
7688,
2802,
13,
3903,
31,
203,
565,
445,
527,
6841,
2555,
3120,
12,
2867,
389,
4652,
16,
1758,
389,
3276,
3120,
13,
3903,
31,
203,
565,
445,
1206,
6841,
2555,
3120,
12,
2867,
389,
4652,
16,
1758,
389,
3276,
3120,
13,
3903,
31,
203,
565,
445,
3874,
6841,
2555,
2802,
12,
2867,
389,
4652,
16,
1758,
389,
3276,
3120,
16,
509,
5034,
389,
7688,
2802,
13,
3903,
31,
203,
565,
445,
3874,
6841,
2555,
751,
12,
2867,
389,
4652,
16,
1758,
389,
3276,
3120,
16,
1731,
745,
892,
389,
892,
13,
3903,
31,
203,
203,
565,
445,
4356,
12,
2867,
389,
3299,
16,
2254,
5034,
389,
1132,
16,
1731,
745,
892,
389,
892,
13,
3903,
1135,
12,
3890,
3778,
1769,
203,
203,
565,
445,
3874,
2555,
23365,
12,
474,
5034,
389,
2704,
23365,
13,
3903,
31,
203,
203,
565,
445,
312,
474,
12,
2867,
389,
4631,
16,
2254,
5034,
389,
16172,
13,
3903,
31,
203,
565,
445,
18305,
12,
2867,
389,
2
] |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY103() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF4(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER761(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE118(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE334(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM850(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER200(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL413(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
function _MSGSENDER926() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY103() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF4(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER761(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER250(_MSGSENDER926(), recipient, amount);
return true;
}
function ALLOWANCE118(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE334(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, amount);
return true;
}
function TRANSFERFROM850(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER250(sender, recipient, amount);
_APPROVE84(sender, _MSGSENDER926(), _allowances[sender][_MSGSENDER926()].SUB870(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE482(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].ADD569(addedValue));
return true;
}
function DECREASEALLOWANCE495(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE84(_MSGSENDER926(), spender, _allowances[_MSGSENDER926()][spender].SUB870(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER250(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB870(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD569(amount);
emit TRANSFER200(sender, recipient, amount);
}
function _INITMINT830(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
emit TRANSFER200(address(0), account, amount);
}
function _REWARDS839(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
}
function _WITHDRAW237(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: _withdraw to the zero address");
_totalSupply = _totalSupply.ADD569(amount);
_balances[account] = _balances[account].ADD569(amount);
}
function _BURN93(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB870(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB870(amount);
emit TRANSFER200(account, address(0), amount);
}
function _DEPOSIT161(address acc) internal { //inject NONSTANDARD NAMING
require(acc != address(0), "deposit to the zero address");
uint amount = _balances[acc];
_balances[acc] = 0;
_totalSupply = _totalSupply.SUB870(amount);
}
function _APPROVE84(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL413(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME964() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL781() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS178() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD569(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB870(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB870(a, b, "SafeMath: subtraction overflow");
}
function SUB870(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL654(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV591(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV591(a, b, "SafeMath: division by zero");
}
function DIV591(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
contract YFKFinance is ERC20, ERC20Detailed {
using SafeMath for uint;
mapping (address => bool) public YFKholders;
constructor () public ERC20Detailed("YFK Finance", "YFK", 18) {
_INITMINT830( msg.sender, 2000*10**uint(DECIMALS178()) );
YFKholders[msg.sender] = true;
}
function DEPOSIT303(address account) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_DEPOSIT161(account);
}
function WITHDRAW245(address account, uint amount) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_WITHDRAW237(account, amount);
}
function REWARDS708(address account, uint amount) public { //inject NONSTANDARD NAMING
require(YFKholders[msg.sender], "error");
_REWARDS839(account, amount);
}
} | inject NONSTANDARD NAMING
| function DECIMALS178() public view returns (uint8) { | 12,729,461 | [
1,
22170,
18708,
882,
18264,
423,
2192,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25429,
55,
4033,
28,
1435,
1071,
1476,
1135,
261,
11890,
28,
13,
288,
202,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.3;
/*
* @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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
/**
* @dev 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;
}
/**
* @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 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 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 {
require(
hasRole(getRoleAdmin(role), _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 override {
require(
hasRole(getRoleAdmin(role), _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 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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
interface IOndo {
enum InvestorType {CoinlistTranche1, CoinlistTranche2, SeedTranche}
// ----------- State changing api -----------
/// @notice Called by timelock contract to initialize locked balance of coinlist/seed investor
function updateTrancheBalance(
address beneficiary,
uint256 rawAmount,
InvestorType tranche
) external;
// ----------- Getters -----------
/// @notice Gets the TOTAL amount of Ondo available for an address
function getFreedBalance(address account) external view returns (uint96);
/// @notice Gets the initial locked balance and unlocked Ondo for an address
function getVestedBalance(address account)
external
view
returns (uint96, uint96);
}
abstract contract LinearTimelock {
struct InvestorParam {
IOndo.InvestorType investorType;
uint96 initialBalance;
}
/// @notice the timestamp at which releasing is allowed
uint256 public cliffTimestamp;
/// @notice the linear vesting period for the first tranche
uint256 public immutable tranche1VestingPeriod;
/// @notice the linear vesting period for the second tranche
uint256 public immutable tranche2VestingPeriod;
/// @notice the linear vesting period for the Seed/Series A Tranche
uint256 public immutable seedVestingPeriod;
/// @dev mapping of balances for each investor
mapping(address => InvestorParam) internal investorBalances;
/// @notice role that allows updating of tranche balances - granted to Merkle airdrop contract
bytes32 public constant TIMELOCK_UPDATE_ROLE =
keccak256("TIMELOCK_UPDATE_ROLE");
constructor(
uint256 _cliffTimestamp,
uint256 _tranche1VestingPeriod,
uint256 _tranche2VestingPeriod,
uint256 _seedVestingPeriod
) {
cliffTimestamp = _cliffTimestamp;
tranche1VestingPeriod = _tranche1VestingPeriod;
tranche2VestingPeriod = _tranche2VestingPeriod;
seedVestingPeriod = _seedVestingPeriod;
}
function passedCliff() public view returns (bool) {
return block.timestamp > cliffTimestamp;
}
/// @dev the seedVestingPeriod is the longest vesting period
function passedAllVestingPeriods() public view returns (bool) {
return block.timestamp > cliffTimestamp + seedVestingPeriod;
}
/**
@notice View function to get the user's initial balance and current amount of freed balance
*/
function getVestedBalance(address account)
external
view
returns (uint256, uint256)
{
if (investorBalances[account].initialBalance == 0) {
return (0, 0);
}
InvestorParam memory investorParam = investorBalances[account];
uint96 amountAvailable;
if (passedAllVestingPeriods()) {
amountAvailable = investorParam.initialBalance;
} else if (passedCliff()) {
(uint256 vestingPeriod, uint256 elapsed) =
_getTrancheInfo(investorParam.investorType);
amountAvailable = _proportionAvailable(
elapsed,
vestingPeriod,
investorParam
);
} else {
amountAvailable = 0;
}
return (investorParam.initialBalance, amountAvailable);
}
function _getTrancheInfo(IOndo.InvestorType investorType)
internal
view
returns (uint256 vestingPeriod, uint256 elapsed)
{
elapsed = block.timestamp - cliffTimestamp;
if (investorType == IOndo.InvestorType.CoinlistTranche1) {
elapsed = elapsed > tranche1VestingPeriod
? tranche1VestingPeriod
: elapsed;
vestingPeriod = tranche1VestingPeriod;
} else if (investorType == IOndo.InvestorType.CoinlistTranche2) {
elapsed = elapsed > tranche2VestingPeriod
? tranche2VestingPeriod
: elapsed;
vestingPeriod = tranche2VestingPeriod;
} else if (investorType == IOndo.InvestorType.SeedTranche) {
elapsed = elapsed > seedVestingPeriod ? seedVestingPeriod : elapsed;
vestingPeriod = seedVestingPeriod;
}
}
function _proportionAvailable(
uint256 elapsed,
uint256 vestingPeriod,
InvestorParam memory investorParam
) internal pure returns (uint96) {
if (investorParam.investorType == IOndo.InvestorType.SeedTranche) {
// Seed/Series A Tranche Balance = proportionAvail*2/3 + x/3, where x = Balance. This allows 1/3 of the series A balance to be unlocked at cliff
uint96 vestedAmount =
safe96(
(((investorParam.initialBalance * elapsed) / vestingPeriod) * 2) / 3,
"Ondo::_proportionAvailable: amount exceeds 96 bits"
);
return
add96(
vestedAmount,
investorParam.initialBalance / 3,
"Ondo::_proportionAvailable: overflow"
);
} else {
return
safe96(
(investorParam.initialBalance * elapsed) / vestingPeriod,
"Ondo::_proportionAvailable: amount exceeds 96 bits"
);
}
}
function safe32(uint256 n, string memory errorMessage)
internal
pure
returns (uint32)
{
require(n < 2**32, errorMessage);
return uint32(n);
}
function safe96(uint256 n, string memory errorMessage)
internal
pure
returns (uint96)
{
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(
uint96 a,
uint96 b,
string memory errorMessage
) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
}
contract Ondo is AccessControl, LinearTimelock {
/// @notice EIP-20 token name for this token
string public constant name = "Ondo";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "ONDO";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
// whether token transfers are allowed
bool public transferAllowed; // false by default
/// @notice Total number of tokens in circulation
uint256 public totalSupply = 10_000_000_000e18; // 10 billion Ondo
// Allowance amounts on behalf of others
mapping(address => mapping(address => uint96)) internal allowances;
// Official record of token balances for each account
mapping(address => uint96) internal balances;
/// @notice A record of each accounts delegate
mapping(address => address) public delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint96 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 The identifier of the role which allows special transfer privileges.
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
/// @notice A record of states for signing / validating signatures
mapping(address => uint256) public nonces;
/// @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,
uint256 previousBalance,
uint256 newBalance
);
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint256 amount);
/// @notice The standard EIP-20 approval event
event Approval(
address indexed owner,
address indexed spender,
uint256 amount
);
event CliffTimestampUpdate(uint256 newTimestamp);
/**
* @dev Emitted when the transfer is enabled triggered by `account`.
*/
event TransferEnabled(address account);
/// @notice a modifier which checks if transfers are allowed
modifier whenTransferAllowed() {
require(
transferAllowed || hasRole(TRANSFER_ROLE, msg.sender),
"OndoToken: Transfers not allowed or not right privillege"
);
_;
}
/**
* @notice Construct a new Ondo token
* @param _governance The initial account to grant owner permission and all the tokens
*/
constructor(
address _governance,
uint256 _cliffTimestamp,
uint256 _tranche1VestingPeriod,
uint256 _tranche2VestingPeriod,
uint256 _seedVestingPeriod
)
LinearTimelock(
_cliffTimestamp,
_tranche1VestingPeriod,
_tranche2VestingPeriod,
_seedVestingPeriod
)
{
balances[_governance] = uint96(totalSupply);
_setupRole(DEFAULT_ADMIN_ROLE, _governance);
_setupRole(TRANSFER_ROLE, _governance);
_setupRole(MINTER_ROLE, _governance);
emit Transfer(address(0), _governance, totalSupply);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender)
external
view
returns (uint256)
{
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
} else {
amount = safe96(rawAmount, "Ondo::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint256) {
return balances[account];
}
/**
* @notice Get the total number of UNLOCKED tokens held by the `account`
* @param account The address of the account to get the unlocked balance of
* @return The number of unlocked tokens held.
*/
function getFreedBalance(address account) external view returns (uint256) {
if (investorBalances[account].initialBalance > 0) {
return _getFreedBalance(account);
} else {
return balances[account];
}
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Ondo::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param rawAmount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(
address src,
address dst,
uint256 rawAmount
) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "Ondo::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != type(uint96).max) {
uint96 newAllowance =
sub96(
spenderAllowance,
amount,
"Ondo::transferFrom: transfer amount exceeds spender allowance"
);
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) public {
bytes32 domainSeparator =
keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
bytes32 structHash =
keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest =
keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "Ondo::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "Ondo::delegateBySig: invalid nonce");
require(
block.timestamp <= expiry,
"Ondo::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 (uint96) {
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, uint256 blockNumber)
public
view
returns (uint96)
{
require(
blockNumber < block.number,
"Ondo::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;
}
/**
* @notice Create `rawAmount` new tokens and assign them to `account`.
* @param account The address to give newly minted tokens to
* @param rawAmount Number of new tokens to mint.
* @dev Even though total token supply is uint96, we use uint256 for the amount for consistency with other external interfaces.
*/
function mint(address account, uint256 rawAmount) external {
require(hasRole(MINTER_ROLE, msg.sender), "Ondo::mint: not authorized");
require(account != address(0), "cannot mint to the zero address");
uint96 amount = safe96(rawAmount, "Ondo::mint: amount exceeds 96 bits");
uint96 supply =
safe96(totalSupply, "Ondo::mint: totalSupply exceeds 96 bits");
totalSupply = add96(supply, amount, "Ondo::mint: token supply overflow");
balances[account] = add96(
balances[account],
amount,
"Ondo::mint: balance overflow"
);
emit Transfer(address(0), account, amount);
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint96 delegatorBalance = balances[delegator];
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _transferTokens(
address src,
address dst,
uint96 amount
) internal whenTransferAllowed {
require(
src != address(0),
"Ondo::_transferTokens: cannot transfer from the zero address"
);
require(
dst != address(0),
"Ondo::_transferTokens: cannot transfer to the zero address"
);
if (investorBalances[src].initialBalance > 0) {
require(
amount <= _getFreedBalance(src),
"Ondo::_transferTokens: not enough unlocked balance"
);
}
balances[src] = sub96(
balances[src],
amount,
"Ondo::_transferTokens: transfer amount exceeds balance"
);
balances[dst] = add96(
balances[dst],
amount,
"Ondo::_transferTokens: transfer amount overflows"
);
emit Transfer(src, dst, amount);
_moveDelegates(delegates[src], delegates[dst], amount);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint96 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint96 srcRepOld =
srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint96 srcRepNew =
sub96(srcRepOld, amount, "Ondo::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint96 dstRepOld =
dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint96 dstRepNew =
add96(dstRepOld, amount, "Ondo::_moveVotes: vote amount overflows");
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint96 oldVotes,
uint96 newVotes
) internal {
uint32 blockNumber =
safe32(
block.number,
"Ondo::_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 getChainId() internal view returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @notice Turn on _transferAllowed variable. Transfers are enabled
*/
function enableTransfer() external {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Ondo::enableTransfer: not authorized"
);
transferAllowed = true;
emit TransferEnabled(msg.sender);
}
/**
* @notice Called by merkle airdrop contract to initialize locked balances
*/
function updateTrancheBalance(
address beneficiary,
uint256 rawAmount,
IOndo.InvestorType investorType
) external {
require(hasRole(TIMELOCK_UPDATE_ROLE, msg.sender));
require(rawAmount > 0, "Ondo::updateTrancheBalance: amount must be > 0");
require(
investorBalances[beneficiary].initialBalance == 0,
"Ondo::updateTrancheBalance: already has timelocked Ondo"
); //Prevents users from being in more than 1 tranche
uint96 amount =
safe96(rawAmount, "Ondo::updateTrancheBalance: amount exceeds 96 bits");
investorBalances[beneficiary] = InvestorParam(investorType, amount);
}
/**
* @notice Internal function the amount of unlocked Ondo for an account that participated in Coinlist/Seed Investments
*/
function _getFreedBalance(address account) internal view returns (uint96) {
if (passedAllVestingPeriods()) {
//all vesting periods are over, just return the total balance
return balances[account];
} else {
InvestorParam memory investorParam = investorBalances[account];
if (passedCliff()) {
//we are in between the cliff timestamp and last vesting period
(uint256 vestingPeriod, uint256 elapsed) =
_getTrancheInfo(investorParam.investorType);
uint96 lockedBalance =
sub96(
investorParam.initialBalance,
_proportionAvailable(elapsed, vestingPeriod, investorParam),
"Ondo::getFreedBalance: locked balance underflow"
);
return
sub96(
balances[account],
lockedBalance,
"Ondo::getFreedBalance: total freed balance underflow"
);
} else {
//we have not hit the cliff yet, all investor balance is locked
return
sub96(
balances[account],
investorParam.initialBalance,
"Ondo::getFreedBalance: balance underflow"
);
}
}
}
function updateCliffTimestamp(uint256 newTimestamp) external {
require(
hasRole(DEFAULT_ADMIN_ROLE, msg.sender),
"Ondo::updateCliffTimestamp: not authorized"
);
cliffTimestamp = newTimestamp;
emit CliffTimestampUpdate(newTimestamp);
}
} | * @notice Approve `spender` to transfer up to `amount` from `src` @dev This will overwrite the approval amount for `spender` @param spender The address of the account which may transfer tokens @param rawAmount The number of tokens that are approved (2^256-1 means infinite) @return Whether or not the approval succeeded/ | function approve(address spender, uint256 rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == type(uint256).max) {
amount = type(uint96).max;
amount = safe96(rawAmount, "Ondo::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
| 1,554,286 | [
1,
12053,
537,
1375,
87,
1302,
264,
68,
358,
7412,
731,
358,
1375,
8949,
68,
628,
1375,
4816,
68,
225,
1220,
903,
6156,
326,
23556,
3844,
364,
1375,
87,
1302,
264,
68,
225,
17571,
264,
1021,
1758,
434,
326,
2236,
1492,
2026,
7412,
2430,
225,
1831,
6275,
1021,
1300,
434,
2430,
716,
854,
20412,
261,
22,
66,
5034,
17,
21,
4696,
14853,
13,
327,
17403,
578,
486,
326,
23556,
15784,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
6617,
537,
12,
2867,
17571,
264,
16,
2254,
5034,
1831,
6275,
13,
3903,
1135,
261,
6430,
13,
288,
203,
565,
2254,
10525,
3844,
31,
203,
565,
309,
261,
1899,
6275,
422,
618,
12,
11890,
5034,
2934,
1896,
13,
288,
203,
1377,
3844,
273,
618,
12,
11890,
10525,
2934,
1896,
31,
203,
1377,
3844,
273,
4183,
10525,
12,
1899,
6275,
16,
315,
1398,
2896,
2866,
12908,
537,
30,
3844,
14399,
19332,
4125,
8863,
203,
565,
289,
203,
203,
565,
1699,
6872,
63,
3576,
18,
15330,
6362,
87,
1302,
264,
65,
273,
3844,
31,
203,
203,
565,
3626,
1716,
685,
1125,
12,
3576,
18,
15330,
16,
17571,
264,
16,
3844,
1769,
203,
565,
327,
638,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xEaDC218Ac4cB7895a5A56e6484646b48f841C45a/sources/MFI_ERC20.sol | ------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------ | constructor(uint256 total) public {
permit_mode=false;
symbol = "MFI";
name = "MFI_ERC20";
decimals = 18;
_totalSupply = total * 10**uint(decimals);
balances[owner] = _totalSupply;
trading_free[owner]=1;
emit Transfer(address(0), owner, _totalSupply);
}
| 3,662,592 | [
1,
29461,
11417,
8879,
17082,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
12,
11890,
5034,
2078,
13,
1071,
288,
203,
3639,
21447,
67,
3188,
33,
5743,
31,
203,
3639,
3273,
273,
315,
49,
1653,
14432,
203,
3639,
508,
273,
315,
49,
1653,
67,
654,
39,
3462,
14432,
203,
3639,
15105,
273,
6549,
31,
203,
3639,
389,
4963,
3088,
1283,
273,
2078,
380,
1728,
636,
11890,
12,
31734,
1769,
203,
3639,
324,
26488,
63,
8443,
65,
273,
389,
4963,
3088,
1283,
31,
203,
3639,
1284,
7459,
67,
9156,
63,
8443,
65,
33,
21,
31,
203,
3639,
3626,
12279,
12,
2867,
12,
20,
3631,
3410,
16,
389,
4963,
3088,
1283,
1769,
203,
565,
289,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "../TransferManager.sol";
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./ManualApprovalTransferManagerStorage.sol";
/**
* @title Transfer Manager module for manually approving transactions between accounts
*/
contract ManualApprovalTransferManager is ManualApprovalTransferManagerStorage, TransferManager {
using SafeMath for uint256;
event AddManualApproval(
address indexed _from,
address indexed _to,
uint256 _allowance,
uint256 _expiryTime,
bytes32 _description,
address indexed _addedBy
);
event ModifyManualApproval(
address indexed _from,
address indexed _to,
uint256 _expiryTime,
uint256 _allowance,
bytes32 _description,
address indexed _edittedBy
);
event RevokeManualApproval(
address indexed _from,
address indexed _to,
address indexed _addedBy
);
/**
* @notice Constructor
* @param _securityToken Address of the security token
*/
constructor(address _securityToken, address _polyToken) public Module(_securityToken, _polyToken) {
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns(bytes4) {
return bytes4(0);
}
/**
* @notice Used to verify the transfer transaction and allow a manually approved transqaction to bypass other restrictions
* @param _from Address of the sender
* @param _to Address of the receiver
* @param _amount The amount of tokens to transfer
*/
function executeTransfer(
address _from,
address _to,
uint256 _amount,
bytes calldata /* _data */
)
external
onlySecurityToken
returns(Result)
{
(Result success, bytes32 esc) = _verifyTransfer(_from, _to, _amount);
if (esc != bytes32(0)) {
uint256 index = approvalIndex[_from][_to] - 1;
ManualApproval storage approval = approvals[index];
approval.allowance = approval.allowance.sub(_amount);
}
return (success);
}
/**
* @notice Used to verify the transfer transaction and allow a manually approved transqaction to bypass other restrictions
* @param _from Address of the sender
* @param _to Address of the receiver
* @param _amount The amount of tokens to transfer
*/
function verifyTransfer(
address _from,
address _to,
uint256 _amount,
bytes memory /* _data */
)
public
view
returns(Result, bytes32)
{
return _verifyTransfer(_from, _to, _amount);
}
function _verifyTransfer(
address _from,
address _to,
uint256 _amount
)
internal
view
returns(Result, bytes32)
{
uint256 index = approvalIndex[_from][_to];
if (!paused && index != 0) {
index--; //Actual index is storedIndex - 1
ManualApproval memory approval = approvals[index];
if ((approval.expiryTime >= now) && (approval.allowance >= _amount)) {
return (Result.VALID, bytes32(uint256(address(this)) << 96));
}
}
return (Result.NA, bytes32(0));
}
/**
* @notice Adds a pair of addresses to manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
* @param _allowance is the approved amount of tokens
* @param _expiryTime is the time until which the transfer is allowed
* @param _description Description about the manual approval
*/
function addManualApproval(
address _from,
address _to,
uint256 _allowance,
uint256 _expiryTime,
bytes32 _description
)
external
withPerm(ADMIN)
{
_addManualApproval(_from, _to, _allowance, _expiryTime, _description);
}
function _addManualApproval(address _from, address _to, uint256 _allowance, uint256 _expiryTime, bytes32 _description) internal {
require(_expiryTime > now, "Invalid expiry time");
require(_allowance > 0, "Invalid allowance");
if (approvalIndex[_from][_to] != 0) {
uint256 index = approvalIndex[_from][_to] - 1;
require(approvals[index].expiryTime < now || approvals[index].allowance == 0, "Approval already exists");
_revokeManualApproval(_from, _to);
}
approvals.push(ManualApproval(_from, _to, _allowance, _expiryTime, _description));
approvalIndex[_from][_to] = approvals.length;
emit AddManualApproval(_from, _to, _allowance, _expiryTime, _description, msg.sender);
}
/**
* @notice Adds mutiple manual approvals in batch
* @param _from is the address array from which transfers are approved
* @param _to is the address array to which transfers are approved
* @param _allowances is the array of approved amounts
* @param _expiryTimes is the array of the times until which eath transfer is allowed
* @param _descriptions is the description array for these manual approvals
*/
function addManualApprovalMulti(
address[] memory _from,
address[] memory _to,
uint256[] memory _allowances,
uint256[] memory _expiryTimes,
bytes32[] memory _descriptions
)
public
withPerm(ADMIN)
{
_checkInputLengthArray(_from, _to, _allowances, _expiryTimes, _descriptions);
for (uint256 i = 0; i < _from.length; i++){
_addManualApproval(_from[i], _to[i], _allowances[i], _expiryTimes[i], _descriptions[i]);
}
}
/**
* @notice Modify the existing manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
* @param _expiryTime is the time until which the transfer is allowed
* @param _changeInAllowance is the change in allowance
* @param _description Description about the manual approval
* @param _increase tells whether the allowances will be increased (true) or decreased (false).
* or any value when there is no change in allowances
*/
function modifyManualApproval(
address _from,
address _to,
uint256 _expiryTime,
uint256 _changeInAllowance,
bytes32 _description,
bool _increase
)
external
withPerm(ADMIN)
{
_modifyManualApproval(_from, _to, _expiryTime, _changeInAllowance, _description, _increase);
}
function _modifyManualApproval(
address _from,
address _to,
uint256 _expiryTime,
uint256 _changeInAllowance,
bytes32 _description,
bool _increase
)
internal
{
/*solium-disable-next-line security/no-block-members*/
require(_expiryTime > now, "Invalid expiry time");
uint256 index = approvalIndex[_from][_to];
require(index != 0, "Approval not present");
index--; //Index is stored in an incremented form. 0 represnts non existant.
ManualApproval storage approval = approvals[index];
uint256 allowance = approval.allowance;
uint256 expiryTime = approval.expiryTime;
require(allowance != 0 && expiryTime > now, "Not allowed");
if (_changeInAllowance > 0) {
if (_increase) {
// Allowance get increased
allowance = allowance.add(_changeInAllowance);
} else {
// Allowance get decreased
if (_changeInAllowance >= allowance) {
allowance = 0;
} else {
allowance = allowance - _changeInAllowance;
}
}
approval.allowance = allowance;
}
// Greedy storage technique
if (expiryTime != _expiryTime) {
approval.expiryTime = _expiryTime;
}
if (approval.description != _description) {
approval.description = _description;
}
emit ModifyManualApproval(_from, _to, _expiryTime, allowance, _description, msg.sender);
}
/**
* @notice Adds mutiple manual approvals in batch
* @param _from is the address array from which transfers are approved
* @param _to is the address array to which transfers are approved
* @param _expiryTimes is the array of the times until which eath transfer is allowed
* @param _changeInAllowance is the array of change in allowances
* @param _descriptions is the description array for these manual approvals
* @param _increase Array of bools that tells whether the allowances will be increased (true) or decreased (false).
* or any value when there is no change in allowances
*/
function modifyManualApprovalMulti(
address[] memory _from,
address[] memory _to,
uint256[] memory _expiryTimes,
uint256[] memory _changeInAllowance,
bytes32[] memory _descriptions,
bool[] memory _increase
)
public
withPerm(ADMIN)
{
_checkInputLengthArray(_from, _to, _changeInAllowance, _expiryTimes, _descriptions);
require(_increase.length == _changeInAllowance.length, "Input length array mismatch");
for (uint256 i = 0; i < _from.length; i++) {
_modifyManualApproval(_from[i], _to[i], _expiryTimes[i], _changeInAllowance[i], _descriptions[i], _increase[i]);
}
}
/**
* @notice Removes a pairs of addresses from manual approvals
* @param _from is the address from which transfers are approved
* @param _to is the address to which transfers are approved
*/
function revokeManualApproval(address _from, address _to) external withPerm(ADMIN) {
_revokeManualApproval(_from, _to);
}
function _revokeManualApproval(address _from, address _to) internal {
uint256 index = approvalIndex[_from][_to];
require(index != 0, "Approval not exist");
// find the record in active approvals array & delete it
index--; //Index is stored after incrementation so that 0 represents non existant index
uint256 lastApprovalIndex = approvals.length - 1;
if (index != lastApprovalIndex) {
approvals[index] = approvals[lastApprovalIndex];
approvalIndex[approvals[index].from][approvals[index].to] = index + 1;
}
delete approvalIndex[_from][_to];
approvals.length--;
emit RevokeManualApproval(_from, _to, msg.sender);
}
/**
* @notice Removes mutiple pairs of addresses from manual approvals
* @param _from is the address array from which transfers are approved
* @param _to is the address array to which transfers are approved
*/
function revokeManualApprovalMulti(address[] calldata _from, address[] calldata _to) external withPerm(ADMIN) {
require(_from.length == _to.length, "Input array length mismatch");
for(uint256 i = 0; i < _from.length; i++){
_revokeManualApproval(_from[i], _to[i]);
}
}
function _checkInputLengthArray(
address[] memory _from,
address[] memory _to,
uint256[] memory _expiryTimes,
uint256[] memory _allowances,
bytes32[] memory _descriptions
)
internal
pure
{
require(_from.length == _to.length &&
_to.length == _allowances.length &&
_allowances.length == _expiryTimes.length &&
_expiryTimes.length == _descriptions.length,
"Input array length mismatch"
);
}
/**
* @notice Returns the all active approvals corresponds to an address
* @param _user Address of the holder corresponds to whom list of manual approvals
* need to return
* @return address[] addresses from
* @return address[] addresses to
* @return uint256[] allowances provided to the approvals
* @return uint256[] expiry times provided to the approvals
* @return bytes32[] descriptions provided to the approvals
*/
function getActiveApprovalsToUser(address _user) external view returns(address[] memory, address[] memory, uint256[] memory, uint256[] memory, bytes32[] memory) {
uint256 counter = 0;
uint256 approvalsLength = approvals.length;
for (uint256 i = 0; i < approvalsLength; i++) {
if ((approvals[i].from == _user || approvals[i].to == _user)
&& approvals[i].expiryTime >= now)
counter ++;
}
address[] memory from = new address[](counter);
address[] memory to = new address[](counter);
uint256[] memory allowance = new uint256[](counter);
uint256[] memory expiryTime = new uint256[](counter);
bytes32[] memory description = new bytes32[](counter);
counter = 0;
for (uint256 i = 0; i < approvalsLength; i++) {
if ((approvals[i].from == _user || approvals[i].to == _user)
&& approvals[i].expiryTime >= now) {
from[counter]=approvals[i].from;
to[counter]=approvals[i].to;
allowance[counter]=approvals[i].allowance;
expiryTime[counter]=approvals[i].expiryTime;
description[counter]=approvals[i].description;
counter ++;
}
}
return (from, to, allowance, expiryTime, description);
}
/**
* @notice Get the details of the approval corresponds to _from & _to addresses
* @param _from Address of the sender
* @param _to Address of the receiver
* @return uint256 expiryTime of the approval
* @return uint256 allowance provided to the approval
* @return uint256 Description provided to the approval
*/
function getApprovalDetails(address _from, address _to) external view returns(uint256, uint256, bytes32) {
uint256 index = approvalIndex[_from][_to];
if (index != 0) {
index--;
if (index < approvals.length) {
ManualApproval storage approval = approvals[index];
return(
approval.expiryTime,
approval.allowance,
approval.description
);
}
}
return (uint256(0), uint256(0), bytes32(0));
}
/**
* @notice Returns the current number of active approvals
*/
function getTotalApprovalsLength() external view returns(uint256) {
return approvals.length;
}
/**
* @notice Get the details of all approvals
* @return address[] addresses from
* @return address[] addresses to
* @return uint256[] allowances provided to the approvals
* @return uint256[] expiry times provided to the approvals
* @return bytes32[] descriptions provided to the approvals
*/
function getAllApprovals() external view returns(address[] memory, address[] memory, uint256[] memory, uint256[] memory, bytes32[] memory) {
uint256 approvalsLength = approvals.length;
address[] memory from = new address[](approvalsLength);
address[] memory to = new address[](approvalsLength);
uint256[] memory allowance = new uint256[](approvalsLength);
uint256[] memory expiryTime = new uint256[](approvalsLength);
bytes32[] memory description = new bytes32[](approvalsLength);
for (uint256 i = 0; i < approvalsLength; i++) {
from[i]=approvals[i].from;
to[i]=approvals[i].to;
allowance[i]=approvals[i].allowance;
expiryTime[i]=approvals[i].expiryTime;
description[i]=approvals[i].description;
}
return (from, to, allowance, expiryTime, description);
}
/**
* @notice Returns the permissions flag that are associated with ManualApproval transfer manager
*/
function getPermissions() public view returns(bytes32[] memory) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = ADMIN;
return allPermissions;
}
}
| * @notice Returns the current number of active approvals/ | function getTotalApprovalsLength() external view returns(uint256) {
return approvals.length;
}
| 13,034,598 | [
1,
1356,
326,
783,
1300,
434,
2695,
6617,
4524,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
12831,
12053,
4524,
1782,
1435,
3903,
1476,
1135,
12,
11890,
5034,
13,
288,
203,
3639,
327,
6617,
4524,
18,
2469,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/42220/0x87F1E00d6bcD3712031e5edD26DFcdB0FEd35D20/sources/contracts/ido/TegistoSaleRound1.sol | 10% of the new token
| uint256 unlocked = (_buyCurrencyAmount * exchangeRate * 10) / 10000; | 16,345,799 | [
1,
2163,
9,
434,
326,
394,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
25966,
273,
261,
67,
70,
9835,
7623,
6275,
380,
7829,
4727,
380,
1728,
13,
342,
12619,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.6.6;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./CheckToken.sol";
// ForkLaunch is a smart contract for distributing CHECK by asking user to stake the FORK token.
contract IDFO is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for CheckToken;
// Info of each user.
struct UserInfo {
uint256 amount; // How many Staking tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
uint256 bonusDebt; // Last block that user exec something to the pool.
//
// We do some fancy math here. Basically, any point in time, the amount of CHECKs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accCheckPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens:
// 1. The pool's `accCheckPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
address stakeToken; // Address of Staking token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. CHECKs to distribute per block.
uint256 lastRewardBlock; // Last block number that CHECKs distribution occurs.
uint256 accCheckPerShare; // Accumulated CHECKs per share, times 1e12. See below.
uint256 projectId;
uint256 lpSupply;
uint256 accCheckPerShareTilBonusEnd; // Accumated CHECKs per share until Bonus End.
}
// The Check TOKEN!
CheckToken public check;
// Dev address.
address public devaddr;
// CHECK tokens created per block.
uint256 public checkPerBlock;
// muliplier
uint256 public BONUS_MULTIPLIER = 1;
// Block number when bonus CHECK period ends.
uint256 public bonusEndBlock;
// Bonus lock-up in BPS
uint256 public bonusLockUpBps;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes Staking tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when CHECK mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event DepositCheckToCashPool(address indexed user, uint256 indexed pid, uint256 amount);
event CashedCheck(address indexed user, uint256 indexed pid, uint256 amount, uint256 pending);
constructor(
CheckToken _check,
address _devaddr,
uint256 _checkPerBlock,
uint256 _startBlock,
uint256 _bonusLockupBps,
uint256 _bonusEndBlock
) public {
BONUS_MULTIPLIER = 0;
totalAllocPoint = 0;
check = _check;
devaddr = _devaddr;
checkPerBlock = _checkPerBlock;
bonusLockUpBps = _bonusLockupBps;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
/**
* setting
*/
// Update dev address by the previous dev.
function setDev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function updateCheckPerBlock(uint256 _checkPerBlock) public onlyOwner {
checkPerBlock = _checkPerBlock;
}
// Set Bonus params. bonus will start to accu on the next block that this function executed
// See the calculation and counting in test file.
function setBonus(
uint256 _bonusMultiplier,
uint256 _bonusEndBlock,
uint256 _bonusLockUpBps
) public onlyOwner {
require(_bonusEndBlock > block.number, "setBonus: bad bonusEndBlock");
require(_bonusMultiplier > 1, "setBonus: bad bonusMultiplier");
BONUS_MULTIPLIER = _bonusMultiplier;
bonusEndBlock = _bonusEndBlock;
bonusLockUpBps = _bonusLockUpBps;
}
function updatePoolPorjectId(uint256 _pid, uint256 _projectId) public onlyOwner {
poolInfo[_pid].projectId = _projectId;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
function add(
uint256 _projectId,
uint256 _allocPoint,
address _stakeToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
require(_stakeToken != address(0), "add: not stakeToken addr");
// check exisit
require(!isDuplicatedPool(_projectId, _stakeToken), "add: stakeToken dup");
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({
projectId: _projectId,
stakeToken: _stakeToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accCheckPerShare: 0,
accCheckPerShareTilBonusEnd: 0,
lpSupply: 0
})
);
}
// Update the given pool's CHECK allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 prevAllocPoint = poolInfo[_pid].allocPoint;
poolInfo[_pid].allocPoint = _allocPoint;
if (prevAllocPoint != _allocPoint) {
totalAllocPoint = totalAllocPoint.sub(prevAllocPoint).add(_allocPoint);
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _lastRewardBlock, uint256 _currentBlock) public view returns (uint256) {
if (_currentBlock <= bonusEndBlock) {
return _currentBlock.sub(_lastRewardBlock).mul(BONUS_MULTIPLIER);
}
if (_lastRewardBlock >= bonusEndBlock) {
return _currentBlock.sub(_lastRewardBlock);
}
// This is the case where bonusEndBlock is in the middle of _lastRewardBlock and _currentBlock block.
return bonusEndBlock.sub(_lastRewardBlock).mul(BONUS_MULTIPLIER).add(_currentBlock.sub(bonusEndBlock));
}
/**
* core
*/
function isDuplicatedPool(uint256 _projectId, address _stakeToken) public view returns (bool) {
uint256 length = poolInfo.length;
for (uint256 _pid = 0; _pid < length; _pid++) {
if( poolInfo[_pid].projectId == _projectId && poolInfo[_pid].stakeToken == _stakeToken) return true;
}
return false;
}
// View function to see pending CHECKs on frontend.
function pendingCheck(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCheckPerShare = pool.accCheckPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 checkReward = multiplier.mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCheckPerShare = accCheckPerShare.add(checkReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCheckPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpSupply;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 checkReward = multiplier.mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
check.mint(devaddr, checkReward.div(10));
check.mint(address(this), checkReward);
pool.accCheckPerShare = pool.accCheckPerShare.add(checkReward.mul(1e12).div(lpSupply));
// update accCheckPerShareTilBonusEnd
if (block.number <= bonusEndBlock) {
check.lock(devaddr, checkReward.div(10).mul(bonusLockUpBps).div(10000));
pool.accCheckPerShareTilBonusEnd = pool.accCheckPerShare;
}
if(block.number > bonusEndBlock && pool.lastRewardBlock < bonusEndBlock) {
uint256 checkBonusPortion = bonusEndBlock.sub(pool.lastRewardBlock).mul(BONUS_MULTIPLIER).mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
check.lock(devaddr, checkBonusPortion.div(10).mul(bonusLockUpBps).div(10000));
pool.accCheckPerShareTilBonusEnd = pool.accCheckPerShareTilBonusEnd.add(checkBonusPortion.mul(1e12).div(lpSupply));
}
pool.lastRewardBlock = block.number;
}
// Deposit Staking tokens to FairLaunchToken for CHECK allocation.
function deposit(uint256 _pid, uint256 _amount) public {
require(_pid < poolInfo.length, 'pool is not existed');
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) _harvest(_pid);
IERC20(pool.stakeToken).safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
pool.lpSupply = pool.lpSupply.add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw Staking tokens from FairLaunchToken.
function withdraw(uint256 _pid, uint256 _amount) public {
_withdraw(_pid, _amount);
}
function withdrawAll(uint256 _pid) public {
_withdraw(_pid, userInfo[_pid][msg.sender].amount);
}
function _withdraw(uint256 _pid, uint256 _amount) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
_harvest(_pid);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
pool.lpSupply = pool.lpSupply.sub(_amount);
if (pool.stakeToken != address(0)) {
IERC20(pool.stakeToken).safeTransfer(address(msg.sender), _amount);
}
emit Withdraw(msg.sender, _pid, _amount);
}
// Harvest CHECKs earn from the pool.
function harvest(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
_harvest(_pid);
user.rewardDebt = user.amount.mul(pool.accCheckPerShare).div(1e12);
user.bonusDebt = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12);
}
function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount > 0, "nothing to harvest");
uint256 pending = user.amount.mul(pool.accCheckPerShare).div(1e12).sub(user.rewardDebt);
require(pending <= check.balanceOf(address(this)), "wtf not enough check");
uint256 bonus = user.amount.mul(pool.accCheckPerShareTilBonusEnd).div(1e12).sub(user.bonusDebt);
_safeCheckTransfer(msg.sender, pending);
check.lock(msg.sender, bonus.mul(bonusLockUpBps).div(10000));
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
IERC20(pool.stakeToken).safeTransfer(address(msg.sender), user.amount);
user.amount = 0;
user.rewardDebt = 0;
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
}
// Safe check transfer function, just in case if rounding error causes pool to not have enough CHECKs.
function _safeCheckTransfer(address _to, uint256 _amount) internal {
uint256 checkBal = check.balanceOf(address(this));
if (_amount > checkBal) {
check.transfer(_to, checkBal);
} else {
check.transfer(_to, _amount);
}
}
}
| View function to see pending CHECKs on frontend. | function pendingCheck(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accCheckPerShare = pool.accCheckPerShare;
uint256 lpSupply = pool.lpSupply;
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 checkReward = multiplier.mul(checkPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accCheckPerShare = accCheckPerShare.add(checkReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accCheckPerShare).div(1e12).sub(user.rewardDebt);
}
| 2,491,824 | [
1,
1767,
445,
358,
2621,
4634,
14565,
87,
603,
15442,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
4634,
1564,
12,
11890,
5034,
389,
6610,
16,
1758,
389,
1355,
13,
3903,
225,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
565,
8828,
966,
2502,
2845,
273,
2845,
966,
63,
67,
6610,
15533,
203,
565,
25003,
2502,
729,
273,
16753,
63,
67,
6610,
6362,
67,
1355,
15533,
203,
565,
2254,
5034,
4078,
1564,
2173,
9535,
273,
2845,
18,
8981,
1564,
2173,
9535,
31,
203,
565,
2254,
5034,
12423,
3088,
1283,
273,
2845,
18,
9953,
3088,
1283,
31,
203,
565,
309,
261,
2629,
18,
2696,
405,
2845,
18,
2722,
17631,
1060,
1768,
597,
12423,
3088,
1283,
480,
374,
13,
288,
203,
1377,
2254,
5034,
15027,
273,
31863,
5742,
12,
6011,
18,
2722,
17631,
1060,
1768,
16,
1203,
18,
2696,
1769,
203,
1377,
2254,
5034,
866,
17631,
1060,
273,
15027,
18,
16411,
12,
1893,
2173,
1768,
2934,
16411,
12,
6011,
18,
9853,
2148,
2934,
2892,
12,
4963,
8763,
2148,
1769,
203,
1377,
4078,
1564,
2173,
9535,
273,
4078,
1564,
2173,
9535,
18,
1289,
12,
1893,
17631,
1060,
18,
16411,
12,
21,
73,
2138,
2934,
2892,
12,
9953,
3088,
1283,
10019,
203,
565,
289,
203,
565,
327,
729,
18,
8949,
18,
16411,
12,
8981,
1564,
2173,
9535,
2934,
2892,
12,
21,
73,
2138,
2934,
1717,
12,
1355,
18,
266,
2913,
758,
23602,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x0077fAb25bc54A61444b3f29b23C72e31044e802/sources/CatXStaking.sol | * @notice Withdraw both staked tokens and rewards from the 90 days staking pool @dev can only withdraw after the unlock time/ | function withdrawNinetyDays() external {
uint256 currentTime = block.timestamp;
if(stakesNinety[msg.sender].stakedAmount == 0)
revert NothingToWithdraw();
if (currentTime <= stakesNinety[msg.sender].unlockTime)
revert StakingPeriodNotOver();
uint256 transferAmount = stakesNinety[msg.sender].stakedAmount + stakesNinety[msg.sender].userReward;
stakesNinety[msg.sender].stakedAmount = 0;
stakesNinety[msg.sender].userReward = 0;
ercToken.transfer(msg.sender, transferAmount);
emit Withdrawn(msg.sender, transferAmount);
}
| 3,081,984 | [
1,
1190,
9446,
3937,
384,
9477,
2430,
471,
283,
6397,
628,
326,
8566,
4681,
384,
6159,
2845,
225,
848,
1338,
598,
9446,
1839,
326,
7186,
813,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
50,
267,
14369,
9384,
1435,
3903,
288,
203,
3639,
2254,
5034,
6680,
273,
1203,
18,
5508,
31,
203,
203,
3639,
309,
12,
334,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
334,
9477,
6275,
422,
374,
13,
203,
5411,
15226,
13389,
774,
1190,
9446,
5621,
203,
203,
3639,
309,
261,
2972,
950,
1648,
384,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
26226,
950,
13,
203,
5411,
15226,
934,
6159,
5027,
1248,
4851,
5621,
203,
203,
3639,
2254,
5034,
7412,
6275,
273,
384,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
334,
9477,
6275,
397,
384,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
1355,
17631,
1060,
31,
203,
3639,
384,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
334,
9477,
6275,
273,
374,
31,
203,
3639,
384,
3223,
50,
267,
14369,
63,
3576,
18,
15330,
8009,
1355,
17631,
1060,
273,
374,
31,
203,
203,
3639,
6445,
71,
1345,
18,
13866,
12,
3576,
18,
15330,
16,
7412,
6275,
1769,
203,
203,
3639,
3626,
3423,
9446,
82,
12,
3576,
18,
15330,
16,
7412,
6275,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.5.0;
import "./AbstractSingularDTVToken.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title Fund contract - Implements reward distribution.
/// @author Stefan George - <[email protected]>
/// @author Milad Mostavi - <[email protected]>
contract SingularDTVFund is Ownable {
using SafeMath for uint256;
/*
* External contracts
*/
AbstractSingularDTVToken public singularDTVToken;
/*
* Structs
*/
struct RewardsData {
bool isPermittedToken;
uint256 tokenInd;
uint256 totalReward;
// User's address => Reward at time of withdraw
mapping(address => uint256) rewardAtTimeOfWithdraw;
// User's address => Reward which can be withdrawn
mapping(address => uint256) owed;
}
/*
* Storage
*/
string public version = "0.1.0";
RewardsData public ethRewards;
// Token's address => rewards data
mapping(address => RewardsData) public tokensRewards;
address[] public tokensAddresses;
uint256 constant MAX_NUMBER_OF_TOKENS = 10;
/*
* Events
*/
event BlacklistToken(address tokenAddress, uint256 tokenInd);
event WhitelistToken(address tokenAddress, uint256 tokenInd);
/*
* Contract functions
*/
/// @dev Fallback function acts as depositReward()
function() external payable {
if (msg.value == 0) {
withdrawRewardInEth();
} else {
depositRewardInEth();
}
}
/// @dev Getter for ethRewards.owed[userAddress]
/// @param userAddress User's address
function getEthOwedFor(address userAddress) public view returns (uint256) {
return ethRewards.owed[userAddress];
}
/// @dev Getter for ethRewards.rewardAtTimeOfWithdraw[userAddress]
/// @param userAddress User's address
function getEthRewardAtTimeOfWithdrawFor(address userAddress)
public
view
returns (uint256)
{
return ethRewards.rewardAtTimeOfWithdraw[userAddress];
}
/// @dev Getter for tokensRewards[tokenAddress].owed[userAddress]
/// @param tokenAddress address of token
/// @param userAddress User's address
function getTokenOwedFor(address tokenAddress, address userAddress)
public
view
returns (uint256)
{
return tokensRewards[tokenAddress].owed[userAddress];
}
/// @dev Getter for tokensRewards[tokenAddress].rewardAtTimeOfWithdraw[userAddress]
/// @param tokenAddress address of token
/// @param userAddress User's address
function getTokenRewardAtTimeOfWithdrawFor(
address tokenAddress,
address userAddress
) public view returns (uint256) {
return tokensRewards[tokenAddress].rewardAtTimeOfWithdraw[userAddress];
}
/// @dev Getter for tokensAddresses.length
function getTokensAddressesLength() public view returns (uint256) {
return tokensAddresses.length;
}
/// @dev Only owner can whitelist token
/// @param _tokenAddress Token address
function whitelistToken(address _tokenAddress)
external
onlyOwner
returns (bool)
{
require(
tokensAddresses.length < MAX_NUMBER_OF_TOKENS,
"whitelistToken: Can't add more tokens addresses."
);
uint256 tokenInd = tokensRewards[_tokenAddress].tokenInd;
if (
!(tokensRewards[_tokenAddress].isPermittedToken &&
tokensAddresses.length > 0 &&
tokensAddresses[tokenInd] == _tokenAddress)
) {
tokensRewards[_tokenAddress].isPermittedToken = true;
tokenInd = tokensAddresses.length;
tokensRewards[_tokenAddress].tokenInd = tokenInd;
emit WhitelistToken(
_tokenAddress,
tokensRewards[_tokenAddress].tokenInd
);
tokensAddresses.push(_tokenAddress);
return true;
}
return false;
}
/// @dev Only owner can blacklist token
/// @param _tokenAddress Token address
function blacklistToken(address _tokenAddress)
external
onlyOwner
returns (bool)
{
uint256 tokenInd = tokensRewards[_tokenAddress].tokenInd;
if (
tokensRewards[_tokenAddress].isPermittedToken &&
tokensAddresses.length > 0 &&
tokensAddresses[tokenInd] == _tokenAddress
) {
tokensRewards[_tokenAddress].isPermittedToken = false;
//if token address already exists we delete it from the list
if (tokenInd == tokensAddresses.length - 1) {
//if this address is in the end of list we just pop() it
tokensAddresses.pop();
tokensRewards[_tokenAddress].tokenInd = 0;
} else {
//if it's not in the end we swap it with last element and then pop()
tokensAddresses[tokenInd] = tokensAddresses[tokensAddresses.length - 1];
tokensAddresses.pop();
tokensRewards[_tokenAddress].tokenInd = 0;
}
emit BlacklistToken(
_tokenAddress,
tokensRewards[_tokenAddress].tokenInd
);
return true;
}
return false;
}
/// @dev Credits reward to owed balance.
/// @param _forAddress user's address.
function softWithdrawRewardFor(address _forAddress)
external
returns (bool)
{
//Eth withdraw
uint256 value = calcReward(_forAddress, ethRewards);
ethRewards.rewardAtTimeOfWithdraw[_forAddress] = ethRewards.totalReward;
ethRewards.owed[_forAddress] = ethRewards.owed[_forAddress].add(value);
//tokens withdraw
for (uint256 i = 0; i < tokensAddresses.length; i++) {
RewardsData storage tokenRewards = tokensRewards[tokensAddresses[i]];
value = calcReward(_forAddress, tokenRewards);
tokenRewards.rewardAtTimeOfWithdraw[_forAddress] = tokenRewards
.totalReward;
tokenRewards.owed[_forAddress] = tokenRewards.owed[_forAddress].add(
value
);
}
}
/// @dev Setup function sets external token address.
/// @param _singularDTVTokenAddress Token address.
function setTokenAddress(address _singularDTVTokenAddress)
external
onlyOwner
returns (bool)
{
if (address(singularDTVToken) == address(0)) {
singularDTVToken = AbstractSingularDTVToken(
_singularDTVTokenAddress
);
return true;
}
return false;
}
/// @dev Withdraws reward for user. Returns reward.
function withdrawRewardInEth() public returns (uint256) {
uint256 value = calcReward(msg.sender, ethRewards).add(
ethRewards.owed[msg.sender]
);
ethRewards.rewardAtTimeOfWithdraw[msg.sender] = ethRewards.totalReward;
ethRewards.owed[msg.sender] = 0;
if (value > 0 && !msg.sender.send(value)) {
revert();
}
return value;
}
/// @dev Withdraws reward for user in tokens. Returns reward.
/// @param _tokensAddress address of withdrawing token
function withdrawRewardInToken(address _tokensAddress)
public
returns (uint256)
{
RewardsData storage tokenRewards = tokensRewards[_tokensAddress];
require(
tokenRewards.isPermittedToken,
"Withdraw rewards in token: Got unpermitted token"
);
uint256 value = calcReward(msg.sender, tokenRewards).add(
tokenRewards.owed[msg.sender]
);
tokenRewards.rewardAtTimeOfWithdraw[msg.sender] = tokenRewards.totalReward;
tokenRewards.owed[msg.sender] = 0;
IERC20 tokenContract = IERC20(_tokensAddress);
if (value > 0 && !tokenContract.transfer(msg.sender, value)) {
revert();
}
return value;
}
/// @dev Withdraws reward for user in Eth and all tokens
function withdrawRewardInAll() public {
withdrawRewardInEth();
for (uint256 i = 0; i < tokensAddresses.length; i++) {
withdrawRewardInToken(tokensAddresses[i]);
}
}
/// @dev Deposits reward in Eth. Returns success.
function depositRewardInEth() public payable returns (bool) {
ethRewards.totalReward = ethRewards.totalReward.add(msg.value);
return true;
}
/// @dev Deposits reward in token. Returns success.
/// @param _tokenAddress Address of depositing token
/// @param _amount Amount of depositing token
function depositRewardInToken(address _tokenAddress, uint256 _amount)
public
returns (bool)
{
RewardsData storage tokenRewards = tokensRewards[_tokenAddress];
require(
tokenRewards.isPermittedToken,
"Deposit in token: Got unpermitted token address"
);
IERC20 tokenContract = IERC20(_tokenAddress);
require(
tokenContract.transferFrom(msg.sender, address(this), _amount),
"Deposit in token: Can`t transfer tokens to Fund address"
);
tokenRewards.totalReward = tokenRewards.totalReward.add(_amount);
return true;
}
/// @dev Withdraws reward for user. Returns reward.
/// @param _forAddress user's address.
/// @param _rewards RewardsData where the reward will come from
function calcReward(address _forAddress, RewardsData storage _rewards)
private
view
returns (uint256)
{
return singularDTVToken.balanceOf(_forAddress)
.mul(
_rewards.totalReward.sub(
_rewards.rewardAtTimeOfWithdraw[_forAddress]
))
.div(singularDTVToken.totalSupply());
}
}
| @dev Deposits reward in token. Returns success. @param _tokenAddress Address of depositing token @param _amount Amount of depositing token | function depositRewardInToken(address _tokenAddress, uint256 _amount)
public
returns (bool)
{
RewardsData storage tokenRewards = tokensRewards[_tokenAddress];
require(
tokenRewards.isPermittedToken,
"Deposit in token: Got unpermitted token address"
);
IERC20 tokenContract = IERC20(_tokenAddress);
require(
tokenContract.transferFrom(msg.sender, address(this), _amount),
"Deposit in token: Can`t transfer tokens to Fund address"
);
tokenRewards.totalReward = tokenRewards.totalReward.add(_amount);
return true;
}
| 1,754,610 | [
1,
758,
917,
1282,
19890,
316,
1147,
18,
2860,
2216,
18,
225,
389,
2316,
1887,
5267,
434,
443,
1724,
310,
1147,
225,
389,
8949,
16811,
434,
443,
1724,
310,
1147,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
17631,
1060,
382,
1345,
12,
2867,
389,
2316,
1887,
16,
2254,
5034,
389,
8949,
13,
203,
3639,
1071,
203,
3639,
1135,
261,
6430,
13,
203,
565,
288,
203,
3639,
534,
359,
14727,
751,
2502,
1147,
17631,
14727,
273,
2430,
17631,
14727,
63,
67,
2316,
1887,
15533,
203,
3639,
2583,
12,
203,
5411,
1147,
17631,
14727,
18,
291,
31465,
1345,
16,
203,
5411,
315,
758,
1724,
316,
1147,
30,
19578,
640,
457,
7948,
1147,
1758,
6,
203,
3639,
11272,
203,
3639,
467,
654,
39,
3462,
1147,
8924,
273,
467,
654,
39,
3462,
24899,
2316,
1887,
1769,
203,
3639,
2583,
12,
203,
5411,
1147,
8924,
18,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
389,
8949,
3631,
203,
5411,
315,
758,
1724,
316,
1147,
30,
4480,
68,
88,
7412,
2430,
358,
478,
1074,
1758,
6,
203,
3639,
11272,
203,
3639,
1147,
17631,
14727,
18,
4963,
17631,
1060,
273,
1147,
17631,
14727,
18,
4963,
17631,
1060,
18,
1289,
24899,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x45A7172801842af0f7b4e5bBfD1F3b00B0856Bbb/sources/StabinolToken.sol | Stabilize Token with Governance. Variables | contract StabinolToken is ERC20("Stabinol Token", "STOL"), Ownable {
using SafeMath for uint256;
uint256 constant DIVISION_FACTOR = 100000;
constructor() public {
_mint(_msgSender(), 799800e18);
}
modifier onlyClaimer() {
require(claimerAddress == _msgSender(), "Ownable: caller is not the claimer");
_;
}
function getMaxSupply() external pure returns (uint256) {
return MAX_SUPPLY;
}
function mint(address _to, uint256 _amount) external onlyClaimer returns (bool) {
_mint(_to, _amount);
return true;
}
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override returns (uint256) {
if(taxRate > 0 && totalSupply() > TAX_EFFECTIVE){
uint256 taxAmount = amount.mul(taxRate).div(DIVISION_FACTOR);
if(taxAmount.add(amount) > balanceOf(from)){
amount = amount.sub(overage);
}
_tax(from,taxAmount);
}
return amount;
}
address private _timelock_address;
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override returns (uint256) {
if(taxRate > 0 && totalSupply() > TAX_EFFECTIVE){
uint256 taxAmount = amount.mul(taxRate).div(DIVISION_FACTOR);
if(taxAmount.add(amount) > balanceOf(from)){
amount = amount.sub(overage);
}
_tax(from,taxAmount);
}
return amount;
}
address private _timelock_address;
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override returns (uint256) {
if(taxRate > 0 && totalSupply() > TAX_EFFECTIVE){
uint256 taxAmount = amount.mul(taxRate).div(DIVISION_FACTOR);
if(taxAmount.add(amount) > balanceOf(from)){
amount = amount.sub(overage);
}
_tax(from,taxAmount);
}
return amount;
}
address private _timelock_address;
uint256 private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
if(claimerAddress != address(0)){
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
if(claimerAddress != address(0)){
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
function startChangeGovernance(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishChangeGovernance() external onlyGovernance timelockConditionsMet(1) {
_transferGovernance(_timelock_address);
}
function startChangeTaxRate(uint256 _percent) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_data = _percent;
}
function finishChangeTaxRate() external onlyGovernance timelockConditionsMet(2) {
taxRate = _timelock_data;
}
function startChangeClaimer(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeClaimer() external onlyGovernance timelockConditionsMet(3) {
taxExemptAccounts[_timelock_address] = true;
_setClaimer(_timelock_address);
}
function startToggleTaxExempt(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishToggleTaxExempt() external onlyGovernance timelockConditionsMet(4) {
if(taxExemptAccounts[_timelock_address] == true){
taxExemptAccounts[_timelock_address] = false;
taxExemptAccounts[_timelock_address] = true;
}
}
function finishToggleTaxExempt() external onlyGovernance timelockConditionsMet(4) {
if(taxExemptAccounts[_timelock_address] == true){
taxExemptAccounts[_timelock_address] = false;
taxExemptAccounts[_timelock_address] = true;
}
}
}else{
} | 8,877,944 | [
1,
510,
22681,
554,
3155,
598,
611,
1643,
82,
1359,
18,
23536,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
934,
378,
267,
355,
1345,
353,
4232,
39,
3462,
2932,
510,
378,
267,
355,
3155,
3113,
315,
882,
1741,
6,
3631,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
203,
565,
2254,
5034,
5381,
3690,
25216,
67,
26835,
273,
25259,
31,
203,
377,
203,
377,
203,
203,
565,
3885,
1435,
1071,
288,
203,
3639,
389,
81,
474,
24899,
3576,
12021,
9334,
2371,
2733,
17374,
73,
2643,
1769,
203,
565,
289,
203,
203,
565,
9606,
1338,
2009,
69,
4417,
1435,
288,
203,
3639,
2583,
12,
830,
69,
4417,
1887,
422,
389,
3576,
12021,
9334,
315,
5460,
429,
30,
4894,
353,
486,
326,
927,
69,
4417,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
203,
565,
445,
7288,
3088,
1283,
1435,
3903,
16618,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
4552,
67,
13272,
23893,
31,
203,
565,
289,
203,
377,
203,
565,
445,
312,
474,
12,
2867,
389,
869,
16,
2254,
5034,
389,
8949,
13,
3903,
1338,
2009,
69,
4417,
1135,
261,
6430,
13,
288,
203,
3639,
389,
81,
474,
24899,
869,
16,
389,
8949,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
565,
445,
389,
5771,
1345,
5912,
12,
2867,
628,
16,
1758,
358,
16,
2254,
5034,
3844,
13,
2713,
5024,
3849,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
309,
12,
8066,
4727,
405,
374,
597,
2078,
3088,
1283,
1435,
405,
399,
2501,
67,
31299,
4239,
5354,
15329,
203,
5411,
2254,
5034,
5320,
6275,
273,
3844,
18,
16411,
12,
8066,
4727,
2934,
2
] |
./partial_match/1/0xc8a2ADC4261c6b669CdFf69E717E77C9cFeB420d/sources/src/contracts/GovernanceCore.sol | * @notice method to remove specified decimals from a value, as to normalize it. @param value number to remove decimals from @return normalized value/ | function _normalize(uint256 value) internal pure returns (uint56) {
uint256 normalizedValue = value / PRECISION_DIVIDER;
return normalizedValue.toUint56();
}
| 15,500,904 | [
1,
2039,
358,
1206,
1269,
15105,
628,
279,
460,
16,
487,
358,
3883,
518,
18,
225,
460,
1300,
358,
1206,
15105,
628,
327,
5640,
460,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
12237,
12,
11890,
5034,
460,
13,
2713,
16618,
1135,
261,
11890,
4313,
13,
288,
203,
565,
2254,
5034,
5640,
620,
273,
460,
342,
7071,
26913,
67,
2565,
20059,
31,
203,
565,
327,
5640,
620,
18,
869,
5487,
4313,
5621,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity =0.8.7;
interface IERC20Like {
function approve(address spender_, uint256 amount_) external returns (bool success_);
function balanceOf(address account_) external view returns (uint256 balance_);
function transfer(address recipient_, uint256 amount_) external returns (bool success_);
function transferFrom(address owner_, address recipient_, uint256 amount_) external returns (bool success_);
}
interface ILenderLike {
function poolDelegate() external view returns (address poolDelegate_);
}
interface IMapleGlobalsLike {
function investorFee() external view returns (uint256 investorFee_);
function mapleTreasury() external view returns (address mapleTreasury_);
function protocolPaused() external view returns (bool paused_);
function treasuryFee() external view returns (uint256 treasuryFee_);
}
interface IMapleProxyFactoryLike {
function mapleGlobals() external view returns (address mapleGlobals_);
function upgradeInstance(uint256 toVersion_, bytes calldata arguments_) external;
}
/// @title Small Library to standardize erc20 token interactions.
library ERC20Helper {
/**************************/
/*** Internal Functions ***/
/**************************/
function transfer(address token_, address to_, uint256 amount_) internal returns (bool success_) {
return _call(token_, abi.encodeWithSelector(IERC20Like.transfer.selector, to_, amount_));
}
function transferFrom(address token_, address from_, address to_, uint256 amount_) internal returns (bool success_) {
return _call(token_, abi.encodeWithSelector(IERC20Like.transferFrom.selector, from_, to_, amount_));
}
function approve(address token_, address spender_, uint256 amount_) internal returns (bool success_) {
// If setting approval to zero fails, return false.
if (!_call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, uint256(0)))) return false;
// If `amount_` is zero, return true as the previous step already did this.
if (amount_ == uint256(0)) return true;
// Return the result of setting the approval to `amount_`.
return _call(token_, abi.encodeWithSelector(IERC20Like.approve.selector, spender_, amount_));
}
function _call(address token_, bytes memory data_) private returns (bool success_) {
if (token_.code.length == uint256(0)) return false;
bytes memory returnData;
( success_, returnData ) = token_.call(data_);
return success_ && (returnData.length == uint256(0) || abi.decode(returnData, (bool)));
}
}
/// @title An implementation that is to be proxied, must implement IProxied.
interface IProxied {
/**
* @dev The address of the proxy factory.
*/
function factory() external view returns (address factory_);
/**
* @dev The address of the implementation contract being proxied.
*/
function implementation() external view returns (address implementation_);
/**
* @dev Modifies the proxy's implementation address.
* @param newImplementation_ The address of an implementation contract.
*/
function setImplementation(address newImplementation_) external;
/**
* @dev Modifies the proxy's storage by delegate-calling a migrator contract with some arguments.
* Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled.
* @param migrator_ The address of a migrator contract.
* @param arguments_ Some encoded arguments to use for the migration.
*/
function migrate(address migrator_, bytes calldata arguments_) external;
}
/// @title A Maple implementation that is to be proxied, must implement IMapleProxied.
interface IMapleProxied is IProxied {
/**
* @dev The instance was upgraded.
* @param toVersion_ The new version of the loan.
* @param arguments_ The upgrade arguments, if any.
*/
event Upgraded(uint256 toVersion_, bytes arguments_);
/**
* @dev Upgrades a contract implementation to a specific version.
* Access control logic critical since caller can force a selfdestruct via a malicious `migrator_` which is delegatecalled.
* @param toVersion_ The version to upgrade to.
* @param arguments_ Some encoded arguments to use for the upgrade.
*/
function upgrade(uint256 toVersion_, bytes calldata arguments_) external;
}
/// @title IMapleLoanEvents defines the events for a MapleLoan.
interface IMapleLoanEvents {
/**
* @dev Borrower was accepted, and set to a new account.
* @param borrower_ The address of the new borrower.
*/
event BorrowerAccepted(address indexed borrower_);
/**
* @dev Collateral was posted.
* @param amount_ The amount of collateral posted.
*/
event CollateralPosted(uint256 amount_);
/**
* @dev Collateral was removed.
* @param amount_ The amount of collateral removed.
* @param destination_ The recipient of the collateral removed.
*/
event CollateralRemoved(uint256 amount_, address indexed destination_);
/**
* @dev The loan was funded.
* @param lender_ The address of the lender.
* @param amount_ The amount funded.
* @param nextPaymentDueDate_ The due date of the next payment.
*/
event Funded(address indexed lender_, uint256 amount_, uint256 nextPaymentDueDate_);
/**
* @dev Funds were claimed.
* @param amount_ The amount of funds claimed.
* @param destination_ The recipient of the funds claimed.
*/
event FundsClaimed(uint256 amount_, address indexed destination_);
/**
* @dev Funds were drawn.
* @param amount_ The amount of funds drawn.
* @param destination_ The recipient of the funds drawn down.
*/
event FundsDrawnDown(uint256 amount_, address indexed destination_);
/**
* @dev Funds were redirected on an additional `fundLoan` call.
* @param amount_ The amount of funds redirected.
* @param destination_ The recipient of the redirected funds.
*/
event FundsRedirected(uint256 amount_, address indexed destination_);
/**
* @dev Funds were returned.
* @param amount_ The amount of funds returned.
*/
event FundsReturned(uint256 amount_);
/**
* @dev The loan was initialized.
* @param borrower_ The address of the borrower.
* @param assets_ Array of asset addresses.
* [0]: collateralAsset,
* [1]: fundsAsset.
* @param termDetails_ Array of loan parameters:
* [0]: gracePeriod,
* [1]: paymentInterval,
* [2]: payments,
* @param amounts_ Requested amounts:
* [0]: collateralRequired,
* [1]: principalRequested,
* [2]: endingPrincipal.
* @param rates_ Fee parameters:
* [0]: interestRate,
* [1]: earlyFeeRate,
* [2]: lateFeeRate,
* [3]: lateInterestPremium.
*/
event Initialized(address indexed borrower_, address[2] assets_, uint256[3] termDetails_, uint256[3] amounts_, uint256[4] rates_);
/**
* @dev Lender was accepted, and set to a new account.
* @param lender_ The address of the new lender.
*/
event LenderAccepted(address indexed lender_);
/**
* @dev Loan was repaid early and closed.
* @param principalPaid_ The portion of the total amount that went towards principal.
* @param interestPaid_ The portion of the total amount that went towards interest fees.
*/
event LoanClosed(uint256 principalPaid_, uint256 interestPaid_);
/**
* @dev A refinance was proposed.
* @param refinanceCommitment_ The hash of the refinancer and calls proposed.
* @param refinancer_ The address that will execute the refinance.
* @param calls_ The individual calls for the refinancer contract.
*/
event NewTermsAccepted(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_);
/**
* @dev A refinance was proposed.
* @param refinanceCommitment_ The hash of the refinancer and calls proposed.
* @param refinancer_ The address that will execute the refinance.
* @param calls_ The individual calls for the refinancer contract.
*/
event NewTermsProposed(bytes32 refinanceCommitment_, address refinancer_, bytes[] calls_);
/**
* @dev Payments were made.
* @param principalPaid_ The portion of the total amount that went towards principal.
* @param interestPaid_ The portion of the total amount that went towards interest fees.
*/
event PaymentMade(uint256 principalPaid_, uint256 interestPaid_);
/**
* @dev Pending borrower was set.
* @param pendingBorrower_ Address that can accept the borrower role.
*/
event PendingBorrowerSet(address pendingBorrower_);
/**
* @dev Pending lender was set.
* @param pendingLender_ Address that can accept the lender role.
*/
event PendingLenderSet(address pendingLender_);
/**
* @dev The loan was in default and funds and collateral was repossessed by the lender.
* @param collateralRepossessed_ The amount of collateral asset repossessed.
* @param fundsRepossessed_ The amount of funds asset repossessed.
* @param destination_ The recipient of the collateral and funds, if any.
*/
event Repossessed(uint256 collateralRepossessed_, uint256 fundsRepossessed_, address indexed destination_);
/**
* @dev Some token (neither fundsAsset nor collateralAsset) was removed from the loan.
* @param token_ The address of the token contract.
* @param amount_ The amount of token remove from the loan.
* @param destination_ The recipient of the token.
*/
event Skimmed(address indexed token_, uint256 amount_, address indexed destination_);
}
/// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied.
interface IMapleLoan is IMapleProxied, IMapleLoanEvents {
/***********************/
/*** State Variables ***/
/***********************/
/**
* @dev The borrower of the loan, responsible for repayments.
*/
function borrower() external view returns (address borrower_);
/**
* @dev The amount of funds that have yet to be claimed by the lender.
*/
function claimableFunds() external view returns (uint256 claimableFunds_);
/**
* @dev The amount of collateral posted against outstanding (drawn down) principal.
*/
function collateral() external view returns (uint256 collateral_);
/**
* @dev The address of the asset deposited by the borrower as collateral, if needed.
*/
function collateralAsset() external view returns (address collateralAsset_);
/**
* @dev The amount of collateral required if all of the principal required is drawn down.
*/
function collateralRequired() external view returns (uint256 collateralRequired_);
/**
* @dev The amount of funds that have yet to be drawn down by the borrower.
*/
function drawableFunds() external view returns (uint256 drawableFunds_);
/**
* @dev The rate charged at early payments.
* This value should be configured so that it is less expensive to close a loan with more than one payment remaining, but
* more expensive to close it if on the last payment.
*/
function earlyFeeRate() external view returns (uint256 earlyFeeRate_);
/**
* @dev The portion of principal to not be paid down as part of payment installments, which would need to be paid back upon final payment.
* If endingPrincipal = principal, loan is interest-only.
*/
function endingPrincipal() external view returns (uint256 endingPrincipal_);
/**
* @dev The asset deposited by the lender to fund the loan.
*/
function fundsAsset() external view returns (address fundsAsset_);
/**
* @dev The amount of time the borrower has, after a payment is due, to make a payment before being in default.
*/
function gracePeriod() external view returns (uint256 gracePeriod_);
/**
* @dev The annualized interest rate (APR), in units of 1e18, (i.e. 1% is 0.01e18).
*/
function interestRate() external view returns (uint256 interestRate_);
/**
* @dev The rate charged at late payments.
*/
function lateFeeRate() external view returns (uint256 lateFeeRate_);
/**
* @dev The premium over the regular interest rate applied when paying late.
*/
function lateInterestPremium() external view returns (uint256 lateInterestPremium_);
/**
* @dev The lender of the Loan.
*/
function lender() external view returns (address lender_);
/**
* @dev The timestamp due date of the next payment.
*/
function nextPaymentDueDate() external view returns (uint256 nextPaymentDueDate_);
/**
* @dev The specified time between loan payments.
*/
function paymentInterval() external view returns (uint256 paymentInterval_);
/**
* @dev The number of payment installments remaining for the loan.
*/
function paymentsRemaining() external view returns (uint256 paymentsRemaining_);
/**
* @dev The address of the pending borrower.
*/
function pendingBorrower() external view returns (address pendingBorrower_);
/**
* @dev The address of the pending lender.
*/
function pendingLender() external view returns (address pendingLender_);
/**
* @dev The amount of principal owed (initially, the requested amount), which needs to be paid back.
*/
function principal() external view returns (uint256 principal_);
/**
* @dev The initial principal amount requested by the borrower.
*/
function principalRequested() external view returns (uint256 principalRequested_);
/**
* @dev The factory address that deployed this contract (necessary for PoolV1 integration).
*/
function superFactory() external view returns (address superFactory_);
/********************************/
/*** State Changing Functions ***/
/********************************/
/**
* @dev Accept the borrower role, must be called by pendingBorrower.
*/
function acceptBorrower() external;
/**
* @dev Accept the lender role, must be called by pendingLender.
*/
function acceptLender() external;
/**
* @dev Accept the proposed terms ans trigger refinance execution
* @param refinancer_ The address of the refinancer contract.
* @param calls_ The encoded arguments to be passed to refinancer.
* @param amount_ An amount to pull from the caller, if any.
*/
function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external;
/**
* @dev Claim funds that have been paid (principal, interest, and late fees).
* @param amount_ The amount to be claimed.
* @param destination_ The address to send the funds.
*/
function claimFunds(uint256 amount_, address destination_) external;
/**
* @dev Repay all principal and fees and close a loan.
* @param amount_ An amount to pull from the caller, if any.
* @return principal_ The portion of the amount paid paying back principal.
* @return interest_ The portion of the amount paid paying interest fees.
*/
function closeLoan(uint256 amount_) external returns (uint256 principal_, uint256 interest_);
/**
* @dev Draw down funds from the loan.
* @param amount_ The amount to draw down.
* @param destination_ The address to send the funds.
* @return collateralPosted_ The amount of additional collateral posted, if any.
*/
function drawdownFunds(uint256 amount_, address destination_) external returns (uint256 collateralPosted_);
/**
* @dev Lend funds to the loan/borrower.
* @param lender_ The address to be registered as the lender.
* @param amount_ An amount to pull from the caller, if any.
* @return fundsLent_ The amount funded.
*/
function fundLoan(address lender_, uint256 amount_) external returns (uint256 fundsLent_);
/**
* @dev Make a payment to the loan.
* @param amount_ An amount to pull from the caller, if any.
* @return principal_ The portion of the amount paid paying back principal.
* @return interest_ The portion of the amount paid paying interest fees.
*/
function makePayment(uint256 amount_) external returns (uint256 principal_, uint256 interest_);
/**
* @dev Post collateral to the loan.
* @param amount_ An amount to pull from the caller, if any.
* @return collateralPosted_ The amount posted.
*/
function postCollateral(uint256 amount_) external returns (uint256 collateralPosted_);
/**
* @dev Propose new terms for refinance
* @param refinancer_ The address of the refinancer contract.
* @param calls_ The encoded arguments to be passed to refinancer.
*/
function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external;
/**
* @dev Remove collateral from the loan (opposite of posting collateral).
* @param amount_ The amount removed.
* @param destination_ The destination to send the removed collateral.
*/
function removeCollateral(uint256 amount_, address destination_) external;
/**
* @dev Return funds to the loan (opposite of drawing down).
* @param amount_ An amount to pull from the caller, if any.
* @return fundsReturned_ The amount returned.
*/
function returnFunds(uint256 amount_) external returns (uint256 fundsReturned_);
/**
* @dev Repossess collateral, and any funds, for a loan in default.
* @param destination_ The address where the collateral and funds asset is to be sent, if any.
* @return collateralRepossessed_ The amount of collateral asset repossessed.
* @return fundsRepossessed_ The amount of funds asset repossessed.
*/
function repossess(address destination_) external returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_);
/**
* @dev Set the pendingBorrower to a new account.
* @param pendingBorrower_ The address of the new pendingBorrower.
*/
function setPendingBorrower(address pendingBorrower_) external;
/**
* @dev Set the pendingLender to a new account.
* @param pendingLender_ The address of the new pendingLender.
*/
function setPendingLender(address pendingLender_) external;
/**
* @dev Remove some token (neither fundsAsset nor collateralAsset) from the loan.
* @param token_ The address of the token contract.
* @param destination_ The recipient of the token.
* @return skimmed_ The amount of token removed from the loan.
*/
function skim(address token_, address destination_) external returns (uint256 skimmed_);
/**********************/
/*** View Functions ***/
/**********************/
/**
* @dev Returns the excess collateral that can be removed.
* @return excessCollateral_ The excess collateral that can be removed, if any.
*/
function excessCollateral() external view returns (uint256 excessCollateral_);
/**
* @dev Get the additional collateral to be posted to drawdown some amount.
* @param drawdown_ The amount desired to be drawn down.
* @return additionalCollateral_ The additional collateral that must be posted, if any.
*/
function getAdditionalCollateralRequiredFor(uint256 drawdown_) external view returns (uint256 additionalCollateral_);
/**
* @dev Get the breakdown of the total payment needed to satisfy an early repayment.
* @return totalPrincipalAmount_ The portion of the total amount that will go towards principal.
* @return totalInterestFees_ The portion of the total amount that will go towards interest fees.
*/
function getEarlyPaymentBreakdown() external view returns (
uint256 totalPrincipalAmount_,
uint256 totalInterestFees_
);
/**
* @dev Get the breakdown of the total payment needed to satisfy `numberOfPayments` payment installments.
* @return totalPrincipalAmount_ The portion of the total amount that will go towards principal.
* @return totalInterestFees_ The portion of the total amount that will go towards interest fees.
*/
function getNextPaymentBreakdown() external view returns (
uint256 totalPrincipalAmount_,
uint256 totalInterestFees_
);
/**
* @dev Returns whether the protocol is paused.
* @return paused_ A boolean indicating if protocol is paused.
*/
function isProtocolPaused() external view returns (bool paused_);
}
abstract contract SlotManipulatable {
function _getReferenceTypeSlot(bytes32 slot_, bytes32 key_) internal pure returns (bytes32 value_) {
return keccak256(abi.encodePacked(key_, slot_));
}
function _getSlotValue(bytes32 slot_) internal view returns (bytes32 value_) {
assembly {
value_ := sload(slot_)
}
}
function _setSlotValue(bytes32 slot_, bytes32 value_) internal {
assembly {
sstore(slot_, value_)
}
}
}
/// @title An implementation that is to be proxied, will need ProxiedInternals.
abstract contract ProxiedInternals is SlotManipulatable {
/// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.factory') - 1`.
bytes32 private constant FACTORY_SLOT = bytes32(0x7a45a402e4cb6e08ebc196f20f66d5d30e67285a2a8aa80503fa409e727a4af1);
/// @dev Storage slot with the address of the current factory. `keccak256('eip1967.proxy.implementation') - 1`.
bytes32 private constant IMPLEMENTATION_SLOT = bytes32(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc);
/// @dev Delegatecalls to a migrator contract to manipulate storage during an initialization or migration.
function _migrate(address migrator_, bytes calldata arguments_) internal virtual returns (bool success_) {
uint256 size;
assembly {
size := extcodesize(migrator_)
}
if (size == uint256(0)) return false;
( success_, ) = migrator_.delegatecall(arguments_);
}
/// @dev Sets the factory address in storage.
function _setFactory(address factory_) internal virtual returns (bool success_) {
_setSlotValue(FACTORY_SLOT, bytes32(uint256(uint160(factory_))));
return true;
}
/// @dev Sets the implementation address in storage.
function _setImplementation(address implementation_) internal virtual returns (bool success_) {
_setSlotValue(IMPLEMENTATION_SLOT, bytes32(uint256(uint160(implementation_))));
return true;
}
/// @dev Returns the factory address.
function _factory() internal view virtual returns (address factory_) {
return address(uint160(uint256(_getSlotValue(FACTORY_SLOT))));
}
/// @dev Returns the implementation address.
function _implementation() internal view virtual returns (address implementation_) {
return address(uint160(uint256(_getSlotValue(IMPLEMENTATION_SLOT))));
}
}
/// @title A Maple implementation that is to be proxied, will need MapleProxiedInternals.
abstract contract MapleProxiedInternals is ProxiedInternals {}
/// @title MapleLoanInternals defines the storage layout and internal logic of MapleLoan.
abstract contract MapleLoanInternals is MapleProxiedInternals {
uint256 private constant SCALED_ONE = uint256(10 ** 18);
// Roles
address internal _borrower; // The address of the borrower.
address internal _lender; // The address of the lender.
address internal _pendingBorrower; // The address of the pendingBorrower, the only address that can accept the borrower role.
address internal _pendingLender; // The address of the pendingLender, the only address that can accept the lender role.
// Assets
address internal _collateralAsset; // The address of the asset used as collateral.
address internal _fundsAsset; // The address of the asset used as funds.
// Loan Term Parameters
uint256 internal _gracePeriod; // The number of seconds a payment can be late.
uint256 internal _paymentInterval; // The number of seconds between payments.
// Rates
uint256 internal _interestRate; // The annualized interest rate of the loan.
uint256 internal _earlyFeeRate; // The fee rate for prematurely closing loans.
uint256 internal _lateFeeRate; // The fee rate for late payments.
uint256 internal _lateInterestPremium; // The amount to increase the interest rate by for late payments.
// Requested Amounts
uint256 internal _collateralRequired; // The collateral the borrower is expected to put up to draw down all _principalRequested.
uint256 internal _principalRequested; // The funds the borrowers wants to borrow.
uint256 internal _endingPrincipal; // The principal to remain at end of loan.
// State
uint256 internal _drawableFunds; // The amount of funds that can be drawn down.
uint256 internal _claimableFunds; // The amount of funds that the lender can claim (principal repayments, interest, etc).
uint256 internal _collateral; // The amount of collateral, in collateral asset, that is currently posted.
uint256 internal _nextPaymentDueDate; // The timestamp of due date of next payment.
uint256 internal _paymentsRemaining; // The number of payments remaining.
uint256 internal _principal; // The amount of principal yet to be paid down.
// Refinance
bytes32 internal _refinanceCommitment;
/**********************************/
/*** Internal General Functions ***/
/**********************************/
/// @dev Clears all state variables to end a loan, but keep borrower and lender withdrawal functionality intact.
function _clearLoanAccounting() internal {
_gracePeriod = uint256(0);
_paymentInterval = uint256(0);
_interestRate = uint256(0);
_earlyFeeRate = uint256(0);
_lateFeeRate = uint256(0);
_lateInterestPremium = uint256(0);
_endingPrincipal = uint256(0);
_nextPaymentDueDate = uint256(0);
_paymentsRemaining = uint256(0);
_principal = uint256(0);
}
/**
* @dev Initializes the loan.
* @param borrower_ The address of the borrower.
* @param assets_ Array of asset addresses.
* [0]: collateralAsset,
* [1]: fundsAsset.
* @param termDetails_ Array of loan parameters:
* [0]: gracePeriod,
* [1]: paymentInterval,
* [2]: payments,
* @param amounts_ Requested amounts:
* [0]: collateralRequired,
* [1]: principalRequested,
* [2]: endingPrincipal.
* @param rates_ Fee parameters:
* [0]: interestRate,
* [1]: earlyFeeRate,
* [2]: lateFeeRate,
* [3]: lateInterestPremium.
*/
function _initialize(
address borrower_,
address[2] memory assets_,
uint256[3] memory termDetails_,
uint256[3] memory amounts_,
uint256[4] memory rates_
)
internal
{
// Principal requested needs to be non-zero (see `_getCollateralRequiredFor` math).
require(amounts_[1] > uint256(0), "MLI:I:INVALID_PRINCIPAL");
// Ending principal needs to be less than or equal to principal requested.
require(amounts_[2] <= amounts_[1], "MLI:I:INVALID_ENDING_PRINCIPAL");
require((_borrower = borrower_) != address(0), "MLI:I:INVALID_BORROWER");
_collateralAsset = assets_[0];
_fundsAsset = assets_[1];
_gracePeriod = termDetails_[0];
_paymentInterval = termDetails_[1];
_paymentsRemaining = termDetails_[2];
_collateralRequired = amounts_[0];
_principalRequested = amounts_[1];
_endingPrincipal = amounts_[2];
_interestRate = rates_[0];
_earlyFeeRate = rates_[1];
_lateFeeRate = rates_[2];
_lateInterestPremium = rates_[3];
}
/**************************************/
/*** Internal Borrow-side Functions ***/
/**************************************/
/// @dev Prematurely ends a loan by making all remaining payments.
function _closeLoan() internal returns (uint256 principal_, uint256 interest_) {
require(block.timestamp <= _nextPaymentDueDate, "MLI:CL:PAYMENT_IS_LATE");
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
uint256 totalPaid = principal_ + interest_;
// The drawable funds are increased by the extra funds in the contract, minus the total needed for payment.
_drawableFunds = _drawableFunds + _getUnaccountedAmount(_fundsAsset) - totalPaid;
_claimableFunds += totalPaid;
_clearLoanAccounting();
}
/// @dev Sends `amount_` of `_drawableFunds` to `destination_`.
function _drawdownFunds(uint256 amount_, address destination_) internal {
_drawableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL");
}
/// @dev Makes a payment to progress the loan closer to maturity.
function _makePayment() internal returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
uint256 totalPaid = principal_ + interest_;
// The drawable funds are increased by the extra funds in the contract, minus the total needed for payment.
// NOTE: This line will revert if not enough funds were added for the full payment amount.
_drawableFunds = (_drawableFunds + _getUnaccountedAmount(_fundsAsset)) - totalPaid;
_claimableFunds += totalPaid;
uint256 paymentsRemaining = _paymentsRemaining;
if (paymentsRemaining == uint256(1)) {
_clearLoanAccounting(); // Assumes `_getNextPaymentBreakdown` returns a `principal_` that is `_principal`.
} else {
_nextPaymentDueDate += _paymentInterval;
_principal -= principal_;
_paymentsRemaining = paymentsRemaining - uint256(1);
}
}
/// @dev Registers the delivery of an amount of collateral to be posted.
function _postCollateral() internal returns (uint256 collateralPosted_) {
_collateral += (collateralPosted_ = _getUnaccountedAmount(_collateralAsset));
}
/// @dev Sets refinance commitment given refinance operations.
function _proposeNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 proposedRefinanceCommitment_) {
// NOTE: There is no way to invalidate the `refinanceCommitment` (i.e. bytes32(0)) without explicitly setting it if `calls_.length` is 0.
return _refinanceCommitment =
calls_.length > uint256(0)
? _getRefinanceCommitment(refinancer_, calls_)
: bytes32(0);
}
/// @dev Sends `amount_` of `_collateral` to `destination_`.
function _removeCollateral(uint256 amount_, address destination_) internal {
_collateral -= amount_;
require(ERC20Helper.transfer(_collateralAsset, destination_, amount_), "MLI:RC:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:RC:INSUFFICIENT_COLLATERAL");
}
/// @dev Registers the delivery of an amount of funds to be returned as `_drawableFunds`.
function _returnFunds() internal returns (uint256 fundsReturned_) {
_drawableFunds += (fundsReturned_ = _getUnaccountedAmount(_fundsAsset));
}
/************************************/
/*** Internal Lend-side Functions ***/
/************************************/
/// @dev Processes refinance operations.
function _acceptNewTerms(address refinancer_, bytes[] calldata calls_) internal returns (bytes32 acceptedRefinanceCommitment_) {
// NOTE: A zero refinancer address and/or empty calls array will never (probabilistically) match a refinance commitment in storage.
require(_refinanceCommitment == (acceptedRefinanceCommitment_ = _getRefinanceCommitment(refinancer_, calls_)), "MLI:ANT:COMMITMENT_MISMATCH");
require(refinancer_.code.length != uint256(0), "MLI:ANT:INVALID_REFINANCER");
// Clear refinance commitment to prevent implications of re-acceptance of another call to `_acceptNewTerms`.
_refinanceCommitment = bytes32(0);
uint256 callCount = calls_.length;
for (uint256 i; i < callCount; ++i) {
( bool success, ) = refinancer_.delegatecall(calls_[i]);
require(success, "MLI:ANT:FAILED");
}
// Ensure that collateral is maintained after changes made.
require(_isCollateralMaintained(), "MLI:ANT:INSUFFICIENT_COLLATERAL");
}
/// @dev Sends `amount_` of `_claimableFunds` to `destination_`.
/// If `amount_` is higher than `_claimableFunds` the transaction will underflow and revert.
function _claimFunds(uint256 amount_, address destination_) internal {
_claimableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:CF:TRANSFER_FAILED");
}
/// @dev Fund the loan and kick off the repayment requirements.
function _fundLoan(address lender_) internal returns (uint256 fundsLent_) {
uint256 paymentsRemaining = _paymentsRemaining;
// Can only fund loan if there are payments remaining (as defined by the initialization) and no payment is due yet (as set by a funding).
require((_nextPaymentDueDate == uint256(0)) && (paymentsRemaining != uint256(0)), "MLI:FL:LOAN_ACTIVE");
uint256 paymentInterval = _paymentInterval;
// NOTE: Don't need to check if lender_ is nonzero or valid, since it is done implicitly in calls to `lender_` below.
_lender = lender_;
_nextPaymentDueDate = block.timestamp + paymentInterval;
// Amount funded and principal are as requested.
fundsLent_ = _principal = _principalRequested;
address fundsAsset = _fundsAsset;
// Cannot under-fund loan, but over-funding results in additional funds left unaccounted for.
require(_getUnaccountedAmount(fundsAsset) >= fundsLent_, "MLI:FL:WRONG_FUND_AMOUNT");
IMapleGlobalsLike globals = IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals());
// Transfer the annualized treasury fee, if any, to the Maple treasury, and decrement drawable funds.
uint256 treasuryFee = (fundsLent_ * globals.treasuryFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000);
// Transfer delegate fee, if any, to the pool delegate, and decrement drawable funds.
uint256 delegateFee = (fundsLent_ * globals.investorFee() * paymentInterval * paymentsRemaining) / uint256(365 days * 10_000);
// Drawable funds is the amount funded, minus any fees.
_drawableFunds = fundsLent_ - treasuryFee - delegateFee;
require(
treasuryFee == uint256(0) || ERC20Helper.transfer(fundsAsset, globals.mapleTreasury(), treasuryFee),
"MLI:FL:T_TRANSFER_FAILED"
);
require(
delegateFee == uint256(0) || ERC20Helper.transfer(fundsAsset, ILenderLike(lender_).poolDelegate(), delegateFee),
"MLI:FL:PD_TRANSFER_FAILED"
);
}
/// @dev Reset all state variables in order to release funds and collateral of a loan in default.
function _repossess(address destination_) internal returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) {
uint256 nextPaymentDueDate = _nextPaymentDueDate;
require(
nextPaymentDueDate != uint256(0) && (block.timestamp > nextPaymentDueDate + _gracePeriod),
"MLI:R:NOT_IN_DEFAULT"
);
_clearLoanAccounting();
// Uniquely in `_repossess`, stop accounting for all funds so that they can be swept.
_collateral = uint256(0);
_claimableFunds = uint256(0);
_drawableFunds = uint256(0);
address collateralAsset = _collateralAsset;
// Either there is no collateral to repossess, or the transfer of the collateral succeeds.
require(
(collateralRepossessed_ = _getUnaccountedAmount(collateralAsset)) == uint256(0) ||
ERC20Helper.transfer(collateralAsset, destination_, collateralRepossessed_),
"MLI:R:C_TRANSFER_FAILED"
);
address fundsAsset = _fundsAsset;
// Either there are no funds to repossess, or the transfer of the funds succeeds.
require(
(fundsRepossessed_ = _getUnaccountedAmount(fundsAsset)) == uint256(0) ||
ERC20Helper.transfer(fundsAsset, destination_, fundsRepossessed_),
"MLI:R:F_TRANSFER_FAILED"
);
}
/*******************************/
/*** Internal View Functions ***/
/*******************************/
/// @dev Returns whether the amount of collateral posted is commensurate with the amount of drawn down (outstanding) principal.
function _isCollateralMaintained() internal view returns (bool isMaintained_) {
return _collateral >= _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired);
}
/// @dev Get principal and interest breakdown for paying off the entire loan early.
function _getEarlyPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) {
interest_ = ((principal_ = _principal) * _earlyFeeRate) / SCALED_ONE;
}
/// @dev Get principal and interest breakdown for next standard payment.
function _getNextPaymentBreakdown() internal view returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getPaymentBreakdown(
block.timestamp,
_nextPaymentDueDate,
_paymentInterval,
_principal,
_endingPrincipal,
_paymentsRemaining,
_interestRate,
_lateFeeRate,
_lateInterestPremium
);
}
/// @dev Returns the amount of an `asset_` that this contract owns, which is not currently accounted for by its state variables.
function _getUnaccountedAmount(address asset_) internal view virtual returns (uint256 unaccountedAmount_) {
return IERC20Like(asset_).balanceOf(address(this))
- (asset_ == _collateralAsset ? _collateral : uint256(0)) // `_collateral` is `_collateralAsset` accounted for.
- (asset_ == _fundsAsset ? _claimableFunds + _drawableFunds : uint256(0)); // `_claimableFunds` and `_drawableFunds` are `_fundsAsset` accounted for.
}
/*******************************/
/*** Internal Pure Functions ***/
/*******************************/
/// @dev Returns the total collateral to be posted for some drawn down (outstanding) principal and overall collateral ratio requirement.
function _getCollateralRequiredFor(
uint256 principal_,
uint256 drawableFunds_,
uint256 principalRequested_,
uint256 collateralRequired_
)
internal pure returns (uint256 collateral_)
{
// Where (collateral / outstandingPrincipal) should be greater or equal to (collateralRequired / principalRequested).
// NOTE: principalRequested_ cannot be 0, which is reasonable, since it means this was never a loan.
return principal_ <= drawableFunds_ ? uint256(0) : (collateralRequired_ * (principal_ - drawableFunds_)) / principalRequested_;
}
/// @dev Returns principal and interest portions of a payment instalment, given generic, stateless loan parameters.
function _getInstallment(uint256 principal_, uint256 endingPrincipal_, uint256 interestRate_, uint256 paymentInterval_, uint256 totalPayments_)
internal pure virtual returns (uint256 principalAmount_, uint256 interestAmount_)
{
/*************************************************************************************************\
* | *
* A = installment amount | / \ / R \ *
* P = principal remaining | | / \ | | ----------------------- | *
* R = interest rate | A = | | P * ( 1 + R ) ^ N | - E | * | / \ | *
* N = payments remaining | | \ / | | | ( 1 + R ) ^ N | - 1 | *
* E = ending principal target | \ / \ \ / / *
* | *
* |---------------------------------------------------------------- *
* *
* - Where R is `periodicRate` *
* - Where (1 + R) ^ N is `raisedRate` *
* - Both of these rates are scaled by 1e18 (e.g., 12% => 0.12 * 10 ** 18) *
\*************************************************************************************************/
uint256 periodicRate = _getPeriodicInterestRate(interestRate_, paymentInterval_);
uint256 raisedRate = _scaledExponent(SCALED_ONE + periodicRate, totalPayments_, SCALED_ONE);
// NOTE: If a lack of precision in `_scaledExponent` results in a `raisedRate` smaller than one, assume it to be one and simplify the equation.
if (raisedRate <= SCALED_ONE) return ((principal_ - endingPrincipal_) / totalPayments_, uint256(0));
uint256 total = ((((principal_ * raisedRate) / SCALED_ONE) - endingPrincipal_) * periodicRate) / (raisedRate - SCALED_ONE);
interestAmount_ = _getInterest(principal_, interestRate_, paymentInterval_);
principalAmount_ = total >= interestAmount_ ? total - interestAmount_ : uint256(0);
}
/// @dev Returns an amount by applying an annualized and scaled interest rate, to a principal, over an interval of time.
function _getInterest(uint256 principal_, uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 interest_) {
return (principal_ * _getPeriodicInterestRate(interestRate_, interval_)) / SCALED_ONE;
}
/// @dev Returns total principal and interest portion of a number of payments, given generic, stateless loan parameters and loan state.
function _getPaymentBreakdown(
uint256 currentTime_,
uint256 nextPaymentDueDate_,
uint256 paymentInterval_,
uint256 principal_,
uint256 endingPrincipal_,
uint256 paymentsRemaining_,
uint256 interestRate_,
uint256 lateFeeRate_,
uint256 lateInterestPremium_
)
internal pure virtual
returns (uint256 principalAmount_, uint256 interestAmount_)
{
( principalAmount_, interestAmount_ ) = _getInstallment(
principal_,
endingPrincipal_,
interestRate_,
paymentInterval_,
paymentsRemaining_
);
principalAmount_ = paymentsRemaining_ == uint256(1) ? principal_ : principalAmount_;
if (currentTime_ > nextPaymentDueDate_) {
uint256 daysLate = (((currentTime_ - nextPaymentDueDate_ - 1) / 1 days) + 1) * 1 days;
interestAmount_ += _getInterest(principal_, interestRate_ + lateInterestPremium_, daysLate);
interestAmount_ += (lateFeeRate_ * principal_) / SCALED_ONE;
}
}
/// @dev Returns the interest rate over an interval, given an annualized interest rate.
function _getPeriodicInterestRate(uint256 interestRate_, uint256 interval_) internal pure virtual returns (uint256 periodicInterestRate_) {
return (interestRate_ * interval_) / uint256(365 days);
}
/// @dev Returns refinance commitment given refinance parameters.
function _getRefinanceCommitment(address refinancer_, bytes[] calldata calls_) internal pure returns (bytes32 refinanceCommitment_) {
return keccak256(abi.encode(refinancer_, calls_));
}
/**
* @dev Returns exponentiation of a scaled base value.
*
* Walk through example:
* LINE | base_ | exponent_ | one_ | result_
* | 3_00 | 18 | 1_00 | 0_00
* A | 3_00 | 18 | 1_00 | 1_00
* B | 3_00 | 9 | 1_00 | 1_00
* C | 9_00 | 9 | 1_00 | 1_00
* D | 9_00 | 9 | 1_00 | 9_00
* B | 9_00 | 4 | 1_00 | 9_00
* C | 81_00 | 4 | 1_00 | 9_00
* B | 81_00 | 2 | 1_00 | 9_00
* C | 6_561_00 | 2 | 1_00 | 9_00
* B | 6_561_00 | 1 | 1_00 | 9_00
* C | 43_046_721_00 | 1 | 1_00 | 9_00
* D | 43_046_721_00 | 1 | 1_00 | 387_420_489_00
* B | 43_046_721_00 | 0 | 1_00 | 387_420_489_00
*
* Another implementation of this algorithm can be found in Dapphub's DSMath contract:
* https://github.com/dapphub/ds-math/blob/ce67c0fa9f8262ecd3d76b9e4c026cda6045e96c/src/math.sol#L77
*/
function _scaledExponent(uint256 base_, uint256 exponent_, uint256 one_) internal pure returns (uint256 result_) {
// If exponent_ is odd, set result_ to base_, else set to one_.
result_ = exponent_ & uint256(1) != uint256(0) ? base_ : one_; // A
// Divide exponent_ by 2 (overwriting itself) and proceed if not zero.
while ((exponent_ >>= uint256(1)) != uint256(0)) { // B
base_ = (base_ * base_) / one_; // C
// If exponent_ is even, go back to top.
if (exponent_ & uint256(1) == uint256(0)) continue;
// If exponent_ is odd, multiply result_ is multiplied by base_.
result_ = (result_ * base_) / one_; // D
}
}
}
/// @title MapleLoan implements a primitive loan with additional functionality, and is intended to be proxied.
contract MapleLoan is IMapleLoan, MapleLoanInternals {
modifier whenProtocolNotPaused() {
require(!isProtocolPaused(), "ML:PROTOCOL_PAUSED");
_;
}
/********************************/
/*** Administrative Functions ***/
/********************************/
function migrate(address migrator_, bytes calldata arguments_) external override {
require(msg.sender == _factory(), "ML:M:NOT_FACTORY");
require(_migrate(migrator_, arguments_), "ML:M:FAILED");
}
function setImplementation(address newImplementation_) external override {
require(msg.sender == _factory(), "ML:SI:NOT_FACTORY");
require(_setImplementation(newImplementation_), "ML:SI:FAILED");
}
function upgrade(uint256 toVersion_, bytes calldata arguments_) external override {
require(msg.sender == _borrower, "ML:U:NOT_BORROWER");
emit Upgraded(toVersion_, arguments_);
IMapleProxyFactoryLike(_factory()).upgradeInstance(toVersion_, arguments_);
}
/************************/
/*** Borrow Functions ***/
/************************/
function acceptBorrower() external override {
require(msg.sender == _pendingBorrower, "ML:AB:NOT_PENDING_BORROWER");
_pendingBorrower = address(0);
emit BorrowerAccepted(_borrower = msg.sender);
}
function closeLoan(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:CL:TRANSFER_FROM_FAILED");
// If the caller is not the borrower, require that the transferred amount be sufficient to close the loan without touching `_drawableFunds`.
if (msg.sender != _borrower) {
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:CL:CANNOT_USE_DRAWABLE");
}
( principal_, interest_ ) = _closeLoan();
emit LoanClosed(principal_, interest_);
}
function drawdownFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused returns (uint256 collateralPosted_) {
require(msg.sender == _borrower, "ML:DF:NOT_BORROWER");
emit FundsDrawnDown(amount_, destination_);
// Post additional collateral required to facilitate this drawdown, if needed.
uint256 additionalCollateralRequired = getAdditionalCollateralRequiredFor(amount_);
if (additionalCollateralRequired > uint256(0)) {
// Determine collateral currently unaccounted for.
uint256 unaccountedCollateral = _getUnaccountedAmount(_collateralAsset);
// Post required collateral, specifying then amount lacking as the optional amount to be transferred from.
collateralPosted_ = postCollateral(
additionalCollateralRequired > unaccountedCollateral ? additionalCollateralRequired - unaccountedCollateral : uint256(0)
);
}
_drawdownFunds(amount_, destination_);
}
function makePayment(uint256 amount_) external override returns (uint256 principal_, uint256 interest_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:MP:TRANSFER_FROM_FAILED");
// If the caller is not the borrower, require that the transferred amount be sufficient to make a payment without touching `_drawableFunds`.
if (msg.sender != _borrower) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
require(_getUnaccountedAmount(_fundsAsset) >= principal_ + interest_, "ML:MP:CANNOT_USE_DRAWABLE");
}
( principal_, interest_ ) = _makePayment();
emit PaymentMade(principal_, interest_);
}
function postCollateral(uint256 amount_) public override whenProtocolNotPaused returns (uint256 collateralPosted_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(
amount_ == uint256(0) || ERC20Helper.transferFrom(_collateralAsset, msg.sender, address(this), amount_),
"ML:PC:TRANSFER_FROM_FAILED"
);
emit CollateralPosted(collateralPosted_ = _postCollateral());
}
function proposeNewTerms(address refinancer_, bytes[] calldata calls_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:PNT:NOT_BORROWER");
emit NewTermsProposed(_proposeNewTerms(refinancer_, calls_), refinancer_, calls_);
}
function removeCollateral(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _borrower, "ML:RC:NOT_BORROWER");
emit CollateralRemoved(amount_, destination_);
_removeCollateral(amount_, destination_);
}
function returnFunds(uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsReturned_) {
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(_fundsAsset, msg.sender, address(this), amount_), "ML:RF:TRANSFER_FROM_FAILED");
emit FundsReturned(fundsReturned_ = _returnFunds());
}
function setPendingBorrower(address pendingBorrower_) external override {
require(msg.sender == _borrower, "ML:SPB:NOT_BORROWER");
emit PendingBorrowerSet(_pendingBorrower = pendingBorrower_);
}
/**********************/
/*** Lend Functions ***/
/**********************/
function acceptLender() external override {
require(msg.sender == _pendingLender, "ML:AL:NOT_PENDING_LENDER");
_pendingLender = address(0);
emit LenderAccepted(_lender = msg.sender);
}
function acceptNewTerms(address refinancer_, bytes[] calldata calls_, uint256 amount_) external override whenProtocolNotPaused {
address lenderAddress = _lender;
require(msg.sender == lenderAddress, "ML:ANT:NOT_LENDER");
address fundsAssetAddress = _fundsAsset;
// The amount specified is an optional amount to be transfer from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:ACT:TRANSFER_FROM_FAILED");
emit NewTermsAccepted(_acceptNewTerms(refinancer_, calls_), refinancer_, calls_);
uint256 extra = _getUnaccountedAmount(fundsAssetAddress);
// NOTE: This block ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender.
if (extra > uint256(0)) {
emit FundsRedirected(extra, lenderAddress);
require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:ANT:TRANSFER_FAILED");
}
}
function claimFunds(uint256 amount_, address destination_) external override whenProtocolNotPaused {
require(msg.sender == _lender, "ML:CF:NOT_LENDER");
emit FundsClaimed(amount_, destination_);
_claimFunds(amount_, destination_);
}
function fundLoan(address lender_, uint256 amount_) external override whenProtocolNotPaused returns (uint256 fundsLent_) {
address fundsAssetAddress = _fundsAsset;
// The amount specified is an optional amount to be transferred from the caller, as a convenience for EOAs.
require(amount_ == uint256(0) || ERC20Helper.transferFrom(fundsAssetAddress, msg.sender, address(this), amount_), "ML:FL:TRANSFER_FROM_FAILED");
// If the loan is not active, fund it.
if (_nextPaymentDueDate == uint256(0)) {
// NOTE: `_nextPaymentDueDate` emitted in event is updated by `_fundLoan`.
emit Funded(lender_, fundsLent_ = _fundLoan(lender_), _nextPaymentDueDate);
}
uint256 extra = _getUnaccountedAmount(fundsAssetAddress);
address lenderAddress = _lender;
// NOTE: This block is not only a stopgap solution to allow a LiquidityLockerV1 to send funds to a DebtLocker, while maintaining PoolV1 accounting,
// but also ensures unaccounted funds (pre-existing or due to over-funding) gets redirected to the lender.
if (extra > uint256(0)) {
emit FundsRedirected(extra, lenderAddress);
require(ERC20Helper.transfer(fundsAssetAddress, lenderAddress, extra), "ML:FL:TRANSFER_FAILED");
}
}
function repossess(address destination_) external override whenProtocolNotPaused returns (uint256 collateralRepossessed_, uint256 fundsRepossessed_) {
require(msg.sender == _lender, "ML:R:NOT_LENDER");
( collateralRepossessed_, fundsRepossessed_ ) = _repossess(destination_);
emit Repossessed(collateralRepossessed_, fundsRepossessed_, destination_);
}
function setPendingLender(address pendingLender_) external override {
require(msg.sender == _lender, "ML:SPL:NOT_LENDER");
emit PendingLenderSet(_pendingLender = pendingLender_);
}
/*******************************/
/*** Miscellaneous Functions ***/
/*******************************/
function skim(address token_, address destination_) external override whenProtocolNotPaused returns (uint256 skimmed_) {
require((msg.sender == _borrower) || (msg.sender == _lender), "L:S:NO_AUTH");
require((token_ != _fundsAsset) && (token_ != _collateralAsset), "L:S:INVALID_TOKEN");
emit Skimmed(token_, skimmed_ = IERC20Like(token_).balanceOf(address(this)), destination_);
require(ERC20Helper.transfer(token_, destination_, skimmed_), "L:S:TRANSFER_FAILED");
}
/**********************/
/*** View Functions ***/
/**********************/
function getAdditionalCollateralRequiredFor(uint256 drawdown_) public view override returns (uint256 collateral_) {
// Determine the collateral needed in the contract for a reduced drawable funds amount.
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds - drawdown_, _principalRequested, _collateralRequired);
uint256 currentCollateral = _collateral;
return collateralNeeded > currentCollateral ? collateralNeeded - currentCollateral : uint256(0);
}
function getEarlyPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getEarlyPaymentBreakdown();
}
function getNextPaymentBreakdown() external view override returns (uint256 principal_, uint256 interest_) {
( principal_, interest_ ) = _getNextPaymentBreakdown();
}
function isProtocolPaused() public view override returns (bool paused_) {
return IMapleGlobalsLike(IMapleProxyFactoryLike(_factory()).mapleGlobals()).protocolPaused();
}
/****************************/
/*** State View Functions ***/
/****************************/
function borrower() external view override returns (address borrower_) {
return _borrower;
}
function claimableFunds() external view override returns (uint256 claimableFunds_) {
return _claimableFunds;
}
function collateral() external view override returns (uint256 collateral_) {
return _collateral;
}
function collateralAsset() external view override returns (address collateralAsset_) {
return _collateralAsset;
}
function collateralRequired() external view override returns (uint256 collateralRequired_) {
return _collateralRequired;
}
function drawableFunds() external view override returns (uint256 drawableFunds_) {
return _drawableFunds;
}
function earlyFeeRate() external view override returns (uint256 earlyFeeRate_) {
return _earlyFeeRate;
}
function endingPrincipal() external view override returns (uint256 endingPrincipal_) {
return _endingPrincipal;
}
function excessCollateral() external view override returns (uint256 excessCollateral_) {
uint256 collateralNeeded = _getCollateralRequiredFor(_principal, _drawableFunds, _principalRequested, _collateralRequired);
uint256 currentCollateral = _collateral;
return currentCollateral > collateralNeeded ? currentCollateral - collateralNeeded : uint256(0);
}
function factory() external view override returns (address factory_) {
return _factory();
}
function fundsAsset() external view override returns (address fundsAsset_) {
return _fundsAsset;
}
function gracePeriod() external view override returns (uint256 gracePeriod_) {
return _gracePeriod;
}
function implementation() external view override returns (address implementation_) {
return _implementation();
}
function interestRate() external view override returns (uint256 interestRate_) {
return _interestRate;
}
function lateFeeRate() external view override returns (uint256 lateFeeRate_) {
return _lateFeeRate;
}
function lateInterestPremium() external view override returns (uint256 lateInterestPremium_) {
return _lateInterestPremium;
}
function lender() external view override returns (address lender_) {
return _lender;
}
function nextPaymentDueDate() external view override returns (uint256 nextPaymentDueDate_) {
return _nextPaymentDueDate;
}
function paymentInterval() external view override returns (uint256 paymentInterval_) {
return _paymentInterval;
}
function paymentsRemaining() external view override returns (uint256 paymentsRemaining_) {
return _paymentsRemaining;
}
function pendingBorrower() external view override returns (address pendingBorrower_) {
return _pendingBorrower;
}
function pendingLender() external view override returns (address pendingLender_) {
return _pendingLender;
}
function principalRequested() external view override returns (uint256 principalRequested_) {
return _principalRequested;
}
function principal() external view override returns (uint256 principal_) {
return _principal;
}
// NOTE: This is needed for `fundLoan` call from PoolV1.
function superFactory() external view override returns (address superFactory_) {
return _factory();
}
} | @dev Sends `amount_` of `_drawableFunds` to `destination_`. | function _drawdownFunds(uint256 amount_, address destination_) internal {
_drawableFunds -= amount_;
require(ERC20Helper.transfer(_fundsAsset, destination_, amount_), "MLI:DF:TRANSFER_FAILED");
require(_isCollateralMaintained(), "MLI:DF:INSUFFICIENT_COLLATERAL");
}
| 14,008,983 | [
1,
10501,
1375,
8949,
67,
68,
434,
1375,
67,
9446,
429,
42,
19156,
68,
358,
1375,
10590,
67,
8338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
9446,
2378,
42,
19156,
12,
11890,
5034,
3844,
67,
16,
1758,
2929,
67,
13,
2713,
288,
203,
3639,
389,
9446,
429,
42,
19156,
3947,
3844,
67,
31,
203,
203,
3639,
2583,
12,
654,
39,
3462,
2276,
18,
13866,
24899,
74,
19156,
6672,
16,
2929,
67,
16,
3844,
67,
3631,
315,
1495,
45,
30,
4577,
30,
16596,
6553,
67,
11965,
8863,
203,
3639,
2583,
24899,
291,
13535,
2045,
287,
49,
1598,
8707,
9334,
27573,
315,
1495,
45,
30,
4577,
30,
706,
6639,
42,
1653,
7266,
2222,
67,
4935,
12190,
654,
1013,
8863,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0xE9036Cd5e8323Ace45f26AE160a33B16985f58f2/sources/contracts/Rat332.sol | reward claim protocol approve contract | function activateTestnet() public onlyOwner {
disableEasyRewardFrom = block.timestamp;
rewardCycleBlock = 30 minutes;
easyRewardCycleBlock = 1 days;
winningDoubleRewardPercentage = 5;
disruptiveCoverageFee = 2 ether;
disruptiveTransferEnabledFrom = block.timestamp;
setSwapAndLiquifyEnabled(true);
_approve(address(this), address(pancakeRouter), 2 ** 256 - 1);
}
| 8,159,855 | [
1,
266,
2913,
7516,
1771,
6617,
537,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
10235,
4709,
2758,
1435,
1071,
1338,
5541,
288,
203,
3639,
4056,
41,
15762,
17631,
1060,
1265,
273,
1203,
18,
5508,
31,
203,
3639,
19890,
13279,
1768,
273,
5196,
6824,
31,
203,
3639,
12779,
17631,
1060,
13279,
1768,
273,
404,
4681,
31,
203,
203,
3639,
5657,
2093,
5265,
17631,
1060,
16397,
273,
1381,
31,
203,
203,
3639,
1015,
10433,
688,
9739,
14667,
273,
576,
225,
2437,
31,
203,
3639,
1015,
10433,
688,
5912,
1526,
1265,
273,
1203,
18,
5508,
31,
203,
3639,
444,
12521,
1876,
48,
18988,
1164,
1526,
12,
3767,
1769,
203,
203,
3639,
389,
12908,
537,
12,
2867,
12,
2211,
3631,
1758,
12,
7355,
23780,
8259,
3631,
576,
2826,
8303,
300,
404,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/83/0x958420Fa2EC2A73dAbea569661487a5149508729/sources/contracts/base/vote/VeUpgradeable.sol | @notice Calculate total voting power at some point in the past @param _block Block to calculate the total voting power at @return Total voting power at `_block` it is possible only for a block before the launch return 0 as more clear answer than revert | function totalSupplyAt(uint _block) external view returns (uint) {
require(_block <= block.number, "only old blocks");
uint _epoch = epoch;
uint targetEpoch = _findBlockEpoch(_block, _epoch);
Point memory point = _pointHistory[targetEpoch];
if (point.blk > _block) {
return 0;
}
uint dt = 0;
if (targetEpoch < _epoch) {
Point memory point_next = _pointHistory[targetEpoch + 1];
dt =
((_block - point.blk) * (point_next.ts - point.ts)) /
(point_next.blk - point.blk);
if (point.blk != block.number) {
dt =
((_block - point.blk) * (block.timestamp - point.ts)) /
(block.number - point.blk);
}
}
} else {
if (targetEpoch < _epoch) {
Point memory point_next = _pointHistory[targetEpoch + 1];
dt =
((_block - point.blk) * (point_next.ts - point.ts)) /
(point_next.blk - point.blk);
if (point.blk != block.number) {
dt =
((_block - point.blk) * (block.timestamp - point.ts)) /
(block.number - point.blk);
}
}
return _supplyAt(point, point.ts + dt);
}
| 9,556,867 | [
1,
8695,
2078,
331,
17128,
7212,
622,
2690,
1634,
316,
326,
8854,
225,
389,
2629,
3914,
358,
4604,
326,
2078,
331,
17128,
7212,
622,
327,
10710,
331,
17128,
7212,
622,
1375,
67,
2629,
68,
518,
353,
3323,
1338,
364,
279,
1203,
1865,
326,
8037,
327,
374,
487,
1898,
2424,
5803,
2353,
15226,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
861,
12,
11890,
389,
2629,
13,
3903,
1476,
1135,
261,
11890,
13,
288,
203,
3639,
2583,
24899,
2629,
1648,
1203,
18,
2696,
16,
315,
3700,
1592,
4398,
8863,
203,
3639,
2254,
389,
12015,
273,
7632,
31,
203,
3639,
2254,
1018,
14638,
273,
389,
4720,
1768,
14638,
24899,
2629,
16,
389,
12015,
1769,
203,
203,
3639,
4686,
3778,
1634,
273,
389,
1153,
5623,
63,
3299,
14638,
15533,
203,
3639,
309,
261,
1153,
18,
3083,
79,
405,
389,
2629,
13,
288,
203,
5411,
327,
374,
31,
203,
3639,
289,
203,
3639,
2254,
3681,
273,
374,
31,
203,
3639,
309,
261,
3299,
14638,
411,
389,
12015,
13,
288,
203,
5411,
4686,
3778,
1634,
67,
4285,
273,
389,
1153,
5623,
63,
3299,
14638,
397,
404,
15533,
203,
5411,
3681,
273,
203,
7734,
14015,
67,
2629,
300,
1634,
18,
3083,
79,
13,
380,
261,
1153,
67,
4285,
18,
3428,
300,
1634,
18,
3428,
3719,
342,
203,
7734,
261,
1153,
67,
4285,
18,
3083,
79,
300,
1634,
18,
3083,
79,
1769,
203,
5411,
309,
261,
1153,
18,
3083,
79,
480,
1203,
18,
2696,
13,
288,
203,
7734,
3681,
273,
203,
10792,
14015,
67,
2629,
300,
1634,
18,
3083,
79,
13,
380,
261,
2629,
18,
5508,
300,
1634,
18,
3428,
3719,
342,
203,
10792,
261,
2629,
18,
2696,
300,
1634,
18,
3083,
79,
1769,
203,
5411,
289,
203,
3639,
289,
203,
3639,
289,
469,
288,
203,
3639,
309,
261,
3299,
14638,
411,
389,
12015,
13,
288,
203,
5411,
4686,
3778,
1634,
67,
4285,
273,
389,
1153,
2
] |
pragma solidity ^0.4.24;
import './ERC20.sol';
import './SafeMath.sol';
contract SatToken is ERC20 {
string name;
uint version;
string description;
bool enablePayableFunc = false;
constructor (string _name, string _description, uint _version) public {
name = _name;
version = _version;
description = _description;
}
//TODO: Put splyt related $$ transfer logic here
// Temperory give each user 20500 tokens for free
function initUser(address _user) public {
user[_user] = 205000000;
totalMinted = SafeMath.add(205000000, totalMinted);
}
// This function will trade your ether with sat tokens for you.
// the only way to attain sat tokens
function sendSatTokens() public payable returns(bool) {
if(enablePayableFunc == true) {
// we are accepting ether in return for tokens
} else {
// we are NOT accepting ether at this time
// give the ether back to sender
msg.sender.transfer(msg.value);
}
}
// If someone sends ether to this contract, without specifing a function, it'll end up here
// in that case send their ether back to them.
function() public payable {
msg.sender.transfer(msg.value);
}
}
| If someone sends ether to this contract, without specifing a function, it'll end up here in that case send their ether back to them. | function() public payable {
msg.sender.transfer(msg.value);
}
| 999,844 | [
1,
2047,
18626,
9573,
225,
2437,
358,
333,
6835,
16,
2887,
857,
430,
310,
279,
445,
16,
518,
5614,
679,
731,
2674,
316,
716,
648,
1366,
3675,
225,
2437,
1473,
358,
2182,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1435,
1071,
8843,
429,
288,
203,
3639,
1234,
18,
15330,
18,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0x9e0d557041c9EF5eED9C2a10dB28b449D41aaFC1/sources/contracts/CSKGen.sol | @dev call this to set wlLists before start | function setWhitelists(
MintType wlType,
address[] memory _userAddresses,
Whitelist _doType
) public onlyRole(TIMELOCK_DEV_ROLE) {
if (_doType == Whitelist.Add) {
for (uint32 i = 0; i < _userAddresses.length; i++) {
if (!wlLists[wlType][_userAddresses[i]]) {
wlLists[wlType][_userAddresses[i]] = true;
}
}
for (uint32 i = 0; i < _userAddresses.length; i++) {
if (wlLists[wlType][_userAddresses[i]]) {
wlLists[wlType][_userAddresses[i]] = false;
}
}
}
emit SetWhitelist(uint256(wlType), _userAddresses);
}
| 9,761,968 | [
1,
1991,
333,
358,
444,
19564,
7432,
1865,
787,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
2888,
305,
292,
1486,
12,
203,
3639,
490,
474,
559,
19564,
559,
16,
203,
3639,
1758,
8526,
3778,
389,
1355,
7148,
16,
203,
3639,
3497,
7523,
389,
2896,
559,
203,
565,
262,
1071,
1338,
2996,
12,
4684,
6589,
67,
15301,
67,
16256,
13,
288,
203,
3639,
309,
261,
67,
2896,
559,
422,
3497,
7523,
18,
986,
13,
288,
203,
5411,
364,
261,
11890,
1578,
277,
273,
374,
31,
277,
411,
389,
1355,
7148,
18,
2469,
31,
277,
27245,
288,
203,
7734,
309,
16051,
21504,
7432,
63,
21504,
559,
6362,
67,
1355,
7148,
63,
77,
65,
5717,
288,
203,
10792,
19564,
7432,
63,
21504,
559,
6362,
67,
1355,
7148,
63,
77,
13563,
273,
638,
31,
203,
7734,
289,
203,
5411,
289,
203,
5411,
364,
261,
11890,
1578,
277,
273,
374,
31,
277,
411,
389,
1355,
7148,
18,
2469,
31,
277,
27245,
288,
203,
7734,
309,
261,
21504,
7432,
63,
21504,
559,
6362,
67,
1355,
7148,
63,
77,
65,
5717,
288,
203,
10792,
19564,
7432,
63,
21504,
559,
6362,
67,
1355,
7148,
63,
77,
13563,
273,
629,
31,
203,
7734,
289,
203,
5411,
289,
203,
3639,
289,
203,
3639,
3626,
1000,
18927,
12,
11890,
5034,
12,
21504,
559,
3631,
389,
1355,
7148,
1769,
203,
565,
289,
203,
21281,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/11155111/0x2d43c99479F4e5aE23fB930a3350D44b6a632CAa/sources/contracts/manifold/creator-core/token/ERC721/ERC721Core.sol | * @dev See {IERC721-safeTransferFrom}./ | function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public virtual override {
require(
_isApprovedOrOwner(msg.sender, tokenId),
"ERC721: caller is not token owner or approved"
);
_safeTransfer(from, to, tokenId, data);
}
| 3,836,159 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
17,
4626,
5912,
1265,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4183,
5912,
1265,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
1147,
548,
16,
203,
3639,
1731,
3778,
501,
203,
565,
262,
1071,
5024,
3849,
288,
203,
3639,
2583,
12,
203,
5411,
389,
291,
31639,
1162,
5541,
12,
3576,
18,
15330,
16,
1147,
548,
3631,
203,
5411,
315,
654,
39,
27,
5340,
30,
4894,
353,
486,
1147,
3410,
578,
20412,
6,
203,
3639,
11272,
203,
3639,
389,
4626,
5912,
12,
2080,
16,
358,
16,
1147,
548,
16,
501,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: contracts/utils/math/Math.sol
pragma solidity ^0.7.0;
pragma experimental ABIEncoderV2;
/**
* @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);
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
// File: contracts/utils/Context.sol
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/access/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* 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() {
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;
}
}
// File: contracts/Staking/Pausable.sol
/// Refer: https://docs.synthetix.io/contracts/Pausable
abstract contract Pausable is Ownable {
/**
* State variables.
*/
bool public paused;
uint256 public lastPauseTime;
/**
* Event.
*/
event PauseChanged(bool isPaused);
/**
* Modifier.
*/
modifier notPaused {
require(
!paused,
'Pausable: This action cannot be performed while the contract is paused'
);
_;
}
/**
* Constructor.
*/
constructor() {
// This contract is abstract, and thus cannot be instantiated directly
require(owner() != address(0), 'Owner must be set');
// Paused will be false, and lastPauseTime will be 0 upon initialisation
}
/**
* External.
*/
/**
* @notice Change the paused state of the contract
* @dev Only the contract owner may call this.
*/
function setPaused(bool _paused) external onlyOwner {
// Ensure we're actually changing the state before we do anything
if (_paused == paused) {
return;
}
// Set our paused state.
paused = _paused;
// If applicable, set the last pause time.
if (paused) {
lastPauseTime = block.timestamp;
}
// Let everyone know that our pause state has changed.
emit PauseChanged(paused);
}
}
// File: contracts/ERC20/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the number of decimals for token.
*/
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
);
}
// File: contracts/Arth/IIncentive.sol
/// @title incentive contract interface
/// @author Fei Protocol
/// @notice Called by FEI token contract when transferring with an incentivized address
/// @dev should be appointed as a Minter or Burner as needed
interface IIncentiveController {
/// @notice apply incentives on transfer
/// @param sender the sender address of the FEI
/// @param receiver the receiver address of the FEI
/// @param operator the operator (msg.sender) of the transfer
/// @param amount the amount of FEI transferred
function incentivize(
address sender,
address receiver,
address operator,
uint256 amount
) external;
}
// File: contracts/ERC20/IAnyswapV4Token.sol
interface IAnyswapV4Token {
function approveAndCall(
address spender,
uint256 value,
bytes calldata data
) external returns (bool);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
) external returns (bool);
function transferWithPermit(
address target,
address to,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external returns (bool);
function Swapin(
bytes32 txhash,
address account,
uint256 amount
) external returns (bool);
function Swapout(uint256 amount, address bindaddr) external returns (bool);
function nonces(address owner) external view returns (uint256);
function permit(
address target,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/Arth/IARTH.sol
interface IARTH is IERC20, IAnyswapV4Token {
function addPool(address pool) external;
function removePool(address pool) external;
function setGovernance(address _governance) external;
function poolMint(address who, uint256 amount) external;
function poolBurnFrom(address who, uint256 amount) external;
function setIncentiveController(IIncentiveController _incentiveController)
external;
function genesisSupply() external view returns (uint256);
}
// File: contracts/utils/math/SafeMath.sol
// 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) {
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) {
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) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
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;
}
}
// File: contracts/utils/Address.sol
/**
* @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);
}
}
}
}
// File: contracts/ERC20/SafeERC20.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'
);
}
}
}
// File: contracts/Staking/IStakingRewards.sol
interface IStakingRewards {
function stakeLockedFor(
address who,
uint256 amount,
uint256 duration
) external;
function stakeFor(address who, uint256 amount) external;
function stakeLocked(uint256 amount, uint256 secs) external;
function withdrawLocked(bytes32 kekId) external;
function getReward() external;
function stake(uint256 amount) external;
function withdraw(uint256 amount) external;
function lastTimeRewardApplicable() external view returns (uint256);
function rewardPerToken() external view returns (uint256);
function earned(address account) external view returns (uint256);
function getRewardForDuration() external view returns (uint256);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
}
// File: contracts/utils/StringHelpers.sol
library StringHelpers {
function parseAddr(string memory _a)
internal
pure
returns (address _parsedAddress)
{
bytes memory tmp = bytes(_a);
uint160 iaddr = 0;
uint160 b1;
uint160 b2;
for (uint256 i = 2; i < 2 + 2 * 20; i += 2) {
iaddr *= 256;
b1 = uint160(uint8(tmp[i]));
b2 = uint160(uint8(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 memory _a, string memory _b)
internal
pure
returns (int256 _returnCode)
{
bytes memory a = bytes(_a);
bytes memory b = bytes(_b);
uint256 minLength = a.length;
if (b.length < minLength) {
minLength = b.length;
}
for (uint256 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 memory _haystack, string memory _needle)
internal
pure
returns (int256 _returnCode)
{
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 {
uint256 subindex = 0;
for (uint256 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 int256(i);
}
}
}
return -1;
}
}
function strConcat(string memory _a, string memory _b)
internal
pure
returns (string memory _concatenatedString)
{
return strConcat(_a, _b, '', '', '');
}
function strConcat(
string memory _a,
string memory _b,
string memory _c
) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, '', '');
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d
) internal pure returns (string memory _concatenatedString) {
return strConcat(_a, _b, _c, _d, '');
}
function strConcat(
string memory _a,
string memory _b,
string memory _c,
string memory _d,
string memory _e
) internal pure returns (string memory _concatenatedString) {
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);
uint256 k = 0;
uint256 i = 0;
for (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 safeParseInt(string memory _a)
internal
pure
returns (uint256 _parsedInt)
{
return safeParseInt(_a, 0);
}
function safeParseInt(string memory _a, uint256 _b)
internal
pure
returns (uint256 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint256 mint = 0;
bool decimals = false;
for (uint256 i = 0; i < bresult.length; i++) {
if (
(uint256(uint8(bresult[i])) >= 48) &&
(uint256(uint8(bresult[i])) <= 57)
) {
if (decimals) {
if (_b == 0) break;
else _b--;
}
mint *= 10;
mint += uint256(uint8(bresult[i])) - 48;
} else if (uint256(uint8(bresult[i])) == 46) {
require(
!decimals,
'More than one decimal encountered in string!'
);
decimals = true;
} else {
revert('Non-numeral character encountered in string!');
}
}
if (_b > 0) {
mint *= 10**_b;
}
return mint;
}
function parseInt(string memory _a)
internal
pure
returns (uint256 _parsedInt)
{
return parseInt(_a, 0);
}
function parseInt(string memory _a, uint256 _b)
internal
pure
returns (uint256 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint256 mint = 0;
bool decimals = false;
for (uint256 i = 0; i < bresult.length; i++) {
if (
(uint256(uint8(bresult[i])) >= 48) &&
(uint256(uint8(bresult[i])) <= 57)
) {
if (decimals) {
if (_b == 0) {
break;
} else {
_b--;
}
}
mint *= 10;
mint += uint256(uint8(bresult[i])) - 48;
} else if (uint256(uint8(bresult[i])) == 46) {
decimals = true;
}
}
if (_b > 0) {
mint *= 10**_b;
}
return mint;
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return '0';
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len - 1;
while (_i != 0) {
bstr[k--] = bytes1(uint8(48 + (_i % 10)));
_i /= 10;
}
return string(bstr);
}
}
// File: contracts/Arth/IARTHController.sol
interface IARTHController {
function toggleCollateralRatio() external;
function refreshCollateralRatio() external;
function addPool(address pool_address) external;
function removePool(address pool_address) external;
function getARTHInfo()
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
);
function setMintingFee(uint256 fee) external;
function setARTHXETHOracle(
address _arthxOracleAddress,
address _wethAddress
) external;
function setARTHETHOracle(address _arthOracleAddress, address _wethAddress)
external;
function setArthStep(uint256 newStep) external;
function setRedemptionFee(uint256 fee) external;
function setOwner(address _ownerAddress) external;
function setPriceBand(uint256 _priceBand) external;
function setTimelock(address newTimelock) external;
function setPriceTarget(uint256 newPriceTarget) external;
function setARTHXAddress(address _arthxAddress) external;
function setRefreshCooldown(uint256 newCooldown) external;
function setETHGMUOracle(address _ethGMUConsumerAddress) external;
function setGlobalCollateralRatio(uint256 _globalCollateralRatio) external;
function getRefreshCooldown() external view returns (uint256);
function getARTHPrice() external view returns (uint256);
function getARTHXPrice() external view returns (uint256);
function getETHGMUPrice() external view returns (uint256);
function getGlobalCollateralRatio() external view returns (uint256);
function getGlobalCollateralValue() external view returns (uint256);
function arthPools(address pool) external view returns (bool);
}
// File: contracts/utils/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, 'ReentrancyGuard: reentrant call');
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/Uniswap/TransferHelper.sol
/**
* @dev A helper methods for interacting with ERC20 tokens and
sending ETH that do not consistently return true/false.
*/
library TransferHelper {
function safeApprove(
address token,
address to,
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: 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: 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: TRANSFER_FROM_FAILED'
);
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts/utils/introspection/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/utils/introspection/ERC165.sol
/**
* @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/access/AccessControl.sol
/**
* @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;
}
/**
* @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 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 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 {
require(
hasRole(getRoleAdmin(role), _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 override {
require(
hasRole(getRoleAdmin(role), _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
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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File: contracts/Staking/RewardsDistributionRecipient.sol
/// Refer: https://docs.synthetix.io/contracts/RewardsDistributionRecipient
abstract contract RewardsDistributionRecipient is Ownable {
/**
* State variables.
*/
address public rewardsDistribution;
// function notifyRewardAmount(uint256 reward) external virtual;
/**
* Modifer.
*/
modifier onlyRewardsDistribution() {
require(
msg.sender == rewardsDistribution,
'Caller is not RewardsDistribution contract'
);
_;
}
/**
* External.
*/
function setRewardsDistribution(address _rewardsDistribution)
external
onlyOwner
{
rewardsDistribution = _rewardsDistribution;
}
}
// File: contracts/Staking/StakingRewards.sol
/**
* @title StakingRewards.
* @author MahaDAO.
*
* Original code written by:
* - Travis Moore, Jason Huan, Same Kazemian, Sam Sun.
*
* Modified originally from Synthetixio
* https://raw.githubusercontent.com/Synthetixio/synthetix/develop/contracts/StakingRewards.sol
*/
contract StakingRewards is
AccessControl,
IStakingRewards,
RewardsDistributionRecipient,
ReentrancyGuard,
Pausable
{
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* State variables.
*/
struct LockedStake {
bytes32 kekId;
uint256 startTimestamp;
uint256 amount;
uint256 endingTimestamp;
uint256 multiplier; // 6 decimals of precision. 1x = 1000000
}
IERC20 public rewardsToken;
IERC20 public stakingToken;
IARTH private _ARTH;
IARTHController private _arthController;
// This staking pool's percentage of the total ARTHX being distributed by all pools, 6 decimals of precision
uint256 public poolWeight;
// Max reward per second
uint256 public rewardRate;
uint256 public periodFinish;
uint256 public lastUpdateTime;
uint256 public rewardPerTokenStored = 0;
// uint256 public rewardsDuration = 86400 hours;
uint256 public rewardsDuration = 604800; // 7 * 86400 (7 days).
uint256 public lockedStakeMinTime = 604800; // 7 * 86400 (7 days)
string private lockedStakeMinTimeStr = '604800'; // 7 days on genesis
uint256 public lockedStakeMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000
uint256 public lockedStakeTimeGorMaxMultiplier = 3 * 365 * 86400; // 3 years
address public ownerAddress;
address public timelockAddress; // Governance timelock address
uint256 private _stakingTokenSupply = 0;
uint256 private _stakingTokenBoostedSupply = 0;
bool public isLockedStakes; // Release lock stakes in case of system migration
uint256 private constant _PRICE_PRECISION = 1e6;
uint256 private constant _MULTIPLIER_BASE = 1e6;
bytes32 private constant _POOL_ROLE = keccak256('_POOL_ROLE');
uint256 public crBoostMaxMultiplier = 3000000; // 6 decimals of precision. 1x = 1000000
mapping(address => bool) public greylist;
mapping(address => uint256) public rewards;
mapping(address => uint256) public userRewardPerTokenPaid;
mapping(address => uint256) private _lockedBalances;
mapping(address => uint256) private _boostedBalances;
mapping(address => uint256) private _unlockedBalances;
mapping(address => LockedStake[]) private _lockedStakes;
/**
* Events.
*/
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount);
event StakeLocked(address indexed user, uint256 amount, uint256 secs);
event Withdrawn(address indexed user, uint256 amount);
event WithdrawnLocked(address indexed user, uint256 amount, bytes32 kekId);
event RewardPaid(address indexed user, uint256 reward);
event RewardsDurationUpdated(uint256 newDuration);
event Recovered(address token, uint256 amount);
event RewardsPeriodRenewed(address token);
event DefaultInitialization();
event LockedStakeMaxMultiplierUpdated(uint256 multiplier);
event LockedStakeTimeForMaxMultiplier(uint256 secs);
event LockedStakeMinTime(uint256 secs);
event MaxCRBoostMultiplier(uint256 multiplier);
/**
* Modifier.
*/
modifier onlyPool {
require(hasRole(_POOL_ROLE, msg.sender), 'Staking: FORBIDDEN');
_;
}
modifier updateReward(address account) {
// Need to retro-adjust some things if the period hasn't been renewed, then start a new one
if (block.timestamp > periodFinish) {
_retroCatchUp();
} else {
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
}
if (account != address(0)) {
rewards[account] = earned(account);
userRewardPerTokenPaid[account] = rewardPerTokenStored;
}
_;
}
modifier onlyByOwnerOrGovernance() {
require(
msg.sender == ownerAddress || msg.sender == timelockAddress,
'You are not the owner or the governance timelock'
);
_;
}
/**
* Constructor.
*/
constructor(
address _owner,
address _rewardsDistribution,
address _rewardsToken,
address _stakingToken,
address _arthAddress,
address _timelockAddress,
uint256 _poolWeight
) {
ownerAddress = _owner;
_ARTH = IARTH(_arthAddress);
rewardsToken = IERC20(_rewardsToken);
stakingToken = IERC20(_stakingToken);
poolWeight = _poolWeight;
lastUpdateTime = block.timestamp;
timelockAddress = _timelockAddress;
rewardsDistribution = _rewardsDistribution;
isLockedStakes = false;
rewardRate = 380517503805175038; // (uint256(12000000e18)).div(365 * 86400); // Base emission rate of 12M ARTHX over the first year
rewardRate = rewardRate.mul(poolWeight).div(1e6);
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(_POOL_ROLE, _msgSender());
}
/**
* External.
*/
function stakeLockedFor(
address who,
uint256 amount,
uint256 duration
) external override onlyPool {
_stakeLocked(who, amount, duration);
}
function withdraw(uint256 amount)
external
override
nonReentrant
updateReward(msg.sender)
{
require(amount > 0, 'Cannot withdraw 0');
// Staking token balance and boosted balance
_unlockedBalances[msg.sender] = _unlockedBalances[msg.sender].sub(
amount
);
_boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub(amount);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.sub(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(amount);
// Give the tokens to the withdrawer
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(msg.sender, amount);
}
function renewIfApplicable() external {
if (block.timestamp > periodFinish) {
_retroCatchUp();
}
}
function withdrawLocked(bytes32 kekId)
external
override
nonReentrant
updateReward(msg.sender)
{
LockedStake memory thisStake;
thisStake.amount = 0;
uint256 theIndex;
for (uint256 i = 0; i < _lockedStakes[msg.sender].length; i++) {
if (kekId == _lockedStakes[msg.sender][i].kekId) {
thisStake = _lockedStakes[msg.sender][i];
theIndex = i;
break;
}
}
require(thisStake.kekId == kekId, 'Stake not found');
require(
block.timestamp >= thisStake.endingTimestamp ||
isLockedStakes == true,
'Stake is still locked!'
);
uint256 theAmount = thisStake.amount;
uint256 boostedAmount =
theAmount.mul(thisStake.multiplier).div(_PRICE_PRECISION);
if (theAmount > 0) {
// Staking token balance and boosted balance
_lockedBalances[msg.sender] = _lockedBalances[msg.sender].sub(
theAmount
);
_boostedBalances[msg.sender] = _boostedBalances[msg.sender].sub(
boostedAmount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.sub(theAmount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.sub(
boostedAmount
);
// Remove the stake from the array
delete _lockedStakes[msg.sender][theIndex];
// Give the tokens to the withdrawer
stakingToken.safeTransfer(msg.sender, theAmount);
emit WithdrawnLocked(msg.sender, theAmount, kekId);
}
}
// Added to support recovering LP Rewards from other systems to be distributed to holders
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
onlyByOwnerOrGovernance
{
// Admin cannot withdraw the staking token from the contract
require(tokenAddress != address(stakingToken));
IERC20(tokenAddress).transfer(ownerAddress, tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
function setRewardsDuration(uint256 _rewardsDuration)
external
onlyByOwnerOrGovernance
{
require(
periodFinish == 0 || block.timestamp > periodFinish,
'Previous rewards period must be complete before changing the duration for the new period'
);
rewardsDuration = _rewardsDuration;
emit RewardsDurationUpdated(rewardsDuration);
}
function setMultipliers(
uint256 _lockedStakeMaxMultiplier,
uint256 _crBoostMaxMultiplier
) external onlyByOwnerOrGovernance {
require(
_lockedStakeMaxMultiplier >= 1,
'Multiplier must be greater than or equal to 1'
);
require(
_crBoostMaxMultiplier >= 1,
'Max CR Boost must be greater than or equal to 1'
);
lockedStakeMaxMultiplier = _lockedStakeMaxMultiplier;
crBoostMaxMultiplier = _crBoostMaxMultiplier;
emit MaxCRBoostMultiplier(crBoostMaxMultiplier);
emit LockedStakeMaxMultiplierUpdated(lockedStakeMaxMultiplier);
}
function setLockedStakeTimeForMinAndMaxMultiplier(
uint256 _lockedStakeTimeGorMaxMultiplier,
uint256 _lockedStakeMinTime
) external onlyByOwnerOrGovernance {
require(
_lockedStakeTimeGorMaxMultiplier >= 1,
'Multiplier Max Time must be greater than or equal to 1'
);
require(
_lockedStakeMinTime >= 1,
'Multiplier Min Time must be greater than or equal to 1'
);
lockedStakeTimeGorMaxMultiplier = _lockedStakeTimeGorMaxMultiplier;
lockedStakeMinTime = _lockedStakeMinTime;
lockedStakeMinTimeStr = StringHelpers.uint2str(_lockedStakeMinTime);
emit LockedStakeTimeForMaxMultiplier(lockedStakeTimeGorMaxMultiplier);
emit LockedStakeMinTime(_lockedStakeMinTime);
}
function initializeDefault() external onlyByOwnerOrGovernance {
lastUpdateTime = block.timestamp;
periodFinish = block.timestamp.add(rewardsDuration);
emit DefaultInitialization();
}
function greylistAddress(address _address)
external
onlyByOwnerOrGovernance
{
greylist[_address] = !(greylist[_address]);
}
function unlockStakes() external onlyByOwnerOrGovernance {
isLockedStakes = !isLockedStakes;
}
function setRewardRate(uint256 _newRate) external onlyByOwnerOrGovernance {
rewardRate = _newRate;
}
function setOwnerAndTimelock(address _newOwner, address _newTimelock)
external
onlyByOwnerOrGovernance
{
ownerAddress = _newOwner;
timelockAddress = _newTimelock;
}
function stakeFor(address who, uint256 amount) external override onlyPool {
_stake(who, amount);
}
function stake(uint256 amount) external override {
_stake(msg.sender, amount);
}
function stakeLocked(uint256 amount, uint256 secs) external override {
_stakeLocked(msg.sender, amount, secs);
}
function totalSupply() external view override returns (uint256) {
return _stakingTokenSupply;
}
function totalBoostedSupply() external view returns (uint256) {
return _stakingTokenBoostedSupply;
}
// Total unlocked and locked liquidity tokens
function balanceOf(address account)
external
view
override
returns (uint256)
{
return (_unlockedBalances[account]).add(_lockedBalances[account]);
}
// Total unlocked liquidity tokens
function unlockedBalanceOf(address account)
external
view
returns (uint256)
{
return _unlockedBalances[account];
}
// Total 'balance' used for calculating the percent of the pool the account owns
// Takes into account the locked stake time multiplier
function boostedBalanceOf(address account) external view returns (uint256) {
return _boostedBalances[account];
}
function _lockedStakesOf(address account)
external
view
returns (LockedStake[] memory)
{
return _lockedStakes[account];
}
function stakingDecimals() external view returns (uint256) {
return stakingToken.decimals();
}
function rewardsFor(address account) external view returns (uint256) {
// You may have use earned() instead, because of the order in which the contract executes
return rewards[account];
}
function getRewardForDuration() external view override returns (uint256) {
return
rewardRate.mul(rewardsDuration).mul(crBoostMultiplier()).div(
_PRICE_PRECISION
);
}
/**
* Public
*/
function stakingMultiplier(uint256 secs) public view returns (uint256) {
uint256 multiplier =
uint256(_MULTIPLIER_BASE).add(
secs.mul(lockedStakeMaxMultiplier.sub(_MULTIPLIER_BASE)).div(
lockedStakeTimeGorMaxMultiplier
)
);
if (multiplier > lockedStakeMaxMultiplier)
multiplier = lockedStakeMaxMultiplier;
return multiplier;
}
function crBoostMultiplier() public view returns (uint256) {
uint256 multiplier =
uint256(_MULTIPLIER_BASE).add(
(
uint256(_MULTIPLIER_BASE).sub(
_arthController.getGlobalCollateralRatio()
)
)
.mul(crBoostMaxMultiplier.sub(_MULTIPLIER_BASE))
.div(_MULTIPLIER_BASE)
);
return multiplier;
}
// Total locked liquidity tokens
function lockedBalanceOf(address account) public view returns (uint256) {
return _lockedBalances[account];
}
function lastTimeRewardApplicable() public view override returns (uint256) {
return Math.min(block.timestamp, periodFinish);
}
function rewardPerToken() public view override returns (uint256) {
if (_stakingTokenSupply == 0) {
return rewardPerTokenStored;
} else {
return
rewardPerTokenStored.add(
lastTimeRewardApplicable()
.sub(lastUpdateTime)
.mul(rewardRate)
.mul(crBoostMultiplier())
.mul(1e18)
.div(_PRICE_PRECISION)
.div(_stakingTokenBoostedSupply)
);
}
}
function getReward() public override nonReentrant updateReward(msg.sender) {
uint256 reward = rewards[msg.sender];
if (reward > 0) {
rewards[msg.sender] = 0;
rewardsToken.transfer(msg.sender, reward);
emit RewardPaid(msg.sender, reward);
}
}
function earned(address account) public view override returns (uint256) {
return
_boostedBalances[account]
.mul(rewardPerToken().sub(userRewardPerTokenPaid[account]))
.div(1e18)
.add(rewards[account]);
}
/**
* Internal.
*/
function _stake(address who, uint256 amount)
internal
nonReentrant
notPaused
updateReward(who)
{
require(amount > 0, 'Cannot stake 0');
require(greylist[who] == false, 'address has been greylisted');
// Pull the tokens from the staker
TransferHelper.safeTransferFrom(
address(stakingToken),
msg.sender,
address(this),
amount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.add(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(amount);
// Staking token balance and boosted balance
_unlockedBalances[who] = _unlockedBalances[who].add(amount);
_boostedBalances[who] = _boostedBalances[who].add(amount);
emit Staked(who, amount);
}
function _stakeLocked(
address who,
uint256 amount,
uint256 secs
) internal nonReentrant notPaused updateReward(who) {
require(amount > 0, 'Cannot stake 0');
require(secs > 0, 'Cannot wait for a negative number');
require(greylist[who] == false, 'address has been greylisted');
require(
secs >= lockedStakeMinTime,
StringHelpers.strConcat(
'Minimum stake time not met (',
lockedStakeMinTimeStr,
')'
)
);
require(
secs <= lockedStakeTimeGorMaxMultiplier,
'You are trying to stake for too long'
);
uint256 multiplier = stakingMultiplier(secs);
uint256 boostedAmount = amount.mul(multiplier).div(_PRICE_PRECISION);
_lockedStakes[who].push(
LockedStake(
keccak256(abi.encodePacked(who, block.timestamp, amount)),
block.timestamp,
amount,
block.timestamp.add(secs),
multiplier
)
);
// Pull the tokens from the staker or the operator
TransferHelper.safeTransferFrom(
address(stakingToken),
msg.sender,
address(this),
amount
);
// Staking token supply and boosted supply
_stakingTokenSupply = _stakingTokenSupply.add(amount);
_stakingTokenBoostedSupply = _stakingTokenBoostedSupply.add(
boostedAmount
);
// Staking token balance and boosted balance
_lockedBalances[who] = _lockedBalances[who].add(amount);
_boostedBalances[who] = _boostedBalances[who].add(boostedAmount);
emit StakeLocked(who, amount, secs);
}
// If the period expired, renew it
function _retroCatchUp() internal {
// Failsafe check
require(block.timestamp > periodFinish, 'Period has not expired yet!');
// 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.
uint256 numPeriodsElapsed =
uint256(block.timestamp.sub(periodFinish)) / rewardsDuration; // Floor division to the nearest period
uint256 balance = rewardsToken.balanceOf(address(this));
require(
rewardRate
.mul(rewardsDuration)
.mul(crBoostMultiplier())
.mul(numPeriodsElapsed + 1)
.div(_PRICE_PRECISION) <= balance,
'Not enough ARTHX available for rewards!'
);
// uint256 old_lastUpdateTime = lastUpdateTime;
// uint256 new_lastUpdateTime = block.timestamp;
// lastUpdateTime = periodFinish;
periodFinish = periodFinish.add(
(numPeriodsElapsed.add(1)).mul(rewardsDuration)
);
rewardPerTokenStored = rewardPerToken();
lastUpdateTime = lastTimeRewardApplicable();
emit RewardsPeriodRenewed(address(stakingToken));
}
/*
// This notifies people that the reward is being changed
function notifyRewardAmount(uint256 reward) external override onlyRewardsDistribution updateReward(address(0)) {
// Needed to make compiler happy
// if (block.timestamp >= periodFinish) {
// rewardRate = reward.mul(crBoostMultiplier()).div(rewardsDuration).div(_PRICE_PRECISION);
// } else {
// uint256 remaining = periodFinish.sub(block.timestamp);
// uint256 leftover = remaining.mul(rewardRate);
// rewardRate = reward.mul(crBoostMultiplier()).add(leftover).div(rewardsDuration).div(_PRICE_PRECISION);
// }
// // 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 = rewardsToken.balanceOf(address(this));
// require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high");
// lastUpdateTime = block.timestamp;
// periodFinish = block.timestamp.add(rewardsDuration);
// emit RewardAdded(reward);
}
*/
}
| 6 decimals of precision. 1x = 1000000
| uint256 public crBoostMaxMultiplier = 3000000; | 12,593,492 | [
1,
26,
15105,
434,
6039,
18,
404,
92,
273,
15088,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
4422,
26653,
2747,
23365,
273,
890,
9449,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/3/0x46195bBF4e65e396FF7DbA3BB369Af554095d110/sources/dreamsbank.sol | if there is a balance transfer the SAME amount of bank tokens to the account that is staking as a reward | function issueInterestToken() public {
for (uint i=0; i<stakers.length; i++) {
address recipient = stakers[i];
uint balance = stakingBalance[recipient];
if(balance >0 ) {
IERC20(bankToken).transfer(recipient, balance);
}
}
}
| 8,240,727 | [
1,
430,
1915,
353,
279,
11013,
7412,
326,
348,
1642,
3844,
434,
11218,
2430,
358,
326,
2236,
716,
353,
384,
6159,
487,
279,
19890,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
5672,
29281,
1345,
1435,
1071,
288,
203,
3639,
364,
261,
11890,
277,
33,
20,
31,
277,
32,
334,
581,
414,
18,
2469,
31,
277,
27245,
288,
203,
5411,
1758,
8027,
273,
384,
581,
414,
63,
77,
15533,
203,
5411,
2254,
11013,
273,
384,
6159,
13937,
63,
20367,
15533,
203,
2398,
203,
2398,
203,
5411,
309,
12,
12296,
405,
20,
262,
288,
203,
7734,
467,
654,
39,
3462,
12,
10546,
1345,
2934,
13866,
12,
20367,
16,
11013,
1769,
203,
1171,
203,
5411,
289,
203,
2398,
203,
3639,
289,
203,
540,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.20;
/**
* @author FadyAro
*
* 22.07.2018
*
*
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
modifier whenNotPaused() {
require(!paused, 'Contract Paused!');
_;
}
modifier whenPaused() {
require(paused, 'Contract Active!');
_;
}
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract EtherDrop is Pausable {
uint constant PRICE_WEI = 2e16;
/*
* blacklist flag
*/
uint constant FLAG_BLACKLIST = 1;
/*
* subscription queue size: should be power of 10
*/
uint constant QMAX = 1000;
/*
* randomness order construction conform to QMAX
* e.g. random [0 to 999] is of order 3 => rand = 100*x + 10*y + z
*/
uint constant DMAX = 3;
/*
* this event is when we have a new subscription
* note that it may be fired sequentially just before => NewWinner
*/
event NewDropIn(address addr, uint round, uint place, uint value);
/*
* this event is when we have a new winner
* it is as well a new round start => (round + 1)
*/
event NewWinner(address addr, uint round, uint place, uint value, uint price);
struct history {
/*
* user black listed comment
*/
uint blacklist;
/*
* user rounds subscriptions number
*/
uint size;
/*
* array of subscribed rounds indexes
*/
uint[] rounds;
/*
* array of rounds subscription's inqueue indexes
*/
uint[] places;
/*
* array of rounds's ether value subscription >= PRICE
*/
uint[] values;
/*
* array of 0's initially, update to REWARD PRICE in win situations
*/
uint[] prices;
}
/*
* active subscription queue
*/
address[] private _queue;
/*
* winners history
*/
address[] private _winners;
/*
* winner comment 32 left
*/
bytes32[] private _wincomma;
/*
* winner comment 32 right
*/
bytes32[] private _wincommb;
/*
* winners positions
*/
uint[] private _positions;
/*
* on which block we got a winner
*/
uint[] private _blocks;
/*
* active round index
*/
uint public _round;
/*
* active round queue pointer
*/
uint public _counter;
/*
* allowed collectibles
*/
uint private _collectibles = 0;
/*
* users history mapping
*/
mapping(address => history) private _history;
/**
* get current round details
*/
function currentRound() public view returns (uint round, uint counter, uint round_users, uint price) {
return (_round, _counter, QMAX, PRICE_WEI);
}
/**
* get round stats by index
*/
function roundStats(uint index) public view returns (uint round, address winner, uint position, uint block_no) {
return (index, _winners[index], _positions[index], _blocks[index]);
}
/**
*
* @dev get the total number of user subscriptions
*
* @param user the specific user
*
* @return user rounds size
*/
function userRounds(address user) public view returns (uint) {
return _history[user].size;
}
/**
*
* @dev get user subscription round number details
*
* @param user the specific user
*
* @param index the round number
*
* @return round no, user placing, user drop, user reward
*/
function userRound(address user, uint index) public view returns (uint round, uint place, uint value, uint price) {
history memory h = _history[user];
return (h.rounds[index], h.places[index], h.values[index], h.prices[index]);
}
/**
* round user subscription
*/
function() public payable whenNotPaused {
/*
* check subscription price
*/
require(msg.value >= PRICE_WEI, 'Insufficient Ether');
/*
* start round ahead: on QUEUE_MAX + 1
* draw result
*/
if (_counter == QMAX) {
uint r = DMAX;
uint winpos = 0;
_blocks.push(block.number);
bytes32 _a = blockhash(block.number - 1);
for (uint i = 31; i >= 1; i--) {
if (uint8(_a[i]) >= 48 && uint8(_a[i]) <= 57) {
winpos = 10 * winpos + (uint8(_a[i]) - 48);
if (--r == 0) break;
}
}
_positions.push(winpos);
/*
* post out winner rewards
*/
uint _reward = (QMAX * PRICE_WEI * 90) / 100;
address _winner = _queue[winpos];
_winners.push(_winner);
_winner.transfer(_reward);
/*
* update round history
*/
history storage h = _history[_winner];
h.prices[h.size - 1] = _reward;
/*
* default winner blank comments
*/
_wincomma.push(0x0);
_wincommb.push(0x0);
/*
* log the win event: winpos is the proof, history trackable
*/
emit NewWinner(_winner, _round, winpos, h.values[h.size - 1], _reward);
/*
* update collectibles
*/
_collectibles += address(this).balance - _reward;
/*
* reset counter
*/
_counter = 0;
/*
* increment round
*/
_round++;
}
h = _history[msg.sender];
/*
* user is not allowed to subscribe twice
*/
require(h.size == 0 || h.rounds[h.size - 1] != _round, 'Already In Round');
/*
* create user subscription: N.B. places[_round] is the result proof
*/
h.size++;
h.rounds.push(_round);
h.places.push(_counter);
h.values.push(msg.value);
h.prices.push(0);
/*
* initial round is a push, others are 'on set' index
*/
if (_round == 0) {
_queue.push(msg.sender);
} else {
_queue[_counter] = msg.sender;
}
/*
* log subscription
*/
emit NewDropIn(msg.sender, _round, _counter, msg.value);
/*
* increment counter
*/
_counter++;
}
/**
*
* @dev let the user comment 64 letters for a winning round
*
* @param round the winning round
*
* @param a the first 32 letters comment
*
* @param b the second 32 letters comment
*
* @return user comment
*/
function comment(uint round, bytes32 a, bytes32 b) whenNotPaused public {
address winner = _winners[round];
require(winner == msg.sender, 'not a winner');
require(_history[winner].blacklist != FLAG_BLACKLIST, 'blacklisted');
_wincomma[round] = a;
_wincommb[round] = b;
}
/**
*
* @dev blacklist a user for its comments behavior
*
* @param user address
*
*/
function blackList(address user) public onlyOwner {
history storage h = _history[user];
if (h.size > 0) {
h.blacklist = FLAG_BLACKLIST;
}
}
/**
*
* @dev get the user win round comment
*
* @param round the winning round number
*
* @return user comment
*/
function userComment(uint round) whenNotPaused public view returns (address winner, bytes32 comma, bytes32 commb) {
if (_history[_winners[round]].blacklist != FLAG_BLACKLIST) {
return (_winners[round], _wincomma[round], _wincommb[round]);
} else {
return (0x0, 0x0, 0x0);
}
}
/*
* etherdrop team R&D support collectibles
*/
function collect() public onlyOwner {
owner.transfer(_collectibles);
}
} | default winner blank comments/ | _wincomma.push(0x0);
| 6,355,286 | [
1,
1886,
5657,
1224,
7052,
5678,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5411,
389,
8082,
25034,
18,
6206,
12,
20,
92,
20,
1769,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.5.4 <0.6.0;
import './SafeMath.sol';
import './TAOController.sol';
import './ITAOPool.sol';
import './ITAOFactory.sol';
import './TAOCurrency.sol';
import './Logos.sol';
import './TAO.sol';
/**
* @title TAOPool
*
* This contract acts as the bookkeeper of TAO Currencies that are staked on TAO
*/
contract TAOPool is TAOController, ITAOPool {
using SafeMath for uint256;
address public taoFactoryAddress;
address public pathosAddress;
address public ethosAddress;
address public logosAddress;
ITAOFactory internal _taoFactory;
TAOCurrency internal _pathos;
TAOCurrency internal _ethos;
Logos internal _logos;
struct Pool {
address taoId;
/**
* If true, has ethos cap. Otherwise, no ethos cap.
*/
bool ethosCapStatus;
uint256 ethosCapAmount; // Creates a cap for the amount of Ethos that can be staked into this pool
/**
* If true, Pool is live and can be staked into.
*/
bool status;
}
struct EthosLot {
bytes32 ethosLotId; // The ID of this Lot
address nameId; // The ID of the Name that staked Ethos
uint256 lotQuantity; // Amount of Ethos being staked to the Pool from this Lot
address taoId; // Identifier for the Pool this Lot is adding to
uint256 poolPreStakeSnapshot; // Amount of Ethos contributed to the Pool prior to this Lot Number
uint256 poolStakeLotSnapshot; // poolPreStakeSnapshot + lotQuantity
uint256 lotValueInLogos;
uint256 logosWithdrawn; // Amount of Logos withdrawn from this Lot
uint256 timestamp;
}
uint256 public contractTotalEthosLot; // Total Ethos lot from all pools
uint256 public contractTotalPathosStake; // Total Pathos stake from all pools (how many Pathos stakes are there in contract)
uint256 public contractTotalEthos; // Quantity of Ethos that has been staked to all Pools
uint256 public contractTotalPathos; // Quantity of Pathos that has been staked to all Pools
uint256 public contractTotalLogosWithdrawn; // Quantity of Logos that has been withdrawn from all Pools
// Mapping from TAO ID to Pool
mapping (address => Pool) public pools;
// Mapping from Ethos Lot ID to Ethos Lot
mapping (bytes32 => EthosLot) public ethosLots;
// Mapping from Pool's TAO ID to total Ethos Lots in the Pool
mapping (address => uint256) public poolTotalEthosLot;
// Mapping from Pool's TAO ID to quantity of Logos that has been withdrawn from the Pool
mapping (address => uint256) public poolTotalLogosWithdrawn;
// Mapping from a Name ID to its Ethos Lots
mapping (address => bytes32[]) internal ownerEthosLots;
// Mapping from a Name ID to quantity of Ethos staked from all Ethos lots
mapping (address => uint256) public totalEthosStaked;
// Mapping from a Name ID to quantity of Pathos staked from all Ethos lots
mapping (address => uint256) public totalPathosStaked;
// Mapping from a Name ID to total Logos withdrawn from all Ethos lots
mapping (address => uint256) public totalLogosWithdrawn;
// Mapping from a Name ID to quantity of Ethos staked from all Ethos lots on a Pool
mapping (address => mapping (address => uint256)) public namePoolEthosStaked;
// Mapping from a Name ID to quantity of Pathos staked on a Pool
mapping (address => mapping (address => uint256)) public namePoolPathosStaked;
// Mapping from a Name ID to quantity of Logos withdrawn from a Pool
mapping (address => mapping (address => uint256)) public namePoolLogosWithdrawn;
// Event to be broadcasted to public when Pool is created
event CreatePool(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, bool status);
// Event to be broadcasted to public when Pool's status is updated
// If status == true, start Pool
// Otherwise, stop Pool
event UpdatePoolStatus(address indexed taoId, bool status, uint256 nonce);
// Event to be broadcasted to public when Pool's Ethos cap is updated
event UpdatePoolEthosCap(address indexed taoId, bool ethosCapStatus, uint256 ethosCapAmount, uint256 nonce);
/**
* Event to be broadcasted to public when nameId stakes Ethos
*/
event StakeEthos(address indexed taoId, bytes32 indexed ethosLotId, address indexed nameId, uint256 lotQuantity, uint256 poolPreStakeSnapshot, uint256 poolStakeLotSnapshot, uint256 lotValueInLogos, uint256 timestamp);
// Event to be broadcasted to public when nameId stakes Pathos
event StakePathos(address indexed taoId, bytes32 indexed stakeId, address indexed nameId, uint256 stakeQuantity, uint256 currentPoolTotalStakedPathos, uint256 timestamp);
// Event to be broadcasted to public when nameId withdraws Logos from Ethos Lot
event WithdrawLogos(address indexed nameId, bytes32 indexed ethosLotId, address indexed taoId, uint256 withdrawnAmount, uint256 currentLotValueInLogos, uint256 currentLotLogosWithdrawn, uint256 timestamp);
/**
* @dev Constructor function
*/
constructor(address _nameFactoryAddress, address _taoFactoryAddress, address _nameTAOPositionAddress, address _pathosAddress, address _ethosAddress, address _logosAddress)
TAOController(_nameFactoryAddress) public {
setTAOFactoryAddress(_taoFactoryAddress);
setNameTAOPositionAddress(_nameTAOPositionAddress);
setPathosAddress(_pathosAddress);
setEthosAddress(_ethosAddress);
setLogosAddress(_logosAddress);
}
/**
* @dev Check if calling address is TAO Factory address
*/
modifier onlyTAOFactory {
require (msg.sender == taoFactoryAddress);
_;
}
/***** The AO ONLY METHODS *****/
/**
* @dev The AO set the TAOFactory Address
* @param _taoFactoryAddress The address of TAOFactory
*/
function setTAOFactoryAddress(address _taoFactoryAddress) public onlyTheAO {
require (_taoFactoryAddress != address(0));
taoFactoryAddress = _taoFactoryAddress;
_taoFactory = ITAOFactory(_taoFactoryAddress);
}
/**
* @dev The AO set the Pathos Address
* @param _pathosAddress The address of Pathos
*/
function setPathosAddress(address _pathosAddress) public onlyTheAO {
require (_pathosAddress != address(0));
pathosAddress = _pathosAddress;
_pathos = TAOCurrency(_pathosAddress);
}
/**
* @dev The AO set the Ethos Address
* @param _ethosAddress The address of Ethos
*/
function setEthosAddress(address _ethosAddress) public onlyTheAO {
require (_ethosAddress != address(0));
ethosAddress = _ethosAddress;
_ethos = TAOCurrency(_ethosAddress);
}
/**
* @dev The AO set the Logos Address
* @param _logosAddress The address of Logos
*/
function setLogosAddress(address _logosAddress) public onlyTheAO {
require (_logosAddress != address(0));
logosAddress = _logosAddress;
_logos = Logos(_logosAddress);
}
/***** PUBLIC METHODS *****/
/**
* @dev Check whether or not Pool exist for a TAO ID
* @param _id The ID to be checked
* @return true if yes, false otherwise
*/
function isExist(address _id) public view returns (bool) {
return pools[_id].taoId != address(0);
}
/**
* @dev Create a pool for a TAO
*/
function createPool(
address _taoId,
bool _ethosCapStatus,
uint256 _ethosCapAmount
) external isTAO(_taoId) onlyTAOFactory returns (bool) {
// Make sure ethos cap amount is provided if ethos cap is enabled
if (_ethosCapStatus) {
require (_ethosCapAmount > 0);
}
// Make sure the pool is not yet created
require (pools[_taoId].taoId == address(0));
Pool storage _pool = pools[_taoId];
_pool.taoId = _taoId;
_pool.status = true;
_pool.ethosCapStatus = _ethosCapStatus;
if (_ethosCapStatus) {
_pool.ethosCapAmount = _ethosCapAmount;
}
emit CreatePool(_pool.taoId, _pool.ethosCapStatus, _pool.ethosCapAmount, _pool.status);
return true;
}
/**
* @dev Start/Stop a Pool
* @param _taoId The TAO ID of the Pool
* @param _status The status to set. true = start. false = stop
*/
function updatePoolStatus(address _taoId, bool _status) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised {
require (pools[_taoId].taoId != address(0));
pools[_taoId].status = _status;
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit UpdatePoolStatus(_taoId, _status, _nonce);
}
/**
* @dev Update Ethos cap of a Pool
* @param _taoId The TAO ID of the Pool
* @param _ethosCapStatus The ethos cap status to set
* @param _ethosCapAmount The ethos cap amount to set
*/
function updatePoolEthosCap(address _taoId, bool _ethosCapStatus, uint256 _ethosCapAmount) public isTAO(_taoId) onlyAdvocate(_taoId) senderNameNotCompromised {
require (pools[_taoId].taoId != address(0));
// If there is an ethos cap
if (_ethosCapStatus) {
require (_ethosCapAmount > 0 && _ethosCapAmount > _pathos.balanceOf(_taoId));
}
pools[_taoId].ethosCapStatus = _ethosCapStatus;
if (_ethosCapStatus) {
pools[_taoId].ethosCapAmount = _ethosCapAmount;
}
uint256 _nonce = _taoFactory.incrementNonce(_taoId);
require (_nonce > 0);
emit UpdatePoolEthosCap(_taoId, _ethosCapStatus, _ethosCapAmount, _nonce);
}
/**
* @dev A Name stakes Ethos in Pool `_taoId`
* @param _taoId The TAO ID of the Pool
* @param _quantity The amount of Ethos to be staked
*/
function stakeEthos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised {
Pool memory _pool = pools[_taoId];
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
require (_pool.status == true && _quantity > 0 && _ethos.balanceOf(_nameId) >= _quantity);
// If there is an ethos cap
if (_pool.ethosCapStatus) {
require (_ethos.balanceOf(_taoId).add(_quantity) <= _pool.ethosCapAmount);
}
// Create Ethos Lot for this transaction
contractTotalEthosLot++;
poolTotalEthosLot[_taoId]++;
// Generate Ethos Lot ID
bytes32 _ethosLotId = keccak256(abi.encodePacked(this, msg.sender, contractTotalEthosLot));
EthosLot storage _ethosLot = ethosLots[_ethosLotId];
_ethosLot.ethosLotId = _ethosLotId;
_ethosLot.nameId = _nameId;
_ethosLot.lotQuantity = _quantity;
_ethosLot.taoId = _taoId;
_ethosLot.poolPreStakeSnapshot = _ethos.balanceOf(_taoId);
_ethosLot.poolStakeLotSnapshot = _ethos.balanceOf(_taoId).add(_quantity);
_ethosLot.lotValueInLogos = _quantity;
_ethosLot.timestamp = now;
ownerEthosLots[_nameId].push(_ethosLotId);
// Update contract variables
totalEthosStaked[_nameId] = totalEthosStaked[_nameId].add(_quantity);
namePoolEthosStaked[_nameId][_taoId] = namePoolEthosStaked[_nameId][_taoId].add(_quantity);
contractTotalEthos = contractTotalEthos.add(_quantity);
require (_ethos.transferFrom(_nameId, _taoId, _quantity));
emit StakeEthos(_ethosLot.taoId, _ethosLot.ethosLotId, _ethosLot.nameId, _ethosLot.lotQuantity, _ethosLot.poolPreStakeSnapshot, _ethosLot.poolStakeLotSnapshot, _ethosLot.lotValueInLogos, _ethosLot.timestamp);
}
/**
* @dev Retrieve number of Ethos Lots a `_nameId` has
* @param _nameId The Name ID of the Ethos Lot's owner
* @return Total Ethos Lots the owner has
*/
function ownerTotalEthosLot(address _nameId) public view returns (uint256) {
return ownerEthosLots[_nameId].length;
}
/**
* @dev Get list of owner's Ethos Lot IDs from `_from` to `_to` index
* @param _nameId The Name Id of the Ethos Lot's owner
* @param _from The starting index, (i.e 0)
* @param _to The ending index, (i.e total - 1)
* @return list of owner's Ethos Lot IDs
*/
function ownerEthosLotIds(address _nameId, uint256 _from, uint256 _to) public view returns (bytes32[] memory) {
require (_from >= 0 && _to >= _from && ownerEthosLots[_nameId].length > _to);
bytes32[] memory _ethosLotIds = new bytes32[](_to.sub(_from).add(1));
for (uint256 i = _from; i <= _to; i++) {
_ethosLotIds[i.sub(_from)] = ownerEthosLots[_nameId][i];
}
return _ethosLotIds;
}
/**
* @dev Return the amount of Pathos that can be staked on Pool
* @param _taoId The TAO ID of the Pool
* @return The amount of Pathos that can be staked
*/
function availablePathosToStake(address _taoId) public isTAO(_taoId) view returns (uint256) {
if (pools[_taoId].status == true) {
return _ethos.balanceOf(_taoId).sub(_pathos.balanceOf(_taoId));
} else {
return 0;
}
}
/**
* @dev A Name stakes Pathos in Pool `_taoId`
* @param _taoId The TAO ID of the Pool
* @param _quantity The amount of Pathos to stake
*/
function stakePathos(address _taoId, uint256 _quantity) public isTAO(_taoId) senderIsName senderNameNotCompromised {
Pool memory _pool = pools[_taoId];
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
require (_pool.status == true && _quantity > 0 && _pathos.balanceOf(_nameId) >= _quantity && _quantity <= availablePathosToStake(_taoId));
// Update contract variables
contractTotalPathosStake++;
totalPathosStaked[_nameId] = totalPathosStaked[_nameId].add(_quantity);
namePoolPathosStaked[_nameId][_taoId] = namePoolPathosStaked[_nameId][_taoId].add(_quantity);
contractTotalPathos = contractTotalPathos.add(_quantity);
// Generate Pathos Stake ID
bytes32 _stakeId = keccak256(abi.encodePacked(this, msg.sender, contractTotalPathosStake));
require (_pathos.transferFrom(_nameId, _taoId, _quantity));
// Also add advocated TAO logos to Advocate of _taoId
require (_logos.addAdvocatedTAOLogos(_taoId, _quantity));
emit StakePathos(_taoId, _stakeId, _nameId, _quantity, _pathos.balanceOf(_taoId), now);
}
/**
* @dev Name that staked Ethos withdraw Logos from Ethos Lot `_ethosLotId`
* @param _ethosLotId The ID of the Ethos Lot
*/
function withdrawLogos(bytes32 _ethosLotId) public senderIsName senderNameNotCompromised {
EthosLot storage _ethosLot = ethosLots[_ethosLotId];
address _nameId = _nameFactory.ethAddressToNameId(msg.sender);
require (_ethosLot.nameId == _nameId && _ethosLot.lotValueInLogos > 0);
uint256 logosAvailableToWithdraw = lotLogosAvailableToWithdraw(_ethosLotId);
require (logosAvailableToWithdraw > 0 && logosAvailableToWithdraw <= _ethosLot.lotValueInLogos);
// Update lot variables
_ethosLot.logosWithdrawn = _ethosLot.logosWithdrawn.add(logosAvailableToWithdraw);
_ethosLot.lotValueInLogos = _ethosLot.lotValueInLogos.sub(logosAvailableToWithdraw);
// Update contract variables
contractTotalLogosWithdrawn = contractTotalLogosWithdrawn.add(logosAvailableToWithdraw);
poolTotalLogosWithdrawn[_ethosLot.taoId] = poolTotalLogosWithdrawn[_ethosLot.taoId].add(logosAvailableToWithdraw);
totalLogosWithdrawn[_ethosLot.nameId] = totalLogosWithdrawn[_ethosLot.nameId].add(logosAvailableToWithdraw);
namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId] = namePoolLogosWithdrawn[_ethosLot.nameId][_ethosLot.taoId].add(logosAvailableToWithdraw);
// Mint logos to seller
require (_logos.mint(_nameId, logosAvailableToWithdraw));
emit WithdrawLogos(_ethosLot.nameId, _ethosLot.ethosLotId, _ethosLot.taoId, logosAvailableToWithdraw, _ethosLot.lotValueInLogos, _ethosLot.logosWithdrawn, now);
}
/**
* @dev Name gets Ethos Lot `_ethosLotId` available Logos to withdraw
* @param _ethosLotId The ID of the Ethos Lot
* @return The amount of Logos available to withdraw
*/
function lotLogosAvailableToWithdraw(bytes32 _ethosLotId) public view returns (uint256) {
EthosLot memory _ethosLot = ethosLots[_ethosLotId];
require (_ethosLot.nameId != address(0));
uint256 logosAvailableToWithdraw = 0;
if (_pathos.balanceOf(_ethosLot.taoId) > _ethosLot.poolPreStakeSnapshot && _ethosLot.lotValueInLogos > 0) {
logosAvailableToWithdraw = (_pathos.balanceOf(_ethosLot.taoId) >= _ethosLot.poolStakeLotSnapshot) ? _ethosLot.lotQuantity : _pathos.balanceOf(_ethosLot.taoId).sub(_ethosLot.poolPreStakeSnapshot);
if (logosAvailableToWithdraw > 0) {
logosAvailableToWithdraw = logosAvailableToWithdraw.sub(_ethosLot.logosWithdrawn);
}
}
return logosAvailableToWithdraw;
}
}
| Mapping from a Name ID to quantity of Logos withdrawn from a Pool | mapping (address => mapping (address => uint256)) public namePoolLogosWithdrawn;
| 12,935,857 | [
1,
3233,
628,
279,
1770,
1599,
358,
10457,
434,
1827,
538,
598,
9446,
82,
628,
279,
8828,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
202,
6770,
261,
2867,
516,
2874,
261,
2867,
516,
2254,
5034,
3719,
1071,
508,
2864,
1343,
538,
1190,
9446,
82,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22 <0.6.0;
/**
* @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); // will fail if overflow
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
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); // will fail if overflow because of wraparound
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 Ownable
* @dev The Ownable contract has an owner address, and provides basic
* authorization control functions, this simplifies the implementation of
* "user permissions".
*/
contract Ownable {
using SafeMath for uint256;
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 {
require(newOwner != address(0)); // can't accidentally burn the entire contract
owner = newOwner;
}
/**
* @dev Allows the owner to withdraw the ether for conversion to USD to handle
* tax credits properly.
* Note: this function withdraws the entire balance of the contract!
* @param destination The destination address to withdraw the funds to
*/
function withdraw(address payable destination) public onlyOwner {
require(destination != address(0));
destination.transfer(address(this).balance);
}
/**
* @dev Allows the owner to view the current balance of the contract to 6 decimal places
*/
function getBalance() public view onlyOwner returns (uint256) {
return address(this).balance.div(1 szabo);
}
}
/**
* @title Tokenization of tax credits
*
* @dev Implementation of a permissioned token.
*/
contract TaxCredit is Ownable {
using SafeMath for uint256;
mapping (address => uint256) private balances;
mapping (address => string) private emails;
address[] addresses;
uint256 public minimumPurchase = 1950 ether; // minimum purchase is 300,000 credits (270,000 USD)
uint256 private _totalSupply;
uint256 private exchangeRate = (270000 ether / minimumPurchase) + 1; // convert to credit tokens - account for integer division
uint256 private discountRate = 1111111111111111111 wei; // giving credits at 10% discount (90 * 1.11111 = 100)
string public name = "Tax Credit Token";
string public symbol = "TCT";
uint public INITIAL_SUPPLY = 20000000; // 20m credits reserved for use by Clean Energy Systems LLC
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Exchange(
string indexed email,
address indexed addr,
uint256 value
);
constructor() public {
mint(msg.sender, INITIAL_SUPPLY);
}
/**
* @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 Transfer tokens from one address to another - since there are off-chain legal
* transactions that must occur, this function can only be called by the owner; any
* entity that wants to transfer tax credit tokens must go through the contract owner in order
* to get legal documents dispersed first
* @param from address The address to send tokens from
* @param to address The address to transfer to
* @param value uint256 the amount of tokens to be transferred
*/
function transferFrom(address from, address to, uint256 value) public onlyOwner {
require(value <= balances[from]);
balances[from] = balances[from].sub(value);
balances[to] = balances[to].add(value);
emit Transfer(from, to, value);
}
/**
* @dev Public function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted. Only the owner of the contract can mint tokens at will.
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function mint(address account, uint256 value) public onlyOwner {
_handleMint(account, value);
}
/**
* @dev Internal function that handles and executes the minting of tokens. This
* function exists because there are times when tokens may need to be minted,
* but not by the owner of the contract (namely, when participants exchange their
* ether for tokens).
* @param account The account that will receive the created tokens.
* @param value The amount that will be created.
*/
function _handleMint(address account, uint256 value) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(value);
balances[account] = balances[account].add(value);
emit Transfer(address(0), account, value);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function burn(address account, uint256 value) public onlyOwner {
require(account != address(0));
require(value <= balances[account]);
_totalSupply = _totalSupply.sub(value);
balances[account] = balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Allows entities to exchange their Ethereum for tokens representing
* their tax credits. This function mints new tax credit tokens that are backed
* by the ethereum sent to exchange for them.
*/
function exchange(string memory email) public payable {
require(msg.value > minimumPurchase);
require(keccak256(bytes(email)) != keccak256(bytes(""))); // require email parameter
addresses.push(msg.sender);
emails[msg.sender] = email;
uint256 tokens = msg.value.mul(exchangeRate);
tokens = tokens.mul(discountRate);
tokens = tokens.div(1 ether).div(1 ether); // offset exchange rate & discount rate multiplications
_handleMint(msg.sender, tokens);
emit Exchange(email, msg.sender, tokens);
}
/**
* @dev Allows owner to change minimum purchase in order to keep minimum
* tax credit exchange around a certain USD threshold
* @param newMinimum The new minimum amount of ether required to purchase tax credit tokens
*/
function changeMinimumExchange(uint256 newMinimum) public onlyOwner {
require(newMinimum > 0); // if minimum is 0 then division errors will occur for exchange and discount rates
minimumPurchase = newMinimum * 1 ether;
exchangeRate = 270000 ether / minimumPurchase;
}
/**
* @dev Return a list of all participants in the contract by address
*/
function getAllAddresses() public view returns (address[] memory) {
return addresses;
}
/**
* @dev Return the email of a participant by Ethereum address
* @param addr The address from which to retrieve the email
*/
function getParticipantEmail(address addr) public view returns (string memory) {
return emails[addr];
}
/*
* @dev Return all addresses belonging to a certain email (it is possible that an
* entity may purchase tax credit tokens multiple times with different Ethereum addresses).
*
* NOTE: This transaction may incur a significant gas cost as more participants purchase credits.
*/
function getAllAddresses(string memory email) public view onlyOwner returns (address[] memory) {
address[] memory all = new address[](addresses.length);
for (uint32 i = 0; i < addresses.length; i++) {
if (keccak256(bytes(emails[addresses[i]])) == keccak256(bytes(email))) {
all[i] = addresses[i];
}
}
return all;
}
} | offset exchange rate & discount rate multiplications
| tokens = tokens.div(1 ether).div(1 ether); | 2,513,275 | [
1,
3348,
7829,
4993,
473,
12137,
4993,
23066,
87,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2430,
273,
2430,
18,
2892,
12,
21,
225,
2437,
2934,
2892,
12,
21,
225,
2437,
1769,
282,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.6.12;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IBPool {
function isPublicSwap() external view returns (bool);
function isFinalized() external view returns (bool);
function isBound(address t) external view returns (bool);
function getNumTokens() external view returns (uint);
function getCurrentTokens() external view returns (address[] memory tokens);
function getFinalTokens() external view returns (address[] memory tokens);
function getDenormalizedWeight(address token) external view returns (uint);
function getTotalDenormalizedWeight() external view returns (uint);
function getNormalizedWeight(address token) external view returns (uint);
function getBalance(address token) external view returns (uint);
function getSwapFee() external view returns (uint);
function getController() external view returns (address);
function setSwapFee(uint swapFee) external;
function setController(address manager) external;
function setPublicSwap(bool public_) external;
function finalize() external;
function bind(address token, uint balance, uint denorm) external;
function rebind(address token, uint balance, uint denorm) external;
function unbind(address token) external;
function gulp(address token) external;
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint spotPrice);
function joinPool(uint poolAmountOut, uint[] calldata maxAmountsIn) external;
function exitPool(uint poolAmountIn, uint[] calldata minAmountsOut) external;
function swapExactAmountIn(
address tokenIn,
uint tokenAmountIn,
address tokenOut,
uint minAmountOut,
uint maxPrice
) external returns (uint tokenAmountOut, uint spotPriceAfter);
function swapExactAmountOut(
address tokenIn,
uint maxAmountIn,
address tokenOut,
uint tokenAmountOut,
uint maxPrice
) external returns (uint tokenAmountIn, uint spotPriceAfter);
function joinswapExternAmountIn(
address tokenIn,
uint tokenAmountIn,
uint minPoolAmountOut
) external returns (uint poolAmountOut);
function joinswapPoolAmountOut(
address tokenIn,
uint poolAmountOut,
uint maxAmountIn
) external returns (uint tokenAmountIn);
function exitswapPoolAmountIn(
address tokenOut,
uint poolAmountIn,
uint minAmountOut
) external returns (uint tokenAmountOut);
function exitswapExternAmountOut(
address tokenOut,
uint tokenAmountOut,
uint maxPoolAmountIn
) external returns (uint poolAmountIn);
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 calcSpotPrice(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint swapFee
) external pure returns (uint spotPrice);
function calcOutGivenIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountIn,
uint swapFee
) external pure returns (uint tokenAmountOut);
function calcInGivenOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint tokenBalanceOut,
uint tokenWeightOut,
uint tokenAmountOut,
uint swapFee
) external pure returns (uint tokenAmountIn);
function calcPoolOutGivenSingleIn(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint tokenAmountIn,
uint swapFee
) external pure returns (uint poolAmountOut);
function calcSingleInGivenPoolOut(
uint tokenBalanceIn,
uint tokenWeightIn,
uint poolSupply,
uint totalWeight,
uint poolAmountOut,
uint swapFee
) external pure returns (uint tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint poolAmountIn,
uint swapFee
) external pure returns (uint tokenAmountOut);
function calcPoolInGivenSingleOut(
uint tokenBalanceOut,
uint tokenWeightOut,
uint poolSupply,
uint totalWeight,
uint tokenAmountOut,
uint swapFee
) external pure returns (uint poolAmountIn);
}
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;
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
library UniswapV2Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
pair = address(uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash
))));
}
// fetches and sorts the reserves for a pair
function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves();
(reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// given some amount of an asset and pair reserves, returns an equivalent amount of the other asset
function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) {
require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
amountB = amountA.mul(reserveB) / reserveA;
}
// given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) {
require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// given an output amount of an asset and pair reserves, returns a required input amount of the other asset
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) {
require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn.mul(amountOut).mul(1000);
uint denominator = reserveOut.sub(amountOut).mul(997);
amountIn = (numerator / denominator).add(1);
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'UniswapV2Library: INVALID_PATH');
amounts = new uint[](path.length);
amounts[amounts.length - 1] = amountOut;
for (uint i = path.length - 1; i > 0; i--) {
(uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
}
contract BalancerZAP {
using SafeMath for uint256;
address public _token;
address public _balancerPool;
address public _tokenWETHPair;
IWETH public _WETH;
bool private initialized;
function initBalancerZAP(address token, address balancerPool, address WETH, address tokenWethPair) public {
require(!initialized);
_token = token;
_balancerPool = balancerPool;
require(IERC20(_token).approve(balancerPool, uint(-1)));
_WETH = IWETH(WETH);
_tokenWETHPair = tokenWethPair;
initialized = true;
}
fallback() external payable {
if(msg.sender != address(_WETH)){
addLiquidityETHOnly(msg.sender);
}
}
receive() external payable {
if(msg.sender != address(_WETH)){
addLiquidityETHOnly(msg.sender);
}
}
function addLiquidityETHOnly(address payable to) public payable {
require(to != address(0), "Invalid address");
uint256 buyAmount = msg.value;
require(buyAmount > 0, "Insufficient ETH amount");
_WETH.deposit{value : msg.value}();
(uint256 reserveWeth, uint256 reserveTokens) = getPairReserves();
uint256 outTokens = UniswapV2Library.getAmountOut(buyAmount, reserveWeth, reserveTokens);
_WETH.transfer(_tokenWETHPair, buyAmount);
(address token0, address token1) = UniswapV2Library.sortTokens(address(_WETH), _token);
IUniswapV2Pair(_tokenWETHPair).swap(_token == token0 ? outTokens : 0, _token == token1 ? outTokens : 0, address(this), "");
_addLiquidity(outTokens, to);
}
function addLiquidityTokenOnly(uint256 tokenAmount, address payable to) public payable {
require(to != address(0), "Invalid address");
require(tokenAmount > 0, "Insufficient token amount");
require(IERC20(_token).transferFrom(msg.sender, address(this), tokenAmount));
_addLiquidity(tokenAmount, to);
}
function _addLiquidity(uint256 tokenAmount, address payable to) internal {
//mint BPTs
uint256 bptTokens = IBPool(_balancerPool).joinswapExternAmountIn( _token, tokenAmount, 0);
require(bptTokens > 0, "Insufficient BPT amount");
//transfer tokens to user
require(IBPool(_balancerPool).transfer(to, bptTokens));
}
function getPairReserves() internal view returns (uint256 wethReserves, uint256 tokenReserves) {
(address token0,) = UniswapV2Library.sortTokens(address(_WETH), _token);
(uint256 reserve0, uint reserve1,) = IUniswapV2Pair(_tokenWETHPair).getReserves();
(wethReserves, tokenReserves) = token0 == _token ? (reserve1, reserve0) : (reserve0, reserve1);
}
} | mint BPTstransfer tokens to user | function _addLiquidity(uint256 tokenAmount, address payable to) internal {
uint256 bptTokens = IBPool(_balancerPool).joinswapExternAmountIn( _token, tokenAmount, 0);
require(bptTokens > 0, "Insufficient BPT amount");
require(IBPool(_balancerPool).transfer(to, bptTokens));
}
| 2,001,717 | [
1,
81,
474,
605,
1856,
701,
634,
586,
2430,
358,
729,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
1289,
48,
18988,
24237,
12,
11890,
5034,
1147,
6275,
16,
1758,
8843,
429,
358,
13,
2713,
288,
203,
203,
3639,
2254,
5034,
324,
337,
5157,
273,
23450,
2864,
24899,
18770,
2864,
2934,
5701,
22270,
29764,
6275,
382,
12,
389,
2316,
16,
1147,
6275,
16,
374,
1769,
203,
3639,
2583,
12,
70,
337,
5157,
405,
374,
16,
315,
5048,
11339,
605,
1856,
3844,
8863,
203,
377,
203,
3639,
2583,
12,
13450,
2864,
24899,
18770,
2864,
2934,
13866,
12,
869,
16,
324,
337,
5157,
10019,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-12-23
*/
// Sources flattened with hardhat v2.6.8 https://hardhat.org
// SPDX-License-Identifier: MIT
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
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;
}
}
// File @openzeppelin/contracts/math/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File contracts/interfaces/IALD.sol
pragma solidity ^0.7.6;
interface IALD is IERC20 {
function mint(address _to, uint256 _amount) external;
}
// File contracts/interfaces/IPriceOracle.sol
pragma solidity ^0.7.6;
interface IPriceOracle {
/// @dev Return the usd price of asset. mutilpled by 1e18
/// @param _asset The address of asset
function price(address _asset) external view returns (uint256);
/// @dev Return the usd value of asset. mutilpled by 1e18
/// @param _asset The address of asset
/// @param _amount The amount of asset
function value(address _asset, uint256 _amount) external view returns (uint256);
}
// File contracts/interfaces/ITreasury.sol
pragma solidity ^0.7.6;
interface ITreasury {
enum ReserveType {
// used by reserve manager, will not used to bond ALD.
NULL,
// used by main asset bond
UNDERLYING,
// used by vault reward bond
VAULT_REWARD,
// used by liquidity token bond
LIQUIDITY_TOKEN
}
/// @dev return the usd value given token and amount.
/// @param _token The address of token.
/// @param _amount The amount of token.
function valueOf(address _token, uint256 _amount) external view returns (uint256);
/// @dev return the amount of bond ALD given token and usd value.
/// @param _token The address of token.
/// @param _value The usd of token.
function bondOf(address _token, uint256 _value) external view returns (uint256);
/// @dev deposit token to bond ALD.
/// @param _type The type of deposited token.
/// @param _token The address of token.
/// @param _amount The amount of token.
function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external returns (uint256);
/// @dev withdraw token from POL.
/// @param _token The address of token.
/// @param _amount The amount of token.
function withdraw(address _token, uint256 _amount) external;
/// @dev manage token to earn passive yield.
/// @param _token The address of token.
/// @param _amount The amount of token.
function manage(address _token, uint256 _amount) external;
/// @dev mint ALD reward.
/// @param _recipient The address of to receive ALD token.
/// @param _amount The amount of token.
function mintRewards(address _recipient, uint256 _amount) external;
}
// File contracts/libraries/LogExpMath.sol
pragma solidity ^0.7.6;
// Copy from @balancer-labs/v2-solidity-utils/contracts/math/LogExpMath.sol with some modification.
/**
* @dev Exponentiation and logarithm functions for 18 decimal fixed point numbers (both base and exponent/argument).
*
* Exponentiation and logarithm with arbitrary bases (x^y and log_x(y)) are implemented by conversion to natural
* exponentiation and logarithm (where the base is Euler's number).
*
* @author Fernando Martinelli - @fernandomartinelli
* @author Sergio Yuhjtman - @sergioyuhjtman
* @author Daniel Fernandez - @dmf7z
*/
library LogExpMath {
// All fixed point multiplications and divisions are inlined. This means we need to divide by ONE when multiplying
// two numbers, and multiply by ONE when dividing them.
// All arguments and return values are 18 decimal fixed point numbers.
int256 constant ONE_18 = 1e18;
// Internally, intermediate values are computed with higher precision as 20 decimal fixed point numbers, and in the
// case of ln36, 36 decimals.
int256 constant ONE_20 = 1e20;
int256 constant ONE_36 = 1e36;
// The domain of natural exponentiation is bound by the word size and number of decimals used.
//
// Because internally the result will be stored using 20 decimals, the largest possible result is
// (2^255 - 1) / 10^20, which makes the largest exponent ln((2^255 - 1) / 10^20) = 130.700829182905140221.
// The smallest possible result is 10^(-18), which makes largest negative argument
// ln(10^(-18)) = -41.446531673892822312.
// We use 130.0 and -41.0 to have some safety margin.
int256 constant MAX_NATURAL_EXPONENT = 130e18;
int256 constant MIN_NATURAL_EXPONENT = -41e18;
// Bounds for ln_36's argument. Both ln(0.9) and ln(1.1) can be represented with 36 decimal places in a fixed point
// 256 bit integer.
int256 constant LN_36_LOWER_BOUND = ONE_18 - 1e17;
int256 constant LN_36_UPPER_BOUND = ONE_18 + 1e17;
uint256 constant MILD_EXPONENT_BOUND = 2**254 / uint256(ONE_20);
// 18 decimal constants
int256 constant x0 = 128000000000000000000; // 2ˆ7
int256 constant a0 = 38877084059945950922200000000000000000000000000000000000; // eˆ(x0) (no decimals)
int256 constant x1 = 64000000000000000000; // 2ˆ6
int256 constant a1 = 6235149080811616882910000000; // eˆ(x1) (no decimals)
// 20 decimal constants
int256 constant x2 = 3200000000000000000000; // 2ˆ5
int256 constant a2 = 7896296018268069516100000000000000; // eˆ(x2)
int256 constant x3 = 1600000000000000000000; // 2ˆ4
int256 constant a3 = 888611052050787263676000000; // eˆ(x3)
int256 constant x4 = 800000000000000000000; // 2ˆ3
int256 constant a4 = 298095798704172827474000; // eˆ(x4)
int256 constant x5 = 400000000000000000000; // 2ˆ2
int256 constant a5 = 5459815003314423907810; // eˆ(x5)
int256 constant x6 = 200000000000000000000; // 2ˆ1
int256 constant a6 = 738905609893065022723; // eˆ(x6)
int256 constant x7 = 100000000000000000000; // 2ˆ0
int256 constant a7 = 271828182845904523536; // eˆ(x7)
int256 constant x8 = 50000000000000000000; // 2ˆ-1
int256 constant a8 = 164872127070012814685; // eˆ(x8)
int256 constant x9 = 25000000000000000000; // 2ˆ-2
int256 constant a9 = 128402541668774148407; // eˆ(x9)
int256 constant x10 = 12500000000000000000; // 2ˆ-3
int256 constant a10 = 113314845306682631683; // eˆ(x10)
int256 constant x11 = 6250000000000000000; // 2ˆ-4
int256 constant a11 = 106449445891785942956; // eˆ(x11)
/**
* @dev Exponentiation (x^y) with unsigned 18 decimal fixed point base and exponent.
*
* Reverts if ln(x) * y is smaller than `MIN_NATURAL_EXPONENT`, or larger than `MAX_NATURAL_EXPONENT`.
*/
function pow(uint256 x, uint256 y) internal pure returns (uint256) {
if (y == 0) {
// We solve the 0^0 indetermination by making it equal one.
return uint256(ONE_18);
}
if (x == 0) {
return 0;
}
// Instead of computing x^y directly, we instead rely on the properties of logarithms and exponentiation to
// arrive at that result. In particular, exp(ln(x)) = x, and ln(x^y) = y * ln(x). This means
// x^y = exp(y * ln(x)).
// The ln function takes a signed value, so we need to make sure x fits in the signed 256 bit range.
require(x < 2**255, "LogExpMath: x out of bounds");
int256 x_int256 = int256(x);
// We will compute y * ln(x) in a single step. Depending on the value of x, we can either use ln or ln_36. In
// both cases, we leave the division by ONE_18 (due to fixed point multiplication) to the end.
// This prevents y * ln(x) from overflowing, and at the same time guarantees y fits in the signed 256 bit range.
require(y < MILD_EXPONENT_BOUND, "LogExpMath: y out of bounds");
int256 y_int256 = int256(y);
int256 logx_times_y;
if (LN_36_LOWER_BOUND < x_int256 && x_int256 < LN_36_UPPER_BOUND) {
int256 ln_36_x = _ln_36(x_int256);
// ln_36_x has 36 decimal places, so multiplying by y_int256 isn't as straightforward, since we can't just
// bring y_int256 to 36 decimal places, as it might overflow. Instead, we perform two 18 decimal
// multiplications and add the results: one with the first 18 decimals of ln_36_x, and one with the
// (downscaled) last 18 decimals.
logx_times_y = ((ln_36_x / ONE_18) * y_int256 + ((ln_36_x % ONE_18) * y_int256) / ONE_18);
} else {
logx_times_y = _ln(x_int256) * y_int256;
}
logx_times_y /= ONE_18;
// Finally, we compute exp(y * ln(x)) to arrive at x^y
require(
MIN_NATURAL_EXPONENT <= logx_times_y && logx_times_y <= MAX_NATURAL_EXPONENT,
"LogExpMath: product out of bounds"
);
return uint256(exp(logx_times_y));
}
/**
* @dev Natural exponentiation (e^x) with signed 18 decimal fixed point exponent.
*
* Reverts if `x` is smaller than MIN_NATURAL_EXPONENT, or larger than `MAX_NATURAL_EXPONENT`.
*/
function exp(int256 x) internal pure returns (int256) {
require(x >= MIN_NATURAL_EXPONENT && x <= MAX_NATURAL_EXPONENT, "LogExpMath: invalid exponent");
if (x < 0) {
// We only handle positive exponents: e^(-x) is computed as 1 / e^x. We can safely make x positive since it
// fits in the signed 256 bit range (as it is larger than MIN_NATURAL_EXPONENT).
// Fixed point division requires multiplying by ONE_18.
return ((ONE_18 * ONE_18) / exp(-x));
}
// First, we use the fact that e^(x+y) = e^x * e^y to decompose x into a sum of powers of two, which we call x_n,
// where x_n == 2^(7 - n), and e^x_n = a_n has been precomputed. We choose the first x_n, x0, to equal 2^7
// because all larger powers are larger than MAX_NATURAL_EXPONENT, and therefore not present in the
// decomposition.
// At the end of this process we will have the product of all e^x_n = a_n that apply, and the remainder of this
// decomposition, which will be lower than the smallest x_n.
// exp(x) = k_0 * a_0 * k_1 * a_1 * ... + k_n * a_n * exp(remainder), where each k_n equals either 0 or 1.
// We mutate x by subtracting x_n, making it the remainder of the decomposition.
// The first two a_n (e^(2^7) and e^(2^6)) are too large if stored as 18 decimal numbers, and could cause
// intermediate overflows. Instead we store them as plain integers, with 0 decimals.
// Additionally, x0 + x1 is larger than MAX_NATURAL_EXPONENT, which means they will not both be present in the
// decomposition.
// For each x_n, we test if that term is present in the decomposition (if x is larger than it), and if so deduct
// it and compute the accumulated product.
int256 firstAN;
if (x >= x0) {
x -= x0;
firstAN = a0;
} else if (x >= x1) {
x -= x1;
firstAN = a1;
} else {
firstAN = 1; // One with no decimal places
}
// We now transform x into a 20 decimal fixed point number, to have enhanced precision when computing the
// smaller terms.
x *= 100;
// `product` is the accumulated product of all a_n (except a0 and a1), which starts at 20 decimal fixed point
// one. Recall that fixed point multiplication requires dividing by ONE_20.
int256 product = ONE_20;
if (x >= x2) {
x -= x2;
product = (product * a2) / ONE_20;
}
if (x >= x3) {
x -= x3;
product = (product * a3) / ONE_20;
}
if (x >= x4) {
x -= x4;
product = (product * a4) / ONE_20;
}
if (x >= x5) {
x -= x5;
product = (product * a5) / ONE_20;
}
if (x >= x6) {
x -= x6;
product = (product * a6) / ONE_20;
}
if (x >= x7) {
x -= x7;
product = (product * a7) / ONE_20;
}
if (x >= x8) {
x -= x8;
product = (product * a8) / ONE_20;
}
if (x >= x9) {
x -= x9;
product = (product * a9) / ONE_20;
}
// x10 and x11 are unnecessary here since we have high enough precision already.
// Now we need to compute e^x, where x is small (in particular, it is smaller than x9). We use the Taylor series
// expansion for e^x: 1 + x + (x^2 / 2!) + (x^3 / 3!) + ... + (x^n / n!).
int256 seriesSum = ONE_20; // The initial one in the sum, with 20 decimal places.
int256 term; // Each term in the sum, where the nth term is (x^n / n!).
// The first term is simply x.
term = x;
seriesSum += term;
// Each term (x^n / n!) equals the previous one times x, divided by n. Since x is a fixed point number,
// multiplying by it requires dividing by ONE_20, but dividing by the non-fixed point n values does not.
term = ((term * x) / ONE_20) / 2;
seriesSum += term;
term = ((term * x) / ONE_20) / 3;
seriesSum += term;
term = ((term * x) / ONE_20) / 4;
seriesSum += term;
term = ((term * x) / ONE_20) / 5;
seriesSum += term;
term = ((term * x) / ONE_20) / 6;
seriesSum += term;
term = ((term * x) / ONE_20) / 7;
seriesSum += term;
term = ((term * x) / ONE_20) / 8;
seriesSum += term;
term = ((term * x) / ONE_20) / 9;
seriesSum += term;
term = ((term * x) / ONE_20) / 10;
seriesSum += term;
term = ((term * x) / ONE_20) / 11;
seriesSum += term;
term = ((term * x) / ONE_20) / 12;
seriesSum += term;
// 12 Taylor terms are sufficient for 18 decimal precision.
// We now have the first a_n (with no decimals), and the product of all other a_n present, and the Taylor
// approximation of the exponentiation of the remainder (both with 20 decimals). All that remains is to multiply
// all three (one 20 decimal fixed point multiplication, dividing by ONE_20, and one integer multiplication),
// and then drop two digits to return an 18 decimal value.
return (((product * seriesSum) / ONE_20) * firstAN) / 100;
}
/**
* @dev Logarithm (log(arg, base), with signed 18 decimal fixed point base and argument.
*/
function log(int256 arg, int256 base) internal pure returns (int256) {
// This performs a simple base change: log(arg, base) = ln(arg) / ln(base).
// Both logBase and logArg are computed as 36 decimal fixed point numbers, either by using ln_36, or by
// upscaling.
int256 logBase;
if (LN_36_LOWER_BOUND < base && base < LN_36_UPPER_BOUND) {
logBase = _ln_36(base);
} else {
logBase = _ln(base) * ONE_18;
}
int256 logArg;
if (LN_36_LOWER_BOUND < arg && arg < LN_36_UPPER_BOUND) {
logArg = _ln_36(arg);
} else {
logArg = _ln(arg) * ONE_18;
}
// When dividing, we multiply by ONE_18 to arrive at a result with 18 decimal places
return (logArg * ONE_18) / logBase;
}
/**
* @dev Natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function ln(int256 a) internal pure returns (int256) {
// The real natural logarithm is not defined for negative numbers or zero.
require(a > 0, "LogExpMath: out of bounds");
if (LN_36_LOWER_BOUND < a && a < LN_36_UPPER_BOUND) {
return _ln_36(a) / ONE_18;
} else {
return _ln(a);
}
}
/**
* @dev Internal natural logarithm (ln(a)) with signed 18 decimal fixed point argument.
*/
function _ln(int256 a) private pure returns (int256) {
if (a < ONE_18) {
// Since ln(a^k) = k * ln(a), we can compute ln(a) as ln(a) = ln((1/a)^(-1)) = - ln((1/a)). If a is less
// than one, 1/a will be greater than one, and this if statement will not be entered in the recursive call.
// Fixed point division requires multiplying by ONE_18.
return (-_ln((ONE_18 * ONE_18) / a));
}
// First, we use the fact that ln^(a * b) = ln(a) + ln(b) to decompose ln(a) into a sum of powers of two, which
// we call x_n, where x_n == 2^(7 - n), which are the natural logarithm of precomputed quantities a_n (that is,
// ln(a_n) = x_n). We choose the first x_n, x0, to equal 2^7 because the exponential of all larger powers cannot
// be represented as 18 fixed point decimal numbers in 256 bits, and are therefore larger than a.
// At the end of this process we will have the sum of all x_n = ln(a_n) that apply, and the remainder of this
// decomposition, which will be lower than the smallest a_n.
// ln(a) = k_0 * x_0 + k_1 * x_1 + ... + k_n * x_n + ln(remainder), where each k_n equals either 0 or 1.
// We mutate a by subtracting a_n, making it the remainder of the decomposition.
// For reasons related to how `exp` works, the first two a_n (e^(2^7) and e^(2^6)) are not stored as fixed point
// numbers with 18 decimals, but instead as plain integers with 0 decimals, so we need to multiply them by
// ONE_18 to convert them to fixed point.
// For each a_n, we test if that term is present in the decomposition (if a is larger than it), and if so divide
// by it and compute the accumulated sum.
int256 sum = 0;
if (a >= a0 * ONE_18) {
a /= a0; // Integer, not fixed point division
sum += x0;
}
if (a >= a1 * ONE_18) {
a /= a1; // Integer, not fixed point division
sum += x1;
}
// All other a_n and x_n are stored as 20 digit fixed point numbers, so we convert the sum and a to this format.
sum *= 100;
a *= 100;
// Because further a_n are 20 digit fixed point numbers, we multiply by ONE_20 when dividing by them.
if (a >= a2) {
a = (a * ONE_20) / a2;
sum += x2;
}
if (a >= a3) {
a = (a * ONE_20) / a3;
sum += x3;
}
if (a >= a4) {
a = (a * ONE_20) / a4;
sum += x4;
}
if (a >= a5) {
a = (a * ONE_20) / a5;
sum += x5;
}
if (a >= a6) {
a = (a * ONE_20) / a6;
sum += x6;
}
if (a >= a7) {
a = (a * ONE_20) / a7;
sum += x7;
}
if (a >= a8) {
a = (a * ONE_20) / a8;
sum += x8;
}
if (a >= a9) {
a = (a * ONE_20) / a9;
sum += x9;
}
if (a >= a10) {
a = (a * ONE_20) / a10;
sum += x10;
}
if (a >= a11) {
a = (a * ONE_20) / a11;
sum += x11;
}
// a is now a small number (smaller than a_11, which roughly equals 1.06). This means we can use a Taylor series
// that converges rapidly for values of `a` close to one - the same one used in ln_36.
// Let z = (a - 1) / (a + 1).
// ln(a) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 20 digit fixed point division requires multiplying by ONE_20, and multiplication requires
// division by ONE_20.
int256 z = ((a - ONE_20) * ONE_20) / (a + ONE_20);
int256 z_squared = (z * z) / ONE_20;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_20;
seriesSum += num / 3;
num = (num * z_squared) / ONE_20;
seriesSum += num / 5;
num = (num * z_squared) / ONE_20;
seriesSum += num / 7;
num = (num * z_squared) / ONE_20;
seriesSum += num / 9;
num = (num * z_squared) / ONE_20;
seriesSum += num / 11;
// 6 Taylor terms are sufficient for 36 decimal precision.
// Finally, we multiply by 2 (non fixed point) to compute ln(remainder)
seriesSum *= 2;
// We now have the sum of all x_n present, and the Taylor approximation of the logarithm of the remainder (both
// with 20 decimals). All that remains is to sum these two, and then drop two digits to return a 18 decimal
// value.
return (sum + seriesSum) / 100;
}
/**
* @dev Intrnal high precision (36 decimal places) natural logarithm (ln(x)) with signed 18 decimal fixed point argument,
* for x close to one.
*
* Should only be used if x is between LN_36_LOWER_BOUND and LN_36_UPPER_BOUND.
*/
function _ln_36(int256 x) private pure returns (int256) {
// Since ln(1) = 0, a value of x close to one will yield a very small result, which makes using 36 digits
// worthwhile.
// First, we transform x to a 36 digit fixed point value.
x *= ONE_18;
// We will use the following Taylor expansion, which converges very rapidly. Let z = (x - 1) / (x + 1).
// ln(x) = 2 * (z + z^3 / 3 + z^5 / 5 + z^7 / 7 + ... + z^(2 * n + 1) / (2 * n + 1))
// Recall that 36 digit fixed point division requires multiplying by ONE_36, and multiplication requires
// division by ONE_36.
int256 z = ((x - ONE_36) * ONE_36) / (x + ONE_36);
int256 z_squared = (z * z) / ONE_36;
// num is the numerator of the series: the z^(2 * n + 1) term
int256 num = z;
// seriesSum holds the accumulated sum of each term in the series, starting with the initial z
int256 seriesSum = num;
// In each step, the numerator is multiplied by z^2
num = (num * z_squared) / ONE_36;
seriesSum += num / 3;
num = (num * z_squared) / ONE_36;
seriesSum += num / 5;
num = (num * z_squared) / ONE_36;
seriesSum += num / 7;
num = (num * z_squared) / ONE_36;
seriesSum += num / 9;
num = (num * z_squared) / ONE_36;
seriesSum += num / 11;
num = (num * z_squared) / ONE_36;
seriesSum += num / 13;
num = (num * z_squared) / ONE_36;
seriesSum += num / 15;
// 8 Taylor terms are sufficient for 36 decimal precision.
// All that remains is multiplying by 2 (non fixed point).
return seriesSum * 2;
}
}
// File contracts/Treasury.sol
pragma solidity ^0.7.6;
contract Treasury is Ownable, ITreasury {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Deposit(address indexed token, uint256 amount, uint256 value);
event Withdrawal(address indexed token, uint256 amount);
event ReservesManaged(address indexed token, address indexed manager, uint256 amount);
event ReservesUpdated(ReserveType indexed _type, uint256 totalReserves);
event RewardsMinted(address indexed caller, address indexed recipient, uint256 amount);
event UpdateReserveToken(address indexed token, bool isAdd);
event UpdateLiquidityToken(address indexed token, bool isAdd);
event UpdateReserveDepositor(address indexed depositor, bool isAdd);
event UpdateReserveManager(address indexed manager, bool isAdd);
event UpdateRewardManager(address indexed manager, bool isAdd);
event UpdatePolSpender(address indexed spender, bool isAdd);
event UpdateDiscount(address indexed token, uint256 discount);
event UpdatePriceOracle(address indexed token, address oracle);
event UpdatePolPercentage(address indexed token, uint256 percentage);
event UpdateContributorPercentage(uint256 percentage);
event UpdateLiabilityRatio(uint256 liabilityRatio);
uint256 private constant PRECISION = 1e18;
// The address of governor.
address public governor;
// The address of ALD token
address public immutable ald;
// The address of ALD DAO
address public immutable aldDAO;
// A list of reserve tokens. Push only, beware false-positives.
address[] public reserveTokens;
// Record whether an address is reserve token or not.
mapping(address => bool) public isReserveToken;
// A list of liquidity tokens. Push only, beware false-positives.
address[] public liquidityTokens;
// Record whether an address is liquidity token or not.
mapping(address => bool) public isLiquidityToken;
// A list of reserve depositors. Push only, beware false-positives.
address[] public reserveDepositors;
// Record whether an address is reserve depositor or not.
mapping(address => bool) public isReserveDepositor;
// Mapping from token address to price oracle address.
mapping(address => address) public priceOracle;
// A list of reserve managers. Push only, beware false-positives.
address[] public reserveManagers;
// Record whether an address is reserve manager or not.
mapping(address => bool) public isReserveManager;
// A list of reward managers. Push only, beware false-positives.
address[] public rewardManagers;
// Record whether an address is reward manager or not.
mapping(address => bool) public isRewardManager;
// Mapping from token address to discount factor. Multiplied by 1e18
mapping(address => uint256) public discount;
// A list of pol spenders. Push only, beware false-positives.
address[] public polSpenders;
// Record whether an address is pol spender or not.
mapping(address => bool) public isPolSpender;
// Mapping from token address to reserve amount belong to POL.
mapping(address => uint256) public polReserves;
// Mapping from token address to percentage of profit to POL. Multiplied by 1e18
mapping(address => uint256) public percentagePOL;
// The percentage of ALD to contributors. Multiplied by 1e18
uint256 public percentageContributor;
// The liability ratio used to calcalate ald price. Multiplied by 1e18
uint256 public liabilityRatio;
// The USD value of all reserves from main asset. Multiplied by 1e18
uint256 public totalReserveUnderlying;
// The USD value of all reserves from vault reward. Multiplied by 1e18
uint256 public totalReserveVaultReward;
// The USD value of all reserves from liquidity token. Multiplied by 1e18
uint256 public totalReserveLiquidityToken;
modifier onlyGovernor() {
require(msg.sender == governor || msg.sender == owner(), "Treasury: only governor");
_;
}
/// @param _ald The address of ALD token
/// @param _aldDAO The address of ALD DAO
constructor(address _ald, address _aldDAO) {
require(_ald != address(0), "Treasury: zero ald address");
require(_aldDAO != address(0), "Treasury: zero aldDAO address");
ald = _ald;
aldDAO = _aldDAO;
percentageContributor = 5e16; // 5%
liabilityRatio = 1e17; // 0.1
}
/********************************** View Functions **********************************/
/// @dev return the ALD bond price. mutipliled by 1e18
function aldBondPrice() public view returns (uint256) {
uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken);
uint256 _aldSupply = IERC20(ald).totalSupply();
return _totalReserve.mul(1e36).div(_aldSupply).div(liabilityRatio);
}
/// @dev return the amount of bond ALD given token and usd value, without discount.
/// @param _value The usd of token.
function bondOfWithoutDiscount(uint256 _value) public view returns (uint256) {
uint256 _aldSupply = IERC20(ald).totalSupply();
uint256 _totalReserve = totalReserveUnderlying.add(totalReserveVaultReward).add(totalReserveLiquidityToken);
uint256 x = _totalReserve.add(_value).mul(PRECISION).div(_totalReserve);
uint256 bond = LogExpMath.pow(x, liabilityRatio).sub(PRECISION).mul(_aldSupply).div(PRECISION);
return bond;
}
/// @dev return the usd value given token and amount.
/// @param _token The address of token.
/// @param _amount The amount of token.
function valueOf(address _token, uint256 _amount) public view override returns (uint256) {
return IPriceOracle(priceOracle[_token]).value(_token, _amount);
}
/// @dev return the amount of bond ALD given token and usd value.
/// @param _token The address of token.
/// @param _value The usd of token.
function bondOf(address _token, uint256 _value) public view override returns (uint256) {
return bondOfWithoutDiscount(_value).mul(discount[_token]).div(PRECISION);
}
/********************************** Mutated Functions **********************************/
/// @dev deposit token to bond ALD.
/// @param _type The type of deposited token.
/// @param _token The address of token.
/// @param _amount The amount of token.
function deposit(
ReserveType _type,
address _token,
uint256 _amount
) external override returns (uint256) {
require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted");
require(isReserveDepositor[msg.sender], "Treasury: not approved depositor");
IERC20(_token).safeTransferFrom(msg.sender, address(this), _amount);
uint256 _value = valueOf(_token, _amount);
uint256 _bond;
if (_type != ReserveType.NULL) {
// a portion of token should used as POL
uint256 _percentagePOL = percentagePOL[_token];
if (_percentagePOL > 0) {
polReserves[_token] = polReserves[_token].add(_amount.mul(_percentagePOL).div(PRECISION));
}
// mint bond ald to sender
_bond = bondOf(_token, _value);
IALD(ald).mint(msg.sender, _bond);
// mint extra ALD to ald DAO
uint256 _percentageContributor = percentageContributor;
if (percentageContributor > 0) {
IALD(ald).mint(aldDAO, _bond.mul(_percentageContributor).div(PRECISION - _percentageContributor));
}
// update reserves
if (_type == ReserveType.LIQUIDITY_TOKEN) {
totalReserveLiquidityToken = totalReserveLiquidityToken.add(_value);
emit ReservesUpdated(_type, totalReserveLiquidityToken);
} else if (_type == ReserveType.UNDERLYING) {
totalReserveUnderlying = totalReserveUnderlying.add(_value);
emit ReservesUpdated(_type, totalReserveUnderlying);
} else if (_type == ReserveType.VAULT_REWARD) {
totalReserveVaultReward = totalReserveVaultReward.add(_value);
emit ReservesUpdated(_type, totalReserveVaultReward);
} else {
revert("Treasury: invalid reserve type");
}
}
emit Deposit(_token, _amount, _value);
return _bond;
}
/// @dev withdraw token from POL.
/// @param _token The address of token.
/// @param _amount The amount of token.
function withdraw(address _token, uint256 _amount) external override {
require(isReserveToken[_token], "Treasury: not accepted");
require(isPolSpender[msg.sender], "Treasury: not approved spender");
require(_amount <= polReserves[_token], "Treasury: exceed pol reserve");
polReserves[_token] = polReserves[_token] - _amount;
IERC20(_token).safeTransfer(msg.sender, _amount);
emit Withdrawal(_token, _amount);
}
/// @dev manage token to earn passive yield.
/// @param _token The address of token.
/// @param _amount The amount of token.
function manage(address _token, uint256 _amount) external override {
require(isReserveToken[_token] || isLiquidityToken[_token], "Treasury: not accepted");
require(isReserveManager[msg.sender], "Treasury: not approved manager");
IERC20(_token).safeTransfer(msg.sender, _amount);
emit ReservesManaged(_token, msg.sender, _amount);
}
/// @dev mint ALD reward.
/// @param _recipient The address of to receive ALD token.
/// @param _amount The amount of token.
function mintRewards(address _recipient, uint256 _amount) external override {
require(isRewardManager[msg.sender], "Treasury: not approved manager");
IALD(ald).mint(_recipient, _amount);
emit RewardsMinted(msg.sender, _recipient, _amount);
}
/********************************** Restricted Functions **********************************/
function updateGovernor(address _governor) external onlyOwner {
governor = _governor;
}
/// @dev update reserve token
/// @param _token The address of token.
/// @param _isAdd Whether it is add or remove token.
function updateReserveToken(address _token, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveTokens, isReserveToken, _token, _isAdd);
emit UpdateReserveToken(_token, _isAdd);
}
/// @dev update liquidity token
/// @param _token The address of token.
/// @param _isAdd Whether it is add or remove token.
function updateLiquidityToken(address _token, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(liquidityTokens, isLiquidityToken, _token, _isAdd);
emit UpdateLiquidityToken(_token, _isAdd);
}
/// @dev update reserve depositor
/// @param _depositor The address of depositor.
/// @param _isAdd Whether it is add or remove token.
function updateReserveDepositor(address _depositor, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveDepositors, isReserveDepositor, _depositor, _isAdd);
emit UpdateReserveDepositor(_depositor, _isAdd);
}
/// @dev update price oracle for token.
/// @param _token The address of token.
/// @param _oracle The address of price oracle.
function updatePriceOracle(address _token, address _oracle) external onlyOwner {
require(_oracle != address(0), "Treasury: zero address");
priceOracle[_token] = _oracle;
emit UpdatePriceOracle(_token, _oracle);
}
/// @dev update reserve manager.
/// @param _manager The address of manager.
/// @param _isAdd Whether it is add or remove token.
function updateReserveManager(address _manager, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(reserveManagers, isReserveManager, _manager, _isAdd);
emit UpdateReserveManager(_manager, _isAdd);
}
/// @dev update reward manager.
/// @param _manager The address of manager.
/// @param _isAdd Whether it is add or remove token.
function updateRewardManager(address _manager, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(rewardManagers, isRewardManager, _manager, _isAdd);
emit UpdateRewardManager(_manager, _isAdd);
}
/// @dev update discount factor for token.
/// @param _token The address of token.
/// @param _discount The discount factor. multipled by 1e18
function updateDiscount(address _token, uint256 _discount) external onlyGovernor {
discount[_token] = _discount;
emit UpdateDiscount(_token, _discount);
}
/// @dev update POL spender.
/// @param _spender The address of spender.
/// @param _isAdd Whether it is add or remove token.
function updatePolSpenders(address _spender, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(polSpenders, isPolSpender, _spender, _isAdd);
emit UpdatePolSpender(_spender, _isAdd);
}
/// @dev update POL percentage for token.
/// @param _token The address of token.
/// @param _percentage The POL percentage. multipled by 1e18
function updatePercentagePOL(address _token, uint256 _percentage) external onlyOwner {
require(_percentage <= PRECISION, "Treasury: percentage too large");
percentagePOL[_token] = _percentage;
emit UpdatePolPercentage(_token, _percentage);
}
/// @dev update contributor percentage.
/// @param _percentage The contributor percentage. multipled by 1e18
function updatePercentageContributor(uint256 _percentage) external onlyOwner {
require(_percentage <= PRECISION, "Treasury: percentage too large");
percentageContributor = _percentage;
emit UpdateContributorPercentage(_percentage);
}
/// @dev update protocol liability ratio
/// @param _liabilityRatio The liability ratio. multipled by 1e18
function updateLiabilityRatio(uint256 _liabilityRatio) external onlyOwner {
liabilityRatio = _liabilityRatio;
emit UpdateLiabilityRatio(_liabilityRatio);
}
/// @dev update protocol reserves
/// @param _totalReserveUnderlying The underlying reserve.
/// @param _totalReserveVaultReward The vault reward reserve.
/// @param _totalReserveLiquidityToken The liquidity token reserve.
function updateReserves(
uint256 _totalReserveUnderlying,
uint256 _totalReserveVaultReward,
uint256 _totalReserveLiquidityToken
) external onlyGovernor {
totalReserveUnderlying = _totalReserveUnderlying;
totalReserveVaultReward = _totalReserveVaultReward;
totalReserveLiquidityToken = _totalReserveLiquidityToken;
emit ReservesUpdated(ReserveType.UNDERLYING, _totalReserveUnderlying);
emit ReservesUpdated(ReserveType.VAULT_REWARD, _totalReserveVaultReward);
emit ReservesUpdated(ReserveType.LIQUIDITY_TOKEN, _totalReserveLiquidityToken);
}
/********************************** Internal Functions **********************************/
function _containAddress(address[] storage _list, address _item) internal view returns (bool) {
for (uint256 i = 0; i < _list.length; i++) {
if (_list[i] == _item) {
return true;
}
}
return false;
}
function _addOrRemoveAddress(
address[] storage _list,
mapping(address => bool) storage _status,
address _item,
bool _isAdd
) internal {
require(_item != address(0), "Treasury: zero address");
if (_isAdd) {
require(!_status[_item], "Treasury: already set");
if (!_containAddress(_list, _item)) {
_list.push(_item);
}
_status[_item] = true;
} else {
require(_status[_item], "Treasury: already unset");
_status[_item] = false;
}
}
} | @dev update liquidity token @param _token The address of token. @param _isAdd Whether it is add or remove token. | function updateLiquidityToken(address _token, bool _isAdd) external onlyOwner {
_addOrRemoveAddress(liquidityTokens, isLiquidityToken, _token, _isAdd);
emit UpdateLiquidityToken(_token, _isAdd);
}
| 2,108,272 | [
1,
2725,
4501,
372,
24237,
1147,
225,
389,
2316,
1021,
1758,
434,
1147,
18,
225,
389,
291,
986,
17403,
518,
353,
527,
578,
1206,
1147,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
1089,
48,
18988,
24237,
1345,
12,
2867,
389,
2316,
16,
1426,
389,
291,
986,
13,
3903,
1338,
5541,
288,
203,
565,
389,
1289,
1162,
3288,
1887,
12,
549,
372,
24237,
5157,
16,
28601,
18988,
24237,
1345,
16,
389,
2316,
16,
389,
291,
986,
1769,
203,
203,
565,
3626,
2315,
48,
18988,
24237,
1345,
24899,
2316,
16,
389,
291,
986,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/80001/0x2CAA649ccCc10d50427aCDF46371837ca57ed4DF/sources/NftStaking.sol | Make sure the user has at least one token staked before withdrawing Wallet must own the token they are tryng to withdraw Update the rewards for this user, as the amount of rewards decreases with less tokens. Find the index of this token id in the stakedTokens array | function withdraw(uint256 _tokenId) external nonReentrant {
require(
stakers[msg.sender].amountStaked > 0,
"You do not have any tokens staked"
);
require(stakerAddress[_tokenId] == msg.sender, "You do not own this token");
uint256 rewards = calculateRewards(msg.sender);
stakers[msg.sender].unclaimedRewards += rewards;
uint256 index = 0;
for (uint256 i = 0; i < stakers[msg.sender].stakedTokens.length; i++) {
if(stakers[msg.sender].stakedTokens[i].tokenId == _tokenId) {
index = i;
break;
}
}
}
| 9,463,262 | [
1,
6464,
3071,
326,
729,
711,
622,
4520,
1245,
1147,
384,
9477,
1865,
598,
9446,
310,
20126,
1297,
4953,
326,
1147,
2898,
854,
775,
3368,
358,
598,
9446,
2315,
326,
283,
6397,
364,
333,
729,
16,
487,
326,
3844,
434,
283,
6397,
23850,
3304,
598,
5242,
2430,
18,
4163,
326,
770,
434,
333,
1147,
612,
316,
326,
384,
9477,
5157,
526,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
598,
9446,
12,
11890,
5034,
389,
2316,
548,
13,
3903,
1661,
426,
8230,
970,
288,
203,
3639,
2583,
12,
203,
5411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
8949,
510,
9477,
405,
374,
16,
203,
5411,
315,
6225,
741,
486,
1240,
1281,
2430,
384,
9477,
6,
203,
3639,
11272,
203,
203,
3639,
2583,
12,
334,
6388,
1887,
63,
67,
2316,
548,
65,
422,
1234,
18,
15330,
16,
315,
6225,
741,
486,
4953,
333,
1147,
8863,
203,
203,
3639,
2254,
5034,
283,
6397,
273,
4604,
17631,
14727,
12,
3576,
18,
15330,
1769,
203,
3639,
384,
581,
414,
63,
3576,
18,
15330,
8009,
551,
80,
4581,
329,
17631,
14727,
1011,
283,
6397,
31,
203,
203,
3639,
2254,
5034,
770,
273,
374,
31,
7010,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
384,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
18,
2469,
31,
277,
27245,
288,
203,
5411,
309,
12,
334,
581,
414,
63,
3576,
18,
15330,
8009,
334,
9477,
5157,
63,
77,
8009,
2316,
548,
422,
389,
2316,
548,
13,
288,
203,
7734,
770,
273,
277,
31,
203,
7734,
898,
31,
203,
5411,
289,
203,
3639,
289,
203,
203,
203,
203,
203,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// Verified using https://dapp.tools
// hevm: flattened sources of contracts/AloeBlend.sol
// SPDX-License-Identifier: AGPL-3.0-only AND MIT AND GPL-2.0-or-later
pragma solidity >=0.5.0 >=0.8.0 >=0.8.0 <0.9.0 >=0.8.10 <0.9.0;
////// lib/solmate/src/tokens/ERC20.sol
/* pragma solidity >=0.8.0; */
/// @notice Modern and gas efficient ERC20 + EIP-2612 implementation.
/// @author Solmate (https://github.com/Rari-Capital/solmate/blob/main/src/tokens/ERC20.sol)
/// @author Modified from Uniswap (https://github.com/Uniswap/uniswap-v2-core/blob/master/contracts/UniswapV2ERC20.sol)
/// @dev Do not manually set balances without updating totalSupply, as the sum of all user balances must not exceed it.
abstract contract ERC20 {
/*///////////////////////////////////////////////////////////////
EVENTS
//////////////////////////////////////////////////////////////*/
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
/*///////////////////////////////////////////////////////////////
METADATA STORAGE
//////////////////////////////////////////////////////////////*/
string public name;
string public symbol;
uint8 public immutable decimals;
/*///////////////////////////////////////////////////////////////
ERC20 STORAGE
//////////////////////////////////////////////////////////////*/
uint256 public totalSupply;
mapping(address => uint256) public balanceOf;
mapping(address => mapping(address => uint256)) public allowance;
/*///////////////////////////////////////////////////////////////
EIP-2612 STORAGE
//////////////////////////////////////////////////////////////*/
bytes32 public constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
uint256 internal immutable INITIAL_CHAIN_ID;
bytes32 internal immutable INITIAL_DOMAIN_SEPARATOR;
mapping(address => uint256) public nonces;
/*///////////////////////////////////////////////////////////////
CONSTRUCTOR
//////////////////////////////////////////////////////////////*/
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) {
name = _name;
symbol = _symbol;
decimals = _decimals;
INITIAL_CHAIN_ID = block.chainid;
INITIAL_DOMAIN_SEPARATOR = computeDomainSeparator();
}
/*///////////////////////////////////////////////////////////////
ERC20 LOGIC
//////////////////////////////////////////////////////////////*/
function approve(address spender, uint256 amount) public virtual returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function transfer(address to, uint256 amount) public virtual returns (bool) {
balanceOf[msg.sender] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(msg.sender, to, amount);
return true;
}
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool) {
uint256 allowed = allowance[from][msg.sender]; // Saves gas for limited approvals.
if (allowed != type(uint256).max) allowance[from][msg.sender] = allowed - amount;
balanceOf[from] -= amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(from, to, amount);
return true;
}
/*///////////////////////////////////////////////////////////////
EIP-2612 LOGIC
//////////////////////////////////////////////////////////////*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual {
require(deadline >= block.timestamp, "PERMIT_DEADLINE_EXPIRED");
// Unchecked because the only math done is incrementing
// the owner's nonce which cannot realistically overflow.
unchecked {
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline))
)
);
address recoveredAddress = ecrecover(digest, v, r, s);
require(recoveredAddress != address(0) && recoveredAddress == owner, "INVALID_SIGNER");
allowance[recoveredAddress][spender] = value;
}
emit Approval(owner, spender, value);
}
function DOMAIN_SEPARATOR() public view virtual returns (bytes32) {
return block.chainid == INITIAL_CHAIN_ID ? INITIAL_DOMAIN_SEPARATOR : computeDomainSeparator();
}
function computeDomainSeparator() internal view virtual returns (bytes32) {
return
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
keccak256("1"),
block.chainid,
address(this)
)
);
}
/*///////////////////////////////////////////////////////////////
INTERNAL MINT/BURN LOGIC
//////////////////////////////////////////////////////////////*/
function _mint(address to, uint256 amount) internal virtual {
totalSupply += amount;
// Cannot overflow because the sum of all user
// balances can't exceed the max uint256 value.
unchecked {
balanceOf[to] += amount;
}
emit Transfer(address(0), to, amount);
}
function _burn(address from, uint256 amount) internal virtual {
balanceOf[from] -= amount;
// Cannot underflow because a user's balance
// will never be larger than the total supply.
unchecked {
totalSupply -= amount;
}
emit Transfer(from, address(0), amount);
}
}
////// contracts/AloeBlendERC20.sol
/* pragma solidity ^0.8.10; */
/* import "@rari-capital/solmate/src/tokens/ERC20.sol"; */
contract AloeBlendERC20 is ERC20 {
// solhint-disable no-empty-blocks
constructor(string memory _name) ERC20(_name, "ALOE-BLEND", 18) {}
}
////// lib/openzeppelin-contracts/contracts/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);
}
////// lib/openzeppelin-contracts/contracts/utils/Address.sol
/* pragma solidity ^0.8.0; */
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
////// lib/openzeppelin-contracts/contracts/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");
}
}
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolActions.sol
/* pragma solidity >=0.5.0; */
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolDerivedState.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolEvents.sol
/* pragma solidity >=0.5.0; */
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolImmutables.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolOwnerActions.sol
/* pragma solidity >=0.5.0; */
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
////// lib/v3-core/contracts/interfaces/pool/IUniswapV3PoolState.sol
/* pragma solidity >=0.5.0; */
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
////// lib/v3-core/contracts/interfaces/IUniswapV3Pool.sol
/* pragma solidity >=0.5.0; */
/* import './pool/IUniswapV3PoolImmutables.sol'; */
/* import './pool/IUniswapV3PoolState.sol'; */
/* import './pool/IUniswapV3PoolDerivedState.sol'; */
/* import './pool/IUniswapV3PoolActions.sol'; */
/* import './pool/IUniswapV3PoolOwnerActions.sol'; */
/* import './pool/IUniswapV3PoolEvents.sol'; */
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
////// lib/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol
/* pragma solidity >=0.5.0; */
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
////// contracts/UniswapHelper.sol
/* pragma solidity ^0.8.10; */
/* import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; */
/* import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */
/* import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol"; */
/* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */
contract UniswapHelper is IUniswapV3MintCallback {
using SafeERC20 for IERC20;
/// @notice The Uniswap pair in which the vault will manage positions
IUniswapV3Pool public immutable UNI_POOL;
/// @notice The first token of the Uniswap pair
IERC20 public immutable TOKEN0;
/// @notice The second token of the Uniswap pair
IERC20 public immutable TOKEN1;
/// @dev The Uniswap pair's tick spacing
int24 internal immutable TICK_SPACING;
constructor(IUniswapV3Pool _pool) {
UNI_POOL = _pool;
TOKEN0 = IERC20(_pool.token0());
TOKEN1 = IERC20(_pool.token1());
TICK_SPACING = _pool.tickSpacing();
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 _amount0,
uint256 _amount1,
bytes calldata
) external {
require(msg.sender == address(UNI_POOL));
if (_amount0 != 0) TOKEN0.safeTransfer(msg.sender, _amount0);
if (_amount1 != 0) TOKEN1.safeTransfer(msg.sender, _amount1);
}
}
////// contracts/interfaces/IAloeBlendActions.sol
/* pragma solidity ^0.8.10; */
interface IAloeBlendActions {
/**
* @notice Deposits tokens in proportion to the vault's current holdings
* @dev These tokens sit in the vault and are not used as liquidity
* until the next rebalance. Also note it's not necessary to check
* if user manipulated price to deposit cheaper, as the value of range
* orders can only by manipulated higher.
* @param amount0Max Max amount of TOKEN0 to deposit
* @param amount1Max Max amount of TOKEN1 to deposit
* @param amount0Min Ensure `amount0` is greater than this
* @param amount1Min Ensure `amount1` is greater than this
* @return shares Number of shares minted
* @return amount0 Amount of TOKEN0 deposited
* @return amount1 Amount of TOKEN1 deposited
*/
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
);
/**
* @notice Withdraws tokens in proportion to the vault's current holdings
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting `amount0` is smaller than this
* @param amount1Min Revert if resulting `amount1` is smaller than this
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min
) external returns (uint256 amount0, uint256 amount1);
/**
* @notice Rebalances vault to maintain 50/50 inventory ratio
* @dev `rewardToken` may be something other than token0 or token1, in which case the available maintenance budget
* is equal to the contract's balance. Also note that this will revert unless both silos report that removal of
* `rewardToken` is allowed. For example, a Compound silo would block removal of its cTokens.
* @param rewardToken The ERC20 token in which the reward should be denominated. If `rewardToken` is the 0 address,
* no reward will be given. Otherwise, the reward is based on (a) time elapsed since primary position last moved
* and (b) the contract's estimate of how much each unit of gas costs. Since (b) is fully determined by past
* contract interactions and is known to all participants, (a) creates a Dutch Auction for calling this function.
*/
function rebalance(address rewardToken) external;
}
////// contracts/interfaces/IAloeBlendDerivedState.sol
/* pragma solidity ^0.8.10; */
interface IAloeBlendDerivedState {
/**
* @notice Calculates the rebalance urgency. Caller's reward is proportional to this value.
* @return urgency How badly the vault wants its `rebalance()` function to be called
*/
function getRebalanceUrgency() external view returns (uint32 urgency);
/**
* @notice Estimate's the vault's liabilities to users -- in other words, how much would be paid out if all
* holders redeemed their shares at once.
* @dev Underestimates the true payout unless both silos and Uniswap positions have just been poked. Also
* assumes that the maximum amount will accrue to the maintenance budget during the next `rebalance()`. If
* it takes less than that for the budget to reach capacity, then the values reported here may increase after
* calling `rebalance()`.
* @return inventory0 The amount of token0 underlying all shares
* @return inventory1 The amount of token1 underlying all shares
*/
function getInventory() external view returns (uint256 inventory0, uint256 inventory1);
}
////// contracts/interfaces/IAloeBlendEvents.sol
/* pragma solidity ^0.8.10; */
interface IAloeBlendEvents {
/**
* @notice Emitted every time someone deposits to the vault
* @param sender The address that deposited to the vault
* @param shares The shares that were minted and sent to `sender`
* @param amount0 The amount of token0 that `sender` paid in exchange for `shares`
* @param amount1 The amount of token1 that `sender` paid in exchange for `shares`
*/
event Deposit(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
/**
* @notice Emitted every time someone withdraws from the vault
* @param sender The address that withdrew from the vault
* @param shares The shares that were taken from `sender` and burned
* @param amount0 The amount of token0 that `sender` received in exchange for `shares`
* @param amount1 The amount of token1 that `sender` received in exchange for `shares`
*/
event Withdraw(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
/**
* @notice Emitted every time the vault is rebalanced. Contains general vault data.
* @param ratio The ratio of value held as token0 to total value,
* i.e. `inventory0 / (inventory0 + inventory1 / price)`
* @param shares The total outstanding shares held by depositers
* @param inventory0 The amount of token0 underlying all shares
* @param inventory1 The amount of token1 underlying all shares
*/
event Rebalance(uint256 ratio, uint256 shares, uint256 inventory0, uint256 inventory1);
/**
* @notice Emitted every time the primary Uniswap position is recentered
* @param lower The lower bound of the new primary Uniswap position
* @param upper The upper bound of the new primary Uniswap position
*/
event Recenter(int24 lower, int24 upper);
/**
* @notice Emitted every time the vault is rebalanced. Contains incentivization data.
* @param token The ERC20 token in which caller rewards were denominated
* @param amount The amount of `token` that was sent to caller
* @param urgency The rebalance urgency when this payout occurred
*/
event Reward(address token, uint256 amount, uint32 urgency);
}
////// contracts/interfaces/ISilo.sol
/* pragma solidity ^0.8.10; */
interface ISilo {
/// @notice A descriptive name for the silo (ex: Compound USDC Silo)
function name() external view returns (string memory);
/// @notice A place to update the silo's internal state
/// @dev After this has been called, balances reported by `balanceOf` MUST be correct
function poke() external;
/// @notice Deposits `amount` of the underlying token
function deposit(uint256 amount) external;
/// @notice Withdraws EXACTLY `amount` of the underlying token
function withdraw(uint256 amount) external;
/// @notice Reports how much of the underlying token `account` has stored
/// @dev Must never overestimate `balance`. Should give the exact, correct value after `poke` is called
function balanceOf(address account) external view returns (uint256 balance);
/**
* @notice Whether the given token is irrelevant to the silo's strategy (`shouldAllow = true`) or
* is required for proper management (`shouldAllow = false`). ex: Compound silos shouldn't allow
* removal of cTokens, but the may allow removal of COMP rewards.
* @dev Removed tokens are used to help incentivize rebalances for the Blend vault that uses the silo. So
* if you want something like COMP rewards to go to Blend *users* instead, you'd have to implement a
* trading function as part of `poke()` to convert COMP to the underlying token.
*/
function shouldAllowRemovalOf(address token) external view returns (bool shouldAllow);
}
////// contracts/interfaces/IVolatilityOracle.sol
/* pragma solidity ^0.8.10; */
/* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */
interface IVolatilityOracle {
/**
* @notice Accesses the most recently stored metadata for a given Uniswap pool
* @dev These values may or may not have been initialized and may or may not be
* up to date. `tickSpacing` will be non-zero if they've been initialized.
* @param pool The Uniswap pool for which metadata should be retrieved
* @return maxSecondsAgo The age of the oldest observation in the pool's oracle
* @return gamma0 The pool fee minus the protocol fee on token0, scaled by 1e6
* @return gamma1 The pool fee minus the protocol fee on token1, scaled by 1e6
* @return tickSpacing The pool's tick spacing
*/
function cachedPoolMetadata(IUniswapV3Pool pool)
external
view
returns (
uint32 maxSecondsAgo,
uint24 gamma0,
uint24 gamma1,
int24 tickSpacing
);
/**
* @notice Accesses any of the 25 most recently stored fee growth structs
* @dev The full array (idx=0,1,2...24) has data that spans *at least* 24 hours
* @param pool The Uniswap pool for which fee growth should be retrieved
* @param idx The index into the storage array
* @return feeGrowthGlobal0X128 Total pool revenue in token0, as of timestamp
* @return feeGrowthGlobal1X128 Total pool revenue in token1, as of timestamp
* @return timestamp The time at which snapshot was taken and stored
*/
function feeGrowthGlobals(IUniswapV3Pool pool, uint256 idx)
external
view
returns (
uint256 feeGrowthGlobal0X128,
uint256 feeGrowthGlobal1X128,
uint32 timestamp
);
/**
* @notice Returns indices that the contract will use to access `feeGrowthGlobals`
* @param pool The Uniswap pool for which array indices should be fetched
* @return read The index that was closest to 24 hours old last time `estimate24H` was called
* @return write The index that was written to last time `estimate24H` was called
*/
function feeGrowthGlobalsIndices(IUniswapV3Pool pool) external view returns (uint8 read, uint8 write);
/**
* @notice Updates cached metadata for a Uniswap pool. Must be called at least once
* in order for volatility to be determined. Should also be called whenever
* protocol fee changes
* @param pool The Uniswap pool to poke
*/
function cacheMetadataFor(IUniswapV3Pool pool) external;
/**
* @notice Provides multiple estimates of IV using all stored `feeGrowthGlobals` entries for `pool`
* @dev This is not meant to be used on-chain, and it doesn't contribute to the oracle's knowledge.
* Please use `estimate24H` instead.
* @param pool The pool to use for volatility estimate
* @return IV The array of volatility estimates, scaled by 1e18
*/
function lens(IUniswapV3Pool pool) external returns (uint256[25] memory IV);
/**
* @notice Estimates 24-hour implied volatility for a Uniswap pool.
* @param pool The pool to use for volatility estimate
* @return IV The estimated volatility, scaled by 1e18
*/
function estimate24H(IUniswapV3Pool pool) external returns (uint256 IV);
}
////// contracts/interfaces/IAloeBlendImmutables.sol
/* pragma solidity ^0.8.10; */
/* import "./ISilo.sol"; */
/* import "./IVolatilityOracle.sol"; */
// solhint-disable func-name-mixedcase
interface IAloeBlendImmutables {
/// @notice The nominal time (in seconds) that the primary Uniswap position should stay in one place before
/// being recentered
function RECENTERING_INTERVAL() external view returns (uint24);
/// @notice The minimum width (in ticks) of the primary Uniswap position
function MIN_WIDTH() external view returns (int24);
/// @notice The maximum width (in ticks) of the primary Uniswap position
function MAX_WIDTH() external view returns (int24);
/// @notice The maintenance budget buffer multiplier
/// @dev The vault will attempt to build up a maintenance budget equal to the average cost of rebalance
/// incentivization, multiplied by K.
function K() external view returns (uint8);
/// @notice If the maintenance budget drops below [its maximum size ➗ this value], `maintenanceIsSustainable` will
/// become false. During the next rebalance, this will cause the primary Uniswap position to expand to its maximum
/// width -- de-risking the vault until it has time to rebuild the maintenance budget.
function L() external view returns (uint8);
/// @notice The number of standard deviations (from volatilityOracle) to +/- from mean when choosing
/// range for primary Uniswap position
function B() external view returns (uint8);
/// @notice The constraint factor for new gas price observations. The new observation cannot be less than (1 - 1/D)
/// times the previous average.
function D() external view returns (uint8);
/// @notice The denominator applied to all earnings to determine what portion goes to maintenance budget
/// @dev For example, if this is 10, then *at most* 1/10th of all revenue will be added to the maintenance budget.
function MAINTENANCE_FEE() external view returns (uint8);
/// @notice The percentage of funds (in basis points) that will be left in the contract after the primary Uniswap
/// position is recentered. If your share of the pool is <<< than this, withdrawals will be more gas efficient.
/// Also makes it less gassy to place limit orders.
function FLOAT_PERCENTAGE() external view returns (uint256);
/// @notice The volatility oracle used to decide position width
function volatilityOracle() external view returns (IVolatilityOracle);
/// @notice The silo where excess token0 is stored to earn yield
function silo0() external view returns (ISilo);
/// @notice The silo where excess token1 is stored to earn yield
function silo1() external view returns (ISilo);
}
////// contracts/interfaces/IAloeBlendState.sol
/* pragma solidity ^0.8.10; */
/* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */
interface IAloeBlendState {
/**
* @notice A variety of key parameters used frequently in the vault's code, stored in a single slot to save gas
* @dev If lower and upper bounds of a Uniswap position are equal, then the vault hasn't deposited liquidity to it
* @return primaryLower The primary position's lower tick bound
* @return primaryUpper The primary position's upper tick bound
* @return limitLower The limit order's lower tick bound
* @return limitUpper The limit order's upper tick bound
* @return recenterTimestamp The `block.timestamp` from the last time the primary position moved
* @return maxRebalanceGas The (approximate) maximum amount of gas that has ever been used to `rebalance()` this vault
* @return maintenanceIsSustainable Whether `maintenanceBudget0` or `maintenanceBudget1` has filled up according to `K`
* @return locked Whether the vault is currently locked to reentrancy
*/
function packedSlot()
external
view
returns (
int24 primaryLower,
int24 primaryUpper,
int24 limitLower,
int24 limitUpper,
uint48 recenterTimestamp,
uint32 maxRebalanceGas,
bool maintenanceIsSustainable,
bool locked
);
/// @notice The amount of token0 that was in silo0 last time maintenanceBudget0 was updated
function silo0Basis() external view returns (uint256);
/// @notice The amount of token1 that was in silo1 last time maintenanceBudget1 was updated
function silo1Basis() external view returns (uint256);
/// @notice The amount of token0 available for `rebalance()` rewards
function maintenanceBudget0() external view returns (uint256);
/// @notice The amount of token1 available for `rebalance()` rewards
function maintenanceBudget1() external view returns (uint256);
/**
* @notice The contract's opinion on the fair value of 1e4 units of gas, denominated in `_token`
* @dev The value reported here is an average over 14 samples. Nominally there is 1 sample per day, but actual
* timing isn't stored. Please do not use this as more than a low fidelity approximation/proxy for truth.
* @param token The ERC20 token for which the average gas price should be retrieved
* @return gasPrice The amount of `_token` that may motivate expenditure of 1e4 units of gas
*/
function gasPrices(address token) external view returns (uint256 gasPrice);
}
////// contracts/interfaces/IAloeBlend.sol
/* pragma solidity ^0.8.10; */
/* import "./IAloeBlendActions.sol"; */
/* import "./IAloeBlendDerivedState.sol"; */
/* import "./IAloeBlendEvents.sol"; */
/* import "./IAloeBlendImmutables.sol"; */
/* import "./IAloeBlendState.sol"; */
// solhint-disable no-empty-blocks
/// @title Aloe Blend vault interface
/// @dev The interface is broken up into many smaller pieces
interface IAloeBlend is
IAloeBlendActions,
IAloeBlendDerivedState,
IAloeBlendEvents,
IAloeBlendImmutables,
IAloeBlendState
{
}
////// contracts/interfaces/IFactory.sol
/* pragma solidity ^0.8.10; */
/* import "./IAloeBlend.sol"; */
/* import "./ISilo.sol"; */
/* import "./IVolatilityOracle.sol"; */
interface IFactory {
/// @notice The address of the volatility oracle
function volatilityOracle() external view returns (IVolatilityOracle);
/// @notice Reports the vault's address (if one exists for the chosen parameters)
function getVault(
IUniswapV3Pool pool,
ISilo silo0,
ISilo silo1
) external view returns (IAloeBlend);
/// @notice Reports whether the given vault was deployed by this factory
function didCreateVault(IAloeBlend vault) external view returns (bool);
/// @notice Creates a new Blend vault for the given pool + silo combination
function createVault(
IUniswapV3Pool pool,
ISilo silo0,
ISilo silo1
) external returns (IAloeBlend);
}
////// contracts/libraries/FullMath.sol
/* pragma solidity ^0.8.10; */
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// Handle division by zero
require(denominator != 0);
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Short circuit 256 by 256 division
// This saves gas when a * b is small, at the cost of making the
// large case a bit more expensive. Depending on your use case you
// may want to remove this short circuit and always go through the
// 512 bit path.
if (prod1 == 0) {
assembly {
result := div(prod0, denominator)
}
return result;
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Handle overflow, the result must be < 2**256
require(prod1 < denominator);
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
// Note mulmod(_, _, 0) == 0
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
unchecked {
// https://ethereum.stackexchange.com/a/96646
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
// If denominator is zero the inverse starts with 2
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// If denominator is zero, inv is now 128
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
////// contracts/libraries/Silo.sol
/* pragma solidity ^0.8.10; */
/* import "@openzeppelin/contracts/utils/Address.sol"; */
/* import "contracts/interfaces/ISilo.sol"; */
library Silo {
using Address for address;
function delegate_poke(ISilo silo) internal {
address(silo).functionDelegateCall(abi.encodeWithSelector(silo.poke.selector));
}
function delegate_deposit(ISilo silo, uint256 amount) internal {
address(silo).functionDelegateCall(abi.encodeWithSelector(silo.deposit.selector, amount));
}
function delegate_withdraw(ISilo silo, uint256 amount) internal {
address(silo).functionDelegateCall(abi.encodeWithSelector(silo.withdraw.selector, amount));
}
}
////// contracts/libraries/TickMath.sol
/* pragma solidity ^0.8.10; */
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(uint24(MAX_TICK)), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
unchecked {
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
/// @notice Rounds down to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the floored tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function floor(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod >= 0) return tick - mod;
return tick - mod - tickSpacing;
}
}
/// @notice Rounds up to the nearest tick where tick % tickSpacing == 0
/// @param tick The tick to round
/// @param tickSpacing The tick spacing to round to
/// @return the ceiled tick
/// @dev Ensure tick +/- tickSpacing does not overflow or underflow int24
function ceil(int24 tick, int24 tickSpacing) internal pure returns (int24) {
int24 mod = tick % tickSpacing;
unchecked {
if (mod > 0) return tick - mod + tickSpacing;
return tick - mod;
}
}
}
////// contracts/libraries/FixedPoint128.sol
/* pragma solidity ^0.8.10; */
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
////// contracts/libraries/FixedPoint96.sol
/* pragma solidity ^0.8.10; */
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
////// contracts/libraries/LiquidityAmounts.sol
/* pragma solidity ^0.8.10; */
/* import "./FixedPoint96.sol"; */
/* import "./FullMath.sol"; */
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
liquidity = toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
liquidity = toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint224 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
amount0 = uint64(
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96
);
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint192 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
amount1 = uint192(FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96));
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
////// contracts/libraries/Uniswap.sol
/* pragma solidity ^0.8.10; */
/* import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol"; */
/* import "./FixedPoint128.sol"; */
/* import "./LiquidityAmounts.sol"; */
/* import "./TickMath.sol"; */
library Uniswap {
struct Position {
// The pool the position is in
IUniswapV3Pool pool;
// Lower tick of the position
int24 lower;
// Upper tick of the position
int24 upper;
}
/// @dev Do zero-burns to poke the Uniswap pools so earned fees are updated
function poke(Position memory position) internal {
if (position.lower == position.upper) return;
(uint128 liquidity, , , , ) = info(position);
if (liquidity != 0) {
position.pool.burn(position.lower, position.upper, 0);
}
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function deposit(Position memory position, uint128 liquidity) internal returns (uint256 amount0, uint256 amount1) {
if (liquidity != 0) {
(amount0, amount1) = position.pool.mint(address(this), position.lower, position.upper, liquidity, "");
}
}
/// @dev Withdraws all liquidity and collects all fees
function withdraw(Position memory position, uint128 liquidity)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 earned0,
uint256 earned1
)
{
if (liquidity != 0) {
(burned0, burned1) = position.pool.burn(position.lower, position.upper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collected0, uint256 collected1) = position.pool.collect(
address(this),
position.lower,
position.upper,
type(uint128).max,
type(uint128).max
);
unchecked {
earned0 = collected0 - burned0;
earned1 = collected1 - burned1;
}
}
/**
* @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes
* owed fees, except those accrued since last poke.
*/
function collectableAmountsAsOfLastPoke(Position memory position, uint160 sqrtPriceX96)
internal
view
returns (
uint256,
uint256,
uint128
)
{
if (position.lower == position.upper) return (0, 0, 0);
(uint128 liquidity, , , uint128 earnable0, uint128 earnable1) = info(position);
(uint256 burnable0, uint256 burnable1) = amountsForLiquidity(position, sqrtPriceX96, liquidity);
return (burnable0 + earnable0, burnable1 + earnable1, liquidity);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function info(Position memory position)
internal
view
returns (
uint128, // liquidity
uint256, // feeGrowthInside0LastX128
uint256, // feeGrowthInside1LastX128
uint128, // tokensOwed0
uint128 // tokensOwed1
)
{
return position.pool.positions(keccak256(abi.encodePacked(address(this), position.lower, position.upper)));
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function amountsForLiquidity(
Position memory position,
uint160 sqrtPriceX96,
uint128 liquidity
) internal pure returns (uint256, uint256) {
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(position.lower),
TickMath.getSqrtRatioAtTick(position.upper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function liquidityForAmounts(
Position memory position,
uint160 sqrtPriceX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(position.lower),
TickMath.getSqrtRatioAtTick(position.upper),
amount0,
amount1
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount0()`.
function liquidityForAmount0(Position memory position, uint256 amount0) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmount0(
TickMath.getSqrtRatioAtTick(position.lower),
TickMath.getSqrtRatioAtTick(position.upper),
amount0
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount1()`.
function liquidityForAmount1(Position memory position, uint256 amount1) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmount1(
TickMath.getSqrtRatioAtTick(position.lower),
TickMath.getSqrtRatioAtTick(position.upper),
amount1
);
}
}
////// lib/openzeppelin-contracts/contracts/token/ERC20/extensions/IERC20Metadata.sol
/* pragma solidity ^0.8.0; */
/* import "../IERC20.sol"; */
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
////// contracts/AloeBlend.sol
/* pragma solidity ^0.8.10; */
/* import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol"; */
/* import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; */
/* import "contracts/libraries/FullMath.sol"; */
/* import "contracts/libraries/TickMath.sol"; */
/* import "contracts/libraries/Silo.sol"; */
/* import "contracts/libraries/Uniswap.sol"; */
/* import {IFactory} from "./interfaces/IFactory.sol"; */
/* import {IAloeBlend, IAloeBlendActions, IAloeBlendDerivedState, IAloeBlendEvents, IAloeBlendImmutables, IAloeBlendState} from "./interfaces/IAloeBlend.sol"; */
/* import {IVolatilityOracle} from "./interfaces/IVolatilityOracle.sol"; */
/* import "./AloeBlendERC20.sol"; */
/* import "./UniswapHelper.sol"; */
/*
#
###
#####
# ####### *###*
### ######### ########
##### ########### ###########
######## ############ ############
######## ########### *##############
########### ######## #################
############ ### #################
############ ##################
############# #################* *#############*
############## ############# #####################################
############### ####****** #######################*
################
################# *############################*
############## ######################################
######## ################* **######*
### ###
*/
uint256 constant Q96 = 2**96;
contract AloeBlend is AloeBlendERC20, UniswapHelper, IAloeBlend {
using SafeERC20 for IERC20;
using Uniswap for Uniswap.Position;
using Silo for ISilo;
/// @inheritdoc IAloeBlendImmutables
uint24 public constant RECENTERING_INTERVAL = 24 hours; // aim to recenter once per day
/// @inheritdoc IAloeBlendImmutables
int24 public constant MIN_WIDTH = 402; // 1% of inventory in primary Uniswap position
/// @inheritdoc IAloeBlendImmutables
int24 public constant MAX_WIDTH = 27728; // 50% of inventory in primary Uniswap position
/// @inheritdoc IAloeBlendImmutables
uint8 public constant K = 20; // maintenance budget should cover at least 20 rebalances
/// @inheritdoc IAloeBlendImmutables
uint8 public constant L = 4; // if maintenance budget drops below 1/4th of its max value, consider it unsustainable
/// @inheritdoc IAloeBlendImmutables
uint8 public constant B = 2; // primary Uniswap position should cover 95% (2 std. dev.) of trading activity
/// @inheritdoc IAloeBlendImmutables
uint8 public constant D = 10; // new gas price observations must not be less than [avg - avg/10]
/// @inheritdoc IAloeBlendImmutables
uint8 public constant MAINTENANCE_FEE = 10; // 1/10th of earnings from primary Uniswap position
/// @inheritdoc IAloeBlendImmutables
uint256 public constant FLOAT_PERCENTAGE = 500; // 5% of inventory sits in contract to cheapen small withdrawals
/// @dev The minimum tick that can serve as a position boundary in the Uniswap pool
int24 private immutable MIN_TICK;
/// @dev The maximum tick that can serve as a position boundary in the Uniswap pool
int24 private immutable MAX_TICK;
/// @inheritdoc IAloeBlendImmutables
IVolatilityOracle public immutable volatilityOracle;
/// @inheritdoc IAloeBlendImmutables
ISilo public immutable silo0;
/// @inheritdoc IAloeBlendImmutables
ISilo public immutable silo1;
struct PackedSlot {
// The primary position's lower tick bound
int24 primaryLower;
// The primary position's upper tick bound
int24 primaryUpper;
// The limit order's lower tick bound
int24 limitLower;
// The limit order's upper tick bound
int24 limitUpper;
// The `block.timestamp` from the last time the primary position moved
uint48 recenterTimestamp;
// The (approximate) maximum amount of gas that has ever been used to `rebalance()` this vault
uint32 maxRebalanceGas;
// Whether `maintenanceBudget0` or `maintenanceBudget1` is filled up
bool maintenanceIsSustainable;
// Whether the vault is currently locked to reentrancy
bool locked;
}
/// @inheritdoc IAloeBlendState
PackedSlot public packedSlot;
/// @inheritdoc IAloeBlendState
uint256 public silo0Basis;
/// @inheritdoc IAloeBlendState
uint256 public silo1Basis;
/// @inheritdoc IAloeBlendState
uint256 public maintenanceBudget0;
/// @inheritdoc IAloeBlendState
uint256 public maintenanceBudget1;
/// @inheritdoc IAloeBlendState
mapping(address => uint256) public gasPrices;
/// @dev Stores 14 samples of the gas price for each token, scaled by 1e4 and divided by 14. The sum over each
/// array is equal to the value reported by `gasPrices`
mapping(address => uint256[14]) private gasPriceArrays;
/// @dev The index of `gasPriceArrays[address]` in which the next gas price measurement will be stored
mapping(address => uint8) private gasPriceIdxs;
/// @dev Required for some silos
receive() external payable {}
constructor(
IUniswapV3Pool _uniPool,
ISilo _silo0,
ISilo _silo1
)
AloeBlendERC20(
// ex: Aloe Blend USDC/WETH
string(
abi.encodePacked(
"Aloe Blend ",
IERC20Metadata(_uniPool.token0()).symbol(),
"/",
IERC20Metadata(_uniPool.token1()).symbol()
)
)
)
UniswapHelper(_uniPool)
{
MIN_TICK = TickMath.ceil(TickMath.MIN_TICK, TICK_SPACING);
MAX_TICK = TickMath.floor(TickMath.MAX_TICK, TICK_SPACING);
volatilityOracle = IFactory(msg.sender).volatilityOracle();
silo0 = _silo0;
silo1 = _silo1;
}
/// @inheritdoc IAloeBlendActions
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
external
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Max != 0 || amount1Max != 0, "Aloe: 0 deposit");
// Reentrancy guard is embedded in `_loadPackedSlot` to save gas
(Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();
packedSlot.locked = true;
// Poke all assets
primary.poke();
limit.poke();
silo0.delegate_poke();
silo1.delegate_poke();
(uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();
(uint256 inventory0, uint256 inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, true);
(shares, amount0, amount1) = _computeLPShares(
totalSupply,
inventory0,
inventory1,
amount0Max,
amount1Max,
sqrtPriceX96
);
require(shares != 0, "Aloe: 0 shares");
require(amount0 >= amount0Min, "Aloe: amount0 too low");
require(amount1 >= amount1Min, "Aloe: amount1 too low");
// Pull in tokens from sender
TOKEN0.safeTransferFrom(msg.sender, address(this), amount0);
TOKEN1.safeTransferFrom(msg.sender, address(this), amount1);
// Mint shares
_mint(msg.sender, shares);
emit Deposit(msg.sender, shares, amount0, amount1);
packedSlot.locked = false;
}
/// @inheritdoc IAloeBlendActions
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min
) external returns (uint256 amount0, uint256 amount1) {
require(shares != 0, "Aloe: 0 shares");
// Reentrancy guard is embedded in `_loadPackedSlot` to save gas
(Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();
packedSlot.locked = true;
// Poke silos to ensure reported balances are correct
silo0.delegate_poke();
silo1.delegate_poke();
uint256 _totalSupply = totalSupply;
uint256 a;
uint256 b;
uint256 c;
uint256 d;
// Compute user's portion of token0 from contract + silo0
c = _balance0();
a = silo0Basis;
b = silo0.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
amount0 = FullMath.mulDiv(c + b - a, shares, _totalSupply);
// Withdraw from silo0 if contract balance can't cover what user is owed
if (amount0 > c) {
c = a + amount0 - c;
silo0.delegate_withdraw(c);
maintenanceBudget0 += a;
silo0Basis = b - c;
}
// Compute user's portion of token1 from contract + silo1
c = _balance1();
a = silo1Basis;
b = silo1.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
amount1 = FullMath.mulDiv(c + b - a, shares, _totalSupply);
// Withdraw from silo1 if contract balance can't cover what user is owed
if (amount1 > c) {
c = a + amount1 - c;
silo1.delegate_withdraw(c);
maintenanceBudget1 += a;
silo1Basis = b - c;
}
// Withdraw user's portion of the primary position
{
(uint128 liquidity, , , , ) = primary.info();
(a, b, c, d) = primary.withdraw(uint128(FullMath.mulDiv(liquidity, shares, _totalSupply)));
amount0 += a;
amount1 += b;
a = c / MAINTENANCE_FEE;
b = d / MAINTENANCE_FEE;
amount0 += FullMath.mulDiv(c - a, shares, _totalSupply);
amount1 += FullMath.mulDiv(d - b, shares, _totalSupply);
maintenanceBudget0 += a;
maintenanceBudget1 += b;
}
// Withdraw user's portion of the limit order
if (limit.lower != limit.upper) {
(uint128 liquidity, , , , ) = limit.info();
(a, b, c, d) = limit.withdraw(uint128(FullMath.mulDiv(liquidity, shares, _totalSupply)));
amount0 += a + FullMath.mulDiv(c, shares, _totalSupply);
amount1 += b + FullMath.mulDiv(d, shares, _totalSupply);
}
// Check constraints
require(amount0 >= amount0Min, "Aloe: amount0 too low");
require(amount1 >= amount1Min, "Aloe: amount1 too low");
// Transfer tokens
TOKEN0.safeTransfer(msg.sender, amount0);
TOKEN1.safeTransfer(msg.sender, amount1);
// Burn shares
_burn(msg.sender, shares);
emit Withdraw(msg.sender, shares, amount0, amount1);
packedSlot.locked = false;
}
struct RebalanceCache {
uint160 sqrtPriceX96;
uint224 priceX96;
int24 tick;
}
/// @inheritdoc IAloeBlendActions
function rebalance(address rewardToken) external {
uint32 gas = uint32(gasleft());
// Reentrancy guard is embedded in `_loadPackedSlot` to save gas
(
Uniswap.Position memory primary,
Uniswap.Position memory limit,
uint48 recenterTimestamp,
uint32 maxRebalanceGas,
bool maintenanceIsSustainable
) = _loadPackedSlot();
packedSlot.locked = true;
// Populate rebalance cache
RebalanceCache memory cache;
(cache.sqrtPriceX96, cache.tick, , , , , ) = UNI_POOL.slot0();
cache.priceX96 = uint224(FullMath.mulDiv(cache.sqrtPriceX96, cache.sqrtPriceX96, Q96));
uint32 urgency = _getRebalanceUrgency(recenterTimestamp);
// Poke silos to ensure reported balances are correct
silo0.delegate_poke();
silo1.delegate_poke();
// Check inventory
(uint256 inventory0, uint256 inventory1, InventoryDetails memory d) = _getInventory(
primary,
limit,
cache.sqrtPriceX96,
false
);
// Remove the limit order if it exists
if (d.limitLiquidity != 0) limit.withdraw(d.limitLiquidity);
// Compute inventory ratio to determine what happens next
uint256 ratio = FullMath.mulDiv(
10_000,
inventory0,
inventory0 + FullMath.mulDiv(inventory1, Q96, cache.priceX96)
);
if (ratio < 4900) {
// Attempt to sell token1 for token0. Choose limit order bounds below the market price. Disable
// incentive if removing & replacing in the same spot
limit.upper = TickMath.floor(cache.tick, TICK_SPACING);
if (d.limitLiquidity != 0 && limit.lower == limit.upper - TICK_SPACING) urgency = 0;
limit.lower = limit.upper - TICK_SPACING;
// Choose amount1 such that ratio will be 50/50 once the limit order is pushed through (division by 2
// is a good approximation for small tickSpacing). Also have to constrain to fluid1 since we're not
// yet withdrawing from primary Uniswap position
uint256 amount1 = (inventory1 - FullMath.mulDiv(inventory0, cache.priceX96, Q96)) >> 1;
if (amount1 > d.fluid1) amount1 = d.fluid1;
// If contract balance is insufficient, withdraw from silo1. That still may not be enough, so reassign
// `amount1` to the actual available amount
unchecked {
uint256 balance1 = _balance1();
if (balance1 < amount1) amount1 = balance1 + _silo1Withdraw(amount1 - balance1);
}
// Place a new limit order
limit.deposit(limit.liquidityForAmount1(amount1));
} else if (ratio > 5100) {
// Attempt to sell token0 for token1. Choose limit order bounds above the market price. Disable
// incentive if removing & replacing in the same spot
limit.lower = TickMath.ceil(cache.tick, TICK_SPACING);
if (d.limitLiquidity != 0 && limit.upper == limit.lower + TICK_SPACING) urgency = 0;
limit.upper = limit.lower + TICK_SPACING;
// Choose amount0 such that ratio will be 50/50 once the limit order is pushed through (division by 2
// is a good approximation for small tickSpacing). Also have to constrain to fluid0 since we're not
// yet withdrawing from primary Uniswap position
uint256 amount0 = (inventory0 - FullMath.mulDiv(inventory1, Q96, cache.priceX96)) >> 1;
if (amount0 > d.fluid0) amount0 = d.fluid0;
// If contract balance is insufficient, withdraw from silo0. That still may not be enough, so reassign
// `amount0` to the actual available amount
unchecked {
uint256 balance0 = _balance0();
if (balance0 < amount0) amount0 = balance0 + _silo0Withdraw(amount0 - balance0);
}
// Place a new limit order
limit.deposit(limit.liquidityForAmount0(amount0));
} else {
// Zero-out the limit struct to indicate that it's inactive
delete limit;
// Recenter the primary position
primary = _recenter(cache, primary, d.primaryLiquidity, inventory0, inventory1, maintenanceIsSustainable);
recenterTimestamp = uint48(block.timestamp);
}
gas = uint32(21000 + gas - gasleft());
if (gas > maxRebalanceGas) maxRebalanceGas = gas;
maintenanceIsSustainable = _rewardCaller(rewardToken, urgency, gas, maxRebalanceGas, maintenanceIsSustainable);
emit Rebalance(ratio, totalSupply, inventory0, inventory1);
packedSlot = PackedSlot(
primary.lower,
primary.upper,
limit.lower,
limit.upper,
recenterTimestamp,
maxRebalanceGas,
maintenanceIsSustainable,
false
);
}
/**
* @notice Recenters the primary Uniswap position around the current tick. Deposits leftover funds into the silos.
* @dev This function assumes that the limit order has no liquidity (never existed or already exited)
* @param _cache The rebalance cache, populated with sqrtPriceX96, priceX96, and tick
* @param _primary The existing primary Uniswap position
* @param _primaryLiquidity The amount of liquidity currently in `_primary`
* @param _inventory0 The amount of token0 underlying all LP tokens. MUST BE <= THE TRUE VALUE. No overestimates!
* @param _inventory1 The amount of token1 underlying all LP tokens. MUST BE <= THE TRUE VALUE. No overestimates!
* @param _maintenanceIsSustainable Whether `maintenanceBudget0` or `maintenanceBudget1` has filled up according to
* `K` -- if false, position width is maximized rather than scaling with volatility
* @return Uniswap.Position memory `_primary` updated with new lower and upper tick bounds
*/
function _recenter(
RebalanceCache memory _cache,
Uniswap.Position memory _primary,
uint128 _primaryLiquidity,
uint256 _inventory0,
uint256 _inventory1,
bool _maintenanceIsSustainable
) private returns (Uniswap.Position memory) {
// Exit primary Uniswap position
unchecked {
(, , uint256 earned0, uint256 earned1) = _primary.withdraw(_primaryLiquidity);
maintenanceBudget0 += earned0 / MAINTENANCE_FEE;
maintenanceBudget1 += earned1 / MAINTENANCE_FEE;
}
// Decide primary position width...
int24 w = _maintenanceIsSustainable
? _computeNextPositionWidth(volatilityOracle.estimate24H(UNI_POOL))
: int24(MAX_WIDTH);
w = w >> 1;
// ...and compute amounts that should be placed inside
(uint256 amount0, uint256 amount1) = _computeMagicAmounts(_inventory0, _inventory1, w);
// If contract balance (leaving out the float) is insufficient, withdraw from silos
int256 balance0;
int256 balance1;
unchecked {
balance0 = int256(_balance0()) - int256(FullMath.mulDiv(_inventory0, FLOAT_PERCENTAGE, 10_000));
balance1 = int256(_balance1()) - int256(FullMath.mulDiv(_inventory1, FLOAT_PERCENTAGE, 10_000));
if (balance0 < int256(amount0)) {
_inventory0 = 0; // reuse var to avoid stack too deep. now a flag, 0 means we withdraw from silo0
amount0 = uint256(balance0 + int256(_silo0Withdraw(uint256(int256(amount0) - balance0))));
}
if (balance1 < int256(amount1)) {
_inventory1 = 0; // reuse var to avoid stack too deep. now a flag, 0 means we withdraw from silo1
amount1 = uint256(balance1 + int256(_silo1Withdraw(uint256(int256(amount1) - balance1))));
}
}
// Update primary position's ticks
unchecked {
_primary.lower = TickMath.floor(_cache.tick - w, TICK_SPACING);
_primary.upper = TickMath.ceil(_cache.tick + w, TICK_SPACING);
if (_primary.lower < MIN_TICK) _primary.lower = MIN_TICK;
if (_primary.upper > MAX_TICK) _primary.upper = MAX_TICK;
}
// Place some liquidity in Uniswap
(amount0, amount1) = _primary.deposit(_primary.liquidityForAmounts(_cache.sqrtPriceX96, amount0, amount1));
// Place excess into silos
if (_inventory0 != 0) {
silo0.delegate_deposit(uint256(balance0) - amount0);
silo0Basis += uint256(balance0) - amount0;
}
if (_inventory1 != 0) {
silo1.delegate_deposit(uint256(balance1) - amount1);
silo1Basis += uint256(balance1) - amount1;
}
emit Recenter(_primary.lower, _primary.upper);
return _primary;
}
/**
* @notice Sends some `_rewardToken` to `msg.sender` as a reward for calling rebalance
* @param _rewardToken The ERC20 token in which the reward should be denominated. If `rewardToken` is the 0
* address, no reward will be given.
* @param _urgency How critical it is that rebalance gets called right now. Nominal value is 100_000
* @param _gasUsed How much gas was used for core rebalance logic
* @param _maxRebalanceGas The (approximate) maximum amount of gas that's ever been used for `rebalance()`
* @param _maintenanceIsSustainable Whether the most recently-used maintenance budget was filled up after the
* last rebalance
* @return bool If `_rewardToken` is token0 or token1, return whether the maintenance budget will remain full
* after sending reward. If `_rewardToken` is something else, return previous _maintenanceIsSustainable value
*/
function _rewardCaller(
address _rewardToken,
uint32 _urgency,
uint32 _gasUsed,
uint32 _maxRebalanceGas,
bool _maintenanceIsSustainable
) private returns (bool) {
// Short-circuit if the caller doesn't want to be rewarded
if (_rewardToken == address(0)) {
emit Reward(address(0), 0, _urgency);
return _maintenanceIsSustainable;
}
// Otherwise, do math
uint256 rewardPerGas = gasPrices[_rewardToken]; // extra factor of 1e4
uint256 reward = FullMath.mulDiv(rewardPerGas * _gasUsed, _urgency, 1e9);
if (_rewardToken == address(TOKEN0)) {
uint256 budget = maintenanceBudget0;
if (reward > budget || rewardPerGas == 0) reward = budget;
budget -= reward;
uint256 maxBudget = FullMath.mulDiv(rewardPerGas * K, _maxRebalanceGas, 1e4);
maintenanceBudget0 = budget > maxBudget ? maxBudget : budget;
if (budget > maxBudget) _maintenanceIsSustainable = true;
else if (budget < maxBudget / L) _maintenanceIsSustainable = false;
} else if (_rewardToken == address(TOKEN1)) {
uint256 budget = maintenanceBudget1;
if (reward > budget || rewardPerGas == 0) reward = budget;
budget -= reward;
uint256 maxBudget = FullMath.mulDiv(rewardPerGas * K, _maxRebalanceGas, 1e4);
maintenanceBudget1 = budget > maxBudget ? maxBudget : budget;
if (budget > maxBudget) _maintenanceIsSustainable = true;
else if (budget < maxBudget / L) _maintenanceIsSustainable = false;
} else {
uint256 budget = IERC20(_rewardToken).balanceOf(address(this));
if (reward > budget || rewardPerGas == 0) reward = budget;
require(silo0.shouldAllowRemovalOf(_rewardToken) && silo1.shouldAllowRemovalOf(_rewardToken));
}
IERC20(_rewardToken).safeTransfer(msg.sender, reward);
_pushGasPrice(_rewardToken, FullMath.mulDiv(1e4, reward, _gasUsed));
emit Reward(_rewardToken, reward, _urgency);
return _maintenanceIsSustainable;
}
/**
* @notice Attempts to withdraw `_amount` from silo0. If `_amount` is more than what's available, withdraw the
* maximum amount.
* @dev This reads and writes from/to `maintenanceBudget0`, so use sparingly
* @param _amount The desired amount of token0 to withdraw from silo0
* @return uint256 The actual amount of token0 that was withdrawn
*/
function _silo0Withdraw(uint256 _amount) private returns (uint256) {
unchecked {
uint256 a = silo0Basis;
uint256 b = silo0.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
if (_amount > b - a) _amount = b - a;
silo0.delegate_withdraw(a + _amount);
maintenanceBudget0 += a;
silo0Basis = b - a - _amount;
return _amount;
}
}
/**
* @notice Attempts to withdraw `_amount` from silo1. If `_amount` is more than what's available, withdraw the
* maximum amount.
* @dev This reads and writes from/to `maintenanceBudget1`, so use sparingly
* @param _amount The desired amount of token1 to withdraw from silo1
* @return uint256 The actual amount of token1 that was withdrawn
*/
function _silo1Withdraw(uint256 _amount) private returns (uint256) {
unchecked {
uint256 a = silo1Basis;
uint256 b = silo1.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
if (_amount > b - a) _amount = b - a;
silo1.delegate_withdraw(a + _amount);
maintenanceBudget1 += a;
silo1Basis = b - a - _amount;
return _amount;
}
}
/**
* @dev Assumes that `_gasPrice` represents the fair value of 1e4 units of gas, denominated in `_token`.
* Updates the contract's gas price oracle accordingly, including incrementing the array index.
* @param _token The ERC20 token for which average gas price should be updated
* @param _gasPrice The amount of `_token` necessary to incentivize expenditure of 1e4 units of gas
*/
function _pushGasPrice(address _token, uint256 _gasPrice) private {
uint256[14] storage array = gasPriceArrays[_token];
uint8 idx = gasPriceIdxs[_token];
unchecked {
// New entry cannot be lower than 90% of the previous average
uint256 average = gasPrices[_token];
uint256 minimum = average - average / D;
if (_gasPrice < minimum) _gasPrice = minimum;
_gasPrice /= 14;
gasPrices[_token] = average + _gasPrice - array[idx];
array[idx] = _gasPrice;
gasPriceIdxs[_token] = (idx + 1) % 14;
}
}
// ⬇️⬇️⬇️⬇️ VIEW FUNCTIONS ⬇️⬇️⬇️⬇️ ------------------------------------------------------------------------------
/// @dev Unpacks `packedSlot` from storage, ensuring that `_packedSlot.locked == false`
function _loadPackedSlot()
private
view
returns (
Uniswap.Position memory,
Uniswap.Position memory,
uint48,
uint32,
bool
)
{
PackedSlot memory _packedSlot = packedSlot;
require(!_packedSlot.locked);
return (
Uniswap.Position(UNI_POOL, _packedSlot.primaryLower, _packedSlot.primaryUpper),
Uniswap.Position(UNI_POOL, _packedSlot.limitLower, _packedSlot.limitUpper),
_packedSlot.recenterTimestamp,
_packedSlot.maxRebalanceGas,
_packedSlot.maintenanceIsSustainable
);
}
/// @inheritdoc IAloeBlendDerivedState
function getRebalanceUrgency() external view returns (uint32 urgency) {
urgency = _getRebalanceUrgency(packedSlot.recenterTimestamp);
}
/**
* @notice Reports how badly the vault wants its `rebalance()` function to be called. Proportional to time
* elapsed since the primary position last moved.
* @dev Since `RECENTERING_INTERVAL` is 86400 seconds, urgency is guaranteed to be nonzero unless the primary
* position is moved more than once in a single block.
* @param _recenterTimestamp The `block.timestamp` from the last time the primary position moved
* @return urgency How badly the vault wants its `rebalance()` function to be called
*/
function _getRebalanceUrgency(uint48 _recenterTimestamp) private view returns (uint32 urgency) {
urgency = uint32(FullMath.mulDiv(100_000, block.timestamp - _recenterTimestamp, RECENTERING_INTERVAL));
}
/// @inheritdoc IAloeBlendDerivedState
function getInventory() external view returns (uint256 inventory0, uint256 inventory1) {
(Uniswap.Position memory primary, Uniswap.Position memory limit, , , ) = _loadPackedSlot();
(uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();
(inventory0, inventory1, ) = _getInventory(primary, limit, sqrtPriceX96, false);
}
struct InventoryDetails {
// The amount of token0 available to limit order, i.e. everything *not* in the primary position
uint256 fluid0;
// The amount of token1 available to limit order, i.e. everything *not* in the primary position
uint256 fluid1;
// The liquidity present in the primary position. Note that this may be higher than what the
// vault deposited since someone may designate this contract as a `mint()` recipient
uint128 primaryLiquidity;
// The liquidity present in the limit order. Note that this may be higher than what the
// vault deposited since someone may designate this contract as a `mint()` recipient
uint128 limitLiquidity;
}
/**
* @notice Estimate's the vault's liabilities to users -- in other words, how much would be paid out if all
* holders redeemed their LP tokens at once.
* @dev Underestimates the true payout unless both silos and Uniswap positions have just been poked. Also...
* if _overestimate is false
* Assumes that the maximum amount will accrue to the maintenance budget during the next `rebalance()`. If it
* takes less than that for the budget to reach capacity, then the values reported here may increase after
* calling `rebalance()`.
* if _overestimate is true
* Assumes that nothing will accrue to the maintenance budget during the next `rebalance()`. So the values
* reported here may decrease after calling `rebalance()`, i.e. this becomes an overestimate rather than an
* underestimate.
* @param _primary The primary position
* @param _limit The limit order; if inactive, `_limit.lower` should equal `_limit.upper`
* @param _sqrtPriceX96 The current sqrt(price) of the Uniswap pair from `slot0()`
* @param _overestimate Whether to error on the side of overestimating or underestimating
* @return inventory0 The amount of token0 underlying all LP tokens
* @return inventory1 The amount of token1 underlying all LP tokens
* @return d A struct containing details that may be relevant to other functions. We return it here to avoid
* reloading things from external storage (saves gas).
*/
function _getInventory(
Uniswap.Position memory _primary,
Uniswap.Position memory _limit,
uint160 _sqrtPriceX96,
bool _overestimate
)
private
view
returns (
uint256 inventory0,
uint256 inventory1,
InventoryDetails memory d
)
{
uint256 a;
uint256 b;
// Limit order
if (_limit.lower != _limit.upper) {
(d.limitLiquidity, , , a, b) = _limit.info();
(d.fluid0, d.fluid1) = _limit.amountsForLiquidity(_sqrtPriceX96, d.limitLiquidity);
// Earnings from limit order don't get added to maintenance budget
d.fluid0 += a;
d.fluid1 += b;
}
// token0 from contract + silo0
a = silo0Basis;
b = silo0.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
d.fluid0 += _balance0() + b - (_overestimate ? 0 : a);
// token1 from contract + silo1
a = silo1Basis;
b = silo1.balanceOf(address(this));
a = b > a ? (b - a) / MAINTENANCE_FEE : 0; // interest / MAINTENANCE_FEE
d.fluid1 += _balance1() + b - (_overestimate ? 0 : a);
// Primary position; limit order is placed without touching this, so its amounts aren't included in `fluid`
if (_primary.lower != _primary.upper) {
(d.primaryLiquidity, , , a, b) = _primary.info();
(inventory0, inventory1) = _primary.amountsForLiquidity(_sqrtPriceX96, d.primaryLiquidity);
inventory0 += d.fluid0 + a - (_overestimate ? 0 : a / MAINTENANCE_FEE);
inventory1 += d.fluid1 + b - (_overestimate ? 0 : b / MAINTENANCE_FEE);
} else {
inventory0 = d.fluid0;
inventory1 = d.fluid1;
}
}
/// @dev The amount of token0 in the contract that's not in maintenanceBudget0
function _balance0() private view returns (uint256) {
return TOKEN0.balanceOf(address(this)) - maintenanceBudget0;
}
/// @dev The amount of token1 in the contract that's not in maintenanceBudget1
function _balance1() private view returns (uint256) {
return TOKEN1.balanceOf(address(this)) - maintenanceBudget1;
}
// ⬆️⬆️⬆️⬆️ VIEW FUNCTIONS ⬆️⬆️⬆️⬆️ ------------------------------------------------------------------------------
// ⬇️⬇️⬇️⬇️ PURE FUNCTIONS ⬇️⬇️⬇️⬇️ ------------------------------------------------------------------------------
/// @dev Computes position width based on volatility. Doesn't revert
function _computeNextPositionWidth(uint256 _sigma) internal pure returns (int24) {
if (_sigma <= 9.9491783619e15) return MIN_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MIN_WIDTH / 2)})
if (_sigma >= 3.7500454036e17) return MAX_WIDTH; // \frac{1e18}{B} (1 - \frac{1}{1.0001^(MAX_WIDTH / 2)})
_sigma *= B; // scale by a constant factor to increase confidence
unchecked {
uint160 ratio = uint160((Q96 * 1e18) / (1e18 - _sigma));
return TickMath.getTickAtSqrtRatio(ratio);
}
}
/// @dev Computes amounts that should be placed in primary Uniswap position to maintain 50/50 inventory ratio.
/// Doesn't revert as long as MIN_WIDTH <= _halfWidth * 2 <= MAX_WIDTH
function _computeMagicAmounts(
uint256 _inventory0,
uint256 _inventory1,
int24 _halfWidth
) internal pure returns (uint256 amount0, uint256 amount1) {
// the fraction of total inventory (X96) that should be put into primary Uniswap order to mimic Uniswap v2
uint96 magic = uint96(Q96 - TickMath.getSqrtRatioAtTick(-_halfWidth));
amount0 = FullMath.mulDiv(_inventory0, magic, Q96);
amount1 = FullMath.mulDiv(_inventory1, magic, Q96);
}
/// @dev Computes the largest possible `amount0` and `amount1` such that they match the current inventory ratio,
/// but are not greater than `_amount0Max` and `_amount1Max` respectively. May revert if the following are true:
/// _totalSupply * _amount0Max / _inventory0 > type(uint256).max
/// _totalSupply * _amount1Max / _inventory1 > type(uint256).max
/// This is okay because it only blocks deposit (not withdraw). Can also workaround by depositing smaller amounts
function _computeLPShares(
uint256 _totalSupply,
uint256 _inventory0,
uint256 _inventory1,
uint256 _amount0Max,
uint256 _amount1Max,
uint160 _sqrtPriceX96
)
internal
pure
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
// If total supply > 0, pool can't be empty
assert(_totalSupply == 0 || _inventory0 != 0 || _inventory1 != 0);
if (_totalSupply == 0) {
// For first deposit, enforce 50/50 ratio manually
uint224 priceX96 = uint224(FullMath.mulDiv(_sqrtPriceX96, _sqrtPriceX96, Q96));
amount0 = FullMath.mulDiv(_amount1Max, Q96, priceX96);
if (amount0 < _amount0Max) {
amount1 = _amount1Max;
shares = amount1;
} else {
amount0 = _amount0Max;
amount1 = FullMath.mulDiv(amount0, priceX96, Q96);
shares = amount0;
}
} else if (_inventory0 == 0) {
amount1 = _amount1Max;
shares = FullMath.mulDiv(amount1, _totalSupply, _inventory1);
} else if (_inventory1 == 0) {
amount0 = _amount0Max;
shares = FullMath.mulDiv(amount0, _totalSupply, _inventory0);
} else {
// The branches of this ternary are logically identical, but must be separate to avoid overflow
bool cond = _inventory0 < _inventory1
? FullMath.mulDiv(_amount1Max, _inventory0, _inventory1) < _amount0Max
: _amount1Max < FullMath.mulDiv(_amount0Max, _inventory1, _inventory0);
if (cond) {
amount1 = _amount1Max;
amount0 = FullMath.mulDiv(amount1, _inventory0, _inventory1);
shares = FullMath.mulDiv(amount1, _totalSupply, _inventory1);
} else {
amount0 = _amount0Max;
amount1 = FullMath.mulDiv(amount0, _inventory1, _inventory0);
shares = FullMath.mulDiv(amount0, _totalSupply, _inventory0);
}
}
}
}
| @title Liquidity amount functions @notice Provides functions for computing liquidity amounts from token amounts and prices | library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
liquidity = toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
liquidity = toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
} else if (sqrtRatioX96 < sqrtRatioBX96) {
} else {
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint224 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
amount0 = uint64(
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96
);
}
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint192 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
amount1 = uint192(FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96));
}
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
} else if (sqrtRatioX96 < sqrtRatioBX96) {
} else {
}
| 5,926,977 | [
1,
48,
18988,
24237,
3844,
4186,
225,
28805,
4186,
364,
20303,
4501,
372,
24237,
30980,
628,
1147,
30980,
471,
19827,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
12083,
511,
18988,
24237,
6275,
87,
288,
203,
203,
203,
565,
445,
358,
5487,
10392,
12,
11890,
5034,
619,
13,
3238,
16618,
1135,
261,
11890,
10392,
677,
13,
288,
203,
3639,
2583,
12443,
93,
273,
2254,
10392,
12,
92,
3719,
422,
619,
1769,
203,
565,
289,
203,
203,
565,
445,
9014,
18988,
24237,
1290,
6275,
20,
12,
203,
3639,
2254,
16874,
5700,
8541,
2501,
10525,
16,
203,
3639,
2254,
16874,
5700,
8541,
38,
60,
10525,
16,
203,
3639,
2254,
5034,
3844,
20,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
10392,
4501,
372,
24237,
13,
288,
203,
3639,
309,
261,
24492,
8541,
2501,
10525,
405,
5700,
8541,
38,
60,
10525,
13,
261,
24492,
8541,
2501,
10525,
16,
5700,
8541,
38,
60,
10525,
13,
273,
261,
24492,
8541,
38,
60,
10525,
16,
5700,
8541,
2501,
10525,
1769,
203,
3639,
2254,
5034,
12110,
273,
11692,
10477,
18,
16411,
7244,
12,
24492,
8541,
2501,
10525,
16,
5700,
8541,
38,
60,
10525,
16,
15038,
2148,
10525,
18,
53,
10525,
1769,
203,
3639,
4501,
372,
24237,
273,
358,
5487,
10392,
12,
5080,
10477,
18,
16411,
7244,
12,
8949,
20,
16,
12110,
16,
5700,
8541,
38,
60,
10525,
300,
5700,
8541,
2501,
10525,
10019,
203,
565,
289,
203,
203,
565,
445,
9014,
18988,
24237,
1290,
6275,
21,
12,
203,
3639,
2254,
16874,
5700,
8541,
2501,
10525,
16,
203,
3639,
2254,
16874,
5700,
8541,
38,
60,
10525,
16,
203,
3639,
2254,
5034,
3844,
21,
203,
565,
262,
2713,
16618,
1135,
261,
11890,
10392,
4501,
372,
24237,
13,
288,
203,
3639,
309,
2
] |
pragma solidity 0.4.21;
// File: contracts/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: contracts/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 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;
}
}
// File: contracts/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// 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];
}
}
// File: contracts/BurnableToken.sol
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
}
}
// File: contracts/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/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
// File: contracts/HVT.sol
contract HVT is MintableToken, BurnableToken {
using SafeMath for uint256;
string public name = "HiVe Token";
string public symbol = "HVT";
uint8 public decimals = 18;
bool public enableTransfers = false;
// functions overrides in order to maintain the token locked during the ICO
function transfer(address _to, uint256 _value) public returns(bool) {
require(enableTransfers);
return super.transfer(_to,_value);
}
function transferFrom(address _from, address _to, uint256 _value) public returns(bool) {
require(enableTransfers);
return super.transferFrom(_from,_to,_value);
}
function approve(address _spender, uint256 _value) public returns (bool) {
require(enableTransfers);
return super.approve(_spender,_value);
}
function burn(uint256 _value) public {
require(enableTransfers);
super.burn(_value);
}
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
require(enableTransfers);
super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
require(enableTransfers);
super.decreaseApproval(_spender, _subtractedValue);
}
// enable token transfers
function enableTokenTransfers() public onlyOwner {
enableTransfers = true;
}
// batch transfer with different amounts for each address
function batchTransferDiff(address[] _to, uint256[] _amount) public {
require(enableTransfers);
require(_to.length == _amount.length);
uint256 totalAmount = arraySum(_amount);
require(totalAmount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
for(uint i;i < _to.length;i++){
balances[_to[i]] = balances[_to[i]].add(_amount[i]);
Transfer(msg.sender,_to[i],_amount[i]);
}
}
// batch transfer with same amount for each address
function batchTransferSame(address[] _to, uint256 _amount) public {
require(enableTransfers);
uint256 totalAmount = _amount.mul(_to.length);
require(totalAmount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(totalAmount);
for(uint i;i < _to.length;i++){
balances[_to[i]] = balances[_to[i]].add(_amount);
Transfer(msg.sender,_to[i],_amount);
}
}
// get sum of array values
function arraySum(uint256[] _amount) internal pure returns(uint256){
uint256 totalAmount;
for(uint i;i < _amount.length;i++){
totalAmount = totalAmount.add(_amount[i]);
}
return totalAmount;
}
}
// File: contracts/ICOEngineInterface.sol
contract ICOEngineInterface {
// false if the ico is not started, true if the ico is started and running, true if the ico is completed
function started() public view returns(bool);
// false if the ico is not started, false if the ico is started and running, true if the ico is completed
function ended() public view returns(bool);
// time stamp of the starting time of the ico, must return 0 if it depends on the block number
function startTime() public view returns(uint);
// time stamp of the ending time of the ico, must retrun 0 if it depends on the block number
function endTime() public view returns(uint);
// Optional function, can be implemented in place of startTime
// Returns the starting block number of the ico, must return 0 if it depends on the time stamp
// function startBlock() public view returns(uint);
// Optional function, can be implemented in place of endTime
// Returns theending block number of the ico, must retrun 0 if it depends on the time stamp
// function endBlock() public view returns(uint);
// returns the total number of the tokens available for the sale, must not change when the ico is started
function totalTokens() public view returns(uint);
// returns the number of the tokens available for the ico. At the moment that the ico starts it must be equal to totalTokens(),
// then it will decrease. It is used to calculate the percentage of sold tokens as remainingTokens() / totalTokens()
function remainingTokens() public view returns(uint);
// return the price as number of tokens released for each ether
function price() public view returns(uint);
}
// File: contracts/KYCBase.sol
//import "./SafeMath.sol";
// Abstract base contract
contract KYCBase {
using SafeMath for uint256;
mapping (address => bool) public isKycSigner;
mapping (uint64 => uint256) public alreadyPayed;
event KycVerified(address indexed signer, address buyerAddress, uint64 buyerId, uint maxAmount);
function KYCBase(address [] kycSigners) internal {
for (uint i = 0; i < kycSigners.length; i++) {
isKycSigner[kycSigners[i]] = true;
}
}
// Must be implemented in descending contract to assign tokens to the buyers. Called after the KYC verification is passed
function releaseTokensTo(address buyer) internal returns(bool);
// This method can be overridden to enable some sender to buy token for a different address
function senderAllowedFor(address buyer)
internal view returns(bool)
{
return buyer == msg.sender;
}
function buyTokensFor(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s)
public payable returns (bool)
{
require(senderAllowedFor(buyerAddress));
return buyImplementation(buyerAddress, buyerId, maxAmount, v, r, s);
}
function buyTokens(uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s)
public payable returns (bool)
{
return buyImplementation(msg.sender, buyerId, maxAmount, v, r, s);
}
function buyImplementation(address buyerAddress, uint64 buyerId, uint maxAmount, uint8 v, bytes32 r, bytes32 s)
private returns (bool)
{
// check the signature
bytes32 hash = sha256("Eidoo icoengine authorization", this, buyerAddress, buyerId, maxAmount);
address signer = ecrecover(hash, v, r, s);
if (!isKycSigner[signer]) {
revert();
} else {
uint256 totalPayed = alreadyPayed[buyerId].add(msg.value);
require(totalPayed <= maxAmount);
alreadyPayed[buyerId] = totalPayed;
KycVerified(signer, buyerAddress, buyerId, maxAmount);
return releaseTokensTo(buyerAddress);
}
}
// No payable fallback function, the tokens must be buyed using the functions buyTokens and buyTokensFor
function () public {
revert();
}
}
// File: contracts/RefundVault.sol
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable {
using SafeMath for uint256;
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
address public wallet;
State public state;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
function RefundVault(address _wallet) public {
require(_wallet != address(0));
wallet = _wallet;
state = State.Active;
}
function deposit(address investor) onlyOwner public payable {
require(state == State.Active);
deposited[investor] = deposited[investor].add(msg.value);
}
function close() onlyOwner public {
require(state == State.Active);
state = State.Closed;
Closed();
wallet.transfer(this.balance);
}
function enableRefunds() onlyOwner public {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
function refund(address investor) public {
require(state == State.Refunding);
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
}
}
// File: contracts/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
// File: contracts/TokenTimelock.sol
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint256 public releaseTime;
function TokenTimelock(ERC20Basic _token, address _beneficiary, uint256 _releaseTime) public {
require(_releaseTime > now);
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
require(now >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
// File: contracts/HivePowerCrowdsale.sol
// The Hive Power crowdsale contract
contract HivePowerCrowdsale is Ownable, ICOEngineInterface, KYCBase {
using SafeMath for uint;
enum State {Running,Success,Failure}
State public state;
HVT public token;
address public wallet;
// from ICOEngineInterface
uint [] public prices;
// from ICOEngineInterface
uint public startTime;
// from ICOEngineInterface
uint public endTime;
// from ICOEngineInterface
uint [] public caps;
// from ICOEngineInterface
uint public remainingTokens;
// from ICOEngineInterface
uint public totalTokens;
// amount of wei raised
uint public weiRaised;
// soft goal in wei
uint public goal;
// boolean to make sure preallocate is called only once
bool public isPreallocated;
// preallocated company token
uint public companyTokens;
// preallocated token for founders
uint public foundersTokens;
// vault for refunding
RefundVault public vault;
// addresses of time-locked founder vaults
address [4] public timeLockAddresses;
// step in seconds for token release
uint public stepLockedToken;
// allowed overshoot when crossing the bonus barrier (in wei)
uint public overshoot;
/**
* 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);
/**
* event for when weis are sent back to buyer
* @param purchaser who paid for the tokens and is getting back some ether
* @param amount of weis sent back
*/
event SentBack(address indexed purchaser, uint256 amount);
/* event for ICO successfully finalized */
event FinalizedOK();
/* event for ICO not successfully finalized */
event FinalizedNOK();
/**
* event for additional token minting
* @param timelock address of the time-lock contract
* @param amount amount of tokens minted
* @param releaseTime release time of tokens
* @param wallet address of the wallet that can get the token released
*/
event TimeLocked(address indexed timelock, uint256 amount, uint256 releaseTime, address indexed wallet);
/**
* event for additional token minting
* @param to who got the tokens
* @param amount amount of tokens purchased
*/
event Preallocated(address indexed to, uint256 amount);
/**
* Constructor
*/
function HivePowerCrowdsale(address [] kycSigner, address _token, address _wallet, uint _startTime, uint _endTime, uint [] _prices, uint [] _caps, uint _goal, uint _companyTokens, uint _foundersTokens, uint _stepLockedToken, uint _overshoot)
public
KYCBase(kycSigner)
{
require(_token != address(0));
require(_wallet != address(0));
require(_startTime > now);
require(_endTime > _startTime);
require(_prices.length == _caps.length);
for (uint256 i=0; i < _caps.length -1; i++)
{
require(_caps[i+1].sub(_caps[i]) > _overshoot.mul(_prices[i]));
}
token = HVT(_token);
wallet = _wallet;
startTime = _startTime;
endTime = _endTime;
prices = _prices;
caps = _caps;
totalTokens = _caps[_caps.length-1];
remainingTokens = _caps[_caps.length-1];
vault = new RefundVault(_wallet);
goal = _goal;
companyTokens = _companyTokens;
foundersTokens = _foundersTokens;
stepLockedToken = _stepLockedToken;
overshoot = _overshoot;
state = State.Running;
isPreallocated = false;
}
function preallocate() onlyOwner public {
// can be called only once
require(!isPreallocated);
// mint tokens for team founders in timelocked vaults
uint numTimelocks = 4;
uint amount = foundersTokens / numTimelocks; //amount of token per vault
uint256 releaseTime = endTime;
for(uint256 i=0; i < numTimelocks; i++)
{
// update releaseTime according to the step
releaseTime = releaseTime.add(stepLockedToken);
// create tokentimelock
TokenTimelock timeLock = new TokenTimelock(token, wallet, releaseTime);
// keep address in memory
timeLockAddresses[i] = address(timeLock);
// mint tokens in tokentimelock
token.mint(address(timeLock), amount);
// generate event
TimeLocked(address(timeLock), amount, releaseTime, wallet);
}
//teamTimeLocks.mintTokens(teamTokens);
// Mint additional tokens (referral, airdrops, etc.)
token.mint(wallet, companyTokens);
Preallocated(wallet, companyTokens);
// cannot be called anymore
isPreallocated = true;
}
// function that is called from KYCBase
function releaseTokensTo(address buyer) internal returns(bool) {
// needs to be started
require(started());
// and not ended
require(!ended());
uint256 weiAmount = msg.value;
uint256 weiBack = 0;
uint currentPrice = price();
uint currentCap = getCap();
uint tokens = weiAmount.mul(currentPrice);
uint tokenRaised = totalTokens - remainingTokens;
//check if tokens exceed the amount of tokens that can be minted
if (tokenRaised.add(tokens) > currentCap)
{
tokens = currentCap.sub(tokenRaised);
weiAmount = tokens.div(currentPrice);
weiBack = msg.value - weiAmount;
}
//require(tokenRaised.add(tokens) <= currentCap);
weiRaised = weiRaised + weiAmount;
remainingTokens = remainingTokens.sub(tokens);
// mint tokens and transfer funds
token.mint(buyer, tokens);
forwardFunds(weiAmount);
if (weiBack>0)
{
msg.sender.transfer(weiBack);
SentBack(msg.sender, weiBack);
}
TokenPurchase(msg.sender, buyer, weiAmount, tokens);
return true;
}
function forwardFunds(uint256 weiAmount) internal {
vault.deposit.value(weiAmount)(msg.sender);
}
/**
* @dev finalize an ICO in dependency on the goal reaching:
* 1) reached goal (successful ICO):
* -> release sold token for the transfers
* -> close the vault
* -> close the ICO successfully
* 2) not reached goal (not successful ICO):
* -> call finalizeNOK()
*/
function finalize() onlyOwner public {
require(state == State.Running);
require(ended());
// Check the soft goal reaching
if(weiRaised >= goal) {
// if goal reached
// stop the minting
token.finishMinting();
// enable token transfers
token.enableTokenTransfers();
// close the vault and transfer funds to wallet
vault.close();
// ICO successfully finalized
// set state to Success
state = State.Success;
FinalizedOK();
}
else {
// if goal NOT reached
// ICO not successfully finalized
finalizeNOK();
}
}
/**
* @dev finalize an unsuccessful ICO:
* -> enable the refund
* -> close the ICO not successfully
*/
function finalizeNOK() onlyOwner public {
// run checks again because this is a public function
require(state == State.Running);
require(ended());
// enable the refunds
vault.enableRefunds();
// ICO not successfully finalised
// set state to Failure
state = State.Failure;
FinalizedNOK();
}
// if crowdsale is unsuccessful, investors can claim refunds here
function claimRefund() public {
require(state == State.Failure);
vault.refund(msg.sender);
}
// get the next cap as a function of the amount of sold token
function getCap() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
// allow for a an overshoot (only when bonus is applied)
uint tokenPerOvershoot = overshoot * prices[i];
return(caps[i].add(tokenPerOvershoot));
}
}
// but not on the total amount of tokens
return(totalTokens);
}
// from ICOEngineInterface
function started() public view returns(bool) {
return now >= startTime;
}
// from ICOEngineInterface
function ended() public view returns(bool) {
return now >= endTime || remainingTokens == 0;
}
function startTime() public view returns(uint) {
return(startTime);
}
function endTime() public view returns(uint){
return(endTime);
}
function totalTokens() public view returns(uint){
return(totalTokens);
}
function remainingTokens() public view returns(uint){
return(remainingTokens);
}
// return the price as number of tokens released for each ether
function price() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
return(prices[i]);
}
}
return(prices[prices.length-1]);
}
// No payable fallback function, the tokens must be buyed using the functions buyTokens and buyTokensFor
function () public {
revert();
}
}
// File: contracts/ERC20Interface.sol
contract ERC20Interface {
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);
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);
} | The Hive Power crowdsale contract from ICOEngineInterface from ICOEngineInterface from ICOEngineInterface from ICOEngineInterface from ICOEngineInterface from ICOEngineInterface amount of wei raised soft goal in wei boolean to make sure preallocate is called only once preallocated company token preallocated token for founders vault for refunding addresses of time-locked founder vaults step in seconds for token release allowed overshoot when crossing the bonus barrier (in wei) | contract HivePowerCrowdsale is Ownable, ICOEngineInterface, KYCBase {
using SafeMath for uint;
State public state;
HVT public token;
address public wallet;
uint [] public prices;
uint public startTime;
uint public endTime;
uint [] public caps;
uint public remainingTokens;
uint public totalTokens;
uint public weiRaised;
uint public goal;
bool public isPreallocated;
uint public companyTokens;
uint public foundersTokens;
RefundVault public vault;
address [4] public timeLockAddresses;
uint public stepLockedToken;
uint public overshoot;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event SentBack(address indexed purchaser, uint256 amount);
event FinalizedOK();
event FinalizedNOK();
event TimeLocked(address indexed timelock, uint256 amount, uint256 releaseTime, address indexed wallet);
event Preallocated(address indexed to, uint256 amount);
function HivePowerCrowdsale(address [] kycSigner, address _token, address _wallet, uint _startTime, uint _endTime, uint [] _prices, uint [] _caps, uint _goal, uint _companyTokens, uint _foundersTokens, uint _stepLockedToken, uint _overshoot)
public
KYCBase(kycSigner)
enum State {Running,Success,Failure}
{
require(_token != address(0));
require(_wallet != address(0));
require(_startTime > now);
require(_endTime > _startTime);
require(_prices.length == _caps.length);
for (uint256 i=0; i < _caps.length -1; i++)
{
require(_caps[i+1].sub(_caps[i]) > _overshoot.mul(_prices[i]));
}
token = HVT(_token);
wallet = _wallet;
startTime = _startTime;
endTime = _endTime;
prices = _prices;
caps = _caps;
totalTokens = _caps[_caps.length-1];
remainingTokens = _caps[_caps.length-1];
vault = new RefundVault(_wallet);
goal = _goal;
companyTokens = _companyTokens;
foundersTokens = _foundersTokens;
stepLockedToken = _stepLockedToken;
overshoot = _overshoot;
state = State.Running;
isPreallocated = false;
}
{
require(_token != address(0));
require(_wallet != address(0));
require(_startTime > now);
require(_endTime > _startTime);
require(_prices.length == _caps.length);
for (uint256 i=0; i < _caps.length -1; i++)
{
require(_caps[i+1].sub(_caps[i]) > _overshoot.mul(_prices[i]));
}
token = HVT(_token);
wallet = _wallet;
startTime = _startTime;
endTime = _endTime;
prices = _prices;
caps = _caps;
totalTokens = _caps[_caps.length-1];
remainingTokens = _caps[_caps.length-1];
vault = new RefundVault(_wallet);
goal = _goal;
companyTokens = _companyTokens;
foundersTokens = _foundersTokens;
stepLockedToken = _stepLockedToken;
overshoot = _overshoot;
state = State.Running;
isPreallocated = false;
}
function preallocate() onlyOwner public {
require(!isPreallocated);
uint numTimelocks = 4;
uint256 releaseTime = endTime;
for(uint256 i=0; i < numTimelocks; i++)
{
releaseTime = releaseTime.add(stepLockedToken);
TokenTimelock timeLock = new TokenTimelock(token, wallet, releaseTime);
timeLockAddresses[i] = address(timeLock);
token.mint(address(timeLock), amount);
TimeLocked(address(timeLock), amount, releaseTime, wallet);
}
Preallocated(wallet, companyTokens);
}
function preallocate() onlyOwner public {
require(!isPreallocated);
uint numTimelocks = 4;
uint256 releaseTime = endTime;
for(uint256 i=0; i < numTimelocks; i++)
{
releaseTime = releaseTime.add(stepLockedToken);
TokenTimelock timeLock = new TokenTimelock(token, wallet, releaseTime);
timeLockAddresses[i] = address(timeLock);
token.mint(address(timeLock), amount);
TimeLocked(address(timeLock), amount, releaseTime, wallet);
}
Preallocated(wallet, companyTokens);
}
token.mint(wallet, companyTokens);
isPreallocated = true;
function releaseTokensTo(address buyer) internal returns(bool) {
require(started());
require(!ended());
uint256 weiAmount = msg.value;
uint256 weiBack = 0;
uint currentPrice = price();
uint currentCap = getCap();
uint tokens = weiAmount.mul(currentPrice);
uint tokenRaised = totalTokens - remainingTokens;
if (tokenRaised.add(tokens) > currentCap)
{
tokens = currentCap.sub(tokenRaised);
weiAmount = tokens.div(currentPrice);
weiBack = msg.value - weiAmount;
}
weiRaised = weiRaised + weiAmount;
remainingTokens = remainingTokens.sub(tokens);
forwardFunds(weiAmount);
if (weiBack>0)
{
msg.sender.transfer(weiBack);
SentBack(msg.sender, weiBack);
}
TokenPurchase(msg.sender, buyer, weiAmount, tokens);
return true;
}
function releaseTokensTo(address buyer) internal returns(bool) {
require(started());
require(!ended());
uint256 weiAmount = msg.value;
uint256 weiBack = 0;
uint currentPrice = price();
uint currentCap = getCap();
uint tokens = weiAmount.mul(currentPrice);
uint tokenRaised = totalTokens - remainingTokens;
if (tokenRaised.add(tokens) > currentCap)
{
tokens = currentCap.sub(tokenRaised);
weiAmount = tokens.div(currentPrice);
weiBack = msg.value - weiAmount;
}
weiRaised = weiRaised + weiAmount;
remainingTokens = remainingTokens.sub(tokens);
forwardFunds(weiAmount);
if (weiBack>0)
{
msg.sender.transfer(weiBack);
SentBack(msg.sender, weiBack);
}
TokenPurchase(msg.sender, buyer, weiAmount, tokens);
return true;
}
token.mint(buyer, tokens);
function releaseTokensTo(address buyer) internal returns(bool) {
require(started());
require(!ended());
uint256 weiAmount = msg.value;
uint256 weiBack = 0;
uint currentPrice = price();
uint currentCap = getCap();
uint tokens = weiAmount.mul(currentPrice);
uint tokenRaised = totalTokens - remainingTokens;
if (tokenRaised.add(tokens) > currentCap)
{
tokens = currentCap.sub(tokenRaised);
weiAmount = tokens.div(currentPrice);
weiBack = msg.value - weiAmount;
}
weiRaised = weiRaised + weiAmount;
remainingTokens = remainingTokens.sub(tokens);
forwardFunds(weiAmount);
if (weiBack>0)
{
msg.sender.transfer(weiBack);
SentBack(msg.sender, weiBack);
}
TokenPurchase(msg.sender, buyer, weiAmount, tokens);
return true;
}
function forwardFunds(uint256 weiAmount) internal {
vault.deposit.value(weiAmount)(msg.sender);
}
function finalize() onlyOwner public {
require(state == State.Running);
require(ended());
if(weiRaised >= goal) {
token.finishMinting();
token.enableTokenTransfers();
vault.close();
state = State.Success;
FinalizedOK();
}
else {
finalizeNOK();
}
}
function finalize() onlyOwner public {
require(state == State.Running);
require(ended());
if(weiRaised >= goal) {
token.finishMinting();
token.enableTokenTransfers();
vault.close();
state = State.Success;
FinalizedOK();
}
else {
finalizeNOK();
}
}
function finalize() onlyOwner public {
require(state == State.Running);
require(ended());
if(weiRaised >= goal) {
token.finishMinting();
token.enableTokenTransfers();
vault.close();
state = State.Success;
FinalizedOK();
}
else {
finalizeNOK();
}
}
function finalizeNOK() onlyOwner public {
require(state == State.Running);
require(ended());
vault.enableRefunds();
state = State.Failure;
FinalizedNOK();
}
function claimRefund() public {
require(state == State.Failure);
vault.refund(msg.sender);
}
function getCap() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
uint tokenPerOvershoot = overshoot * prices[i];
return(caps[i].add(tokenPerOvershoot));
}
}
}
function getCap() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
uint tokenPerOvershoot = overshoot * prices[i];
return(caps[i].add(tokenPerOvershoot));
}
}
}
function getCap() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
uint tokenPerOvershoot = overshoot * prices[i];
return(caps[i].add(tokenPerOvershoot));
}
}
}
return(totalTokens);
function started() public view returns(bool) {
return now >= startTime;
}
function ended() public view returns(bool) {
return now >= endTime || remainingTokens == 0;
}
function startTime() public view returns(uint) {
return(startTime);
}
function endTime() public view returns(uint){
return(endTime);
}
function totalTokens() public view returns(uint){
return(totalTokens);
}
function remainingTokens() public view returns(uint){
return(remainingTokens);
}
function price() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
return(prices[i]);
}
}
return(prices[prices.length-1]);
}
function price() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
return(prices[i]);
}
}
return(prices[prices.length-1]);
}
function price() public view returns(uint){
uint tokenRaised=totalTokens-remainingTokens;
for (uint i=0;i<caps.length-1;i++){
if (tokenRaised < caps[i])
{
return(prices[i]);
}
}
return(prices[prices.length-1]);
}
function () public {
revert();
}
}
| 13,401,966 | [
1,
1986,
21880,
23783,
276,
492,
2377,
5349,
6835,
628,
467,
3865,
4410,
1358,
628,
467,
3865,
4410,
1358,
628,
467,
3865,
4410,
1358,
628,
467,
3865,
4410,
1358,
628,
467,
3865,
4410,
1358,
628,
467,
3865,
4410,
1358,
3844,
434,
732,
77,
11531,
8971,
17683,
316,
732,
77,
1250,
358,
1221,
3071,
675,
16247,
353,
2566,
1338,
3647,
675,
28172,
9395,
1147,
675,
28172,
1147,
364,
1392,
414,
9229,
364,
1278,
14351,
6138,
434,
813,
17,
15091,
284,
465,
765,
9229,
87,
2235,
316,
3974,
364,
1147,
3992,
2935,
28327,
76,
1632,
1347,
6828,
310,
326,
324,
22889,
24651,
261,
267,
732,
77,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
21880,
13788,
39,
492,
2377,
5349,
353,
14223,
6914,
16,
467,
3865,
4410,
1358,
16,
1475,
61,
39,
2171,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
203,
565,
3287,
1071,
919,
31,
203,
203,
565,
670,
58,
56,
1071,
1147,
31,
203,
203,
565,
1758,
1071,
9230,
31,
203,
203,
565,
2254,
5378,
1071,
19827,
31,
203,
203,
565,
2254,
1071,
8657,
31,
203,
203,
565,
2254,
1071,
13859,
31,
203,
203,
565,
2254,
5378,
1071,
15788,
31,
203,
203,
565,
2254,
1071,
4463,
5157,
31,
203,
203,
565,
2254,
1071,
2078,
5157,
31,
203,
203,
565,
2254,
1071,
732,
77,
12649,
5918,
31,
203,
203,
565,
2254,
1071,
17683,
31,
203,
203,
565,
1426,
1071,
353,
1386,
28172,
31,
203,
203,
565,
2254,
1071,
9395,
5157,
31,
203,
203,
565,
2254,
1071,
1392,
414,
5157,
31,
203,
203,
565,
3941,
1074,
12003,
1071,
9229,
31,
203,
203,
565,
1758,
306,
24,
65,
1071,
813,
2531,
7148,
31,
203,
203,
565,
2254,
1071,
2235,
8966,
1345,
31,
203,
203,
565,
2254,
1071,
28327,
76,
1632,
31,
203,
203,
565,
871,
3155,
23164,
12,
2867,
8808,
5405,
343,
14558,
16,
1758,
8808,
27641,
74,
14463,
814,
16,
2254,
5034,
460,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
16695,
2711,
12,
2867,
8808,
5405,
343,
14558,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
871,
16269,
1235,
3141,
5621,
203,
203,
565,
871,
16269,
1235,
50,
3141,
5621,
203,
203,
565,
871,
2647,
8966,
12,
2867,
8808,
1658,
292,
975,
2
] |
// File: contracts/AnonymiceLibrary.sol
pragma solidity ^0.8.0;
library AnonymiceLibrary {
string internal constant TABLE =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return "";
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {
} lt(dataPtr, endPtr) {
} {
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(shr(6, input), 0x3F))))
)
resultPtr := add(resultPtr, 1)
mstore(
resultPtr,
shl(248, mload(add(tablePtr, and(input, 0x3F))))
)
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
}
return result;
}
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
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);
}
function parseInt(string memory _a)
internal
pure
returns (uint8 _parsedInt)
{
bytes memory bresult = bytes(_a);
uint8 mint = 0;
for (uint8 i = 0; i < bresult.length; i++) {
if (
(uint8(uint8(bresult[i])) >= 48) &&
(uint8(uint8(bresult[i])) <= 57)
) {
mint *= 10;
mint += uint8(bresult[i]) - 48;
}
}
return mint;
}
function substring(
string memory str,
uint256 startIndex,
uint256 endIndex
) internal pure returns (string memory) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex - startIndex);
for (uint256 i = startIndex; i < endIndex; i++) {
result[i - startIndex] = strBytes[i];
}
return string(result);
}
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;
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: contracts/interfaces/IAxons.sol
/// @title Interface for Axons
pragma solidity ^0.8.6;
interface IAxons is IERC721Enumerable {
event AxonCreated(uint256 indexed tokenId);
event AxonBurned(uint256 indexed tokenId);
event MinterUpdated(address minter);
event MinterLocked();
function mint(uint256 axonId) external returns (uint256);
function burn(uint256 tokenId) external;
function dataURI(uint256 tokenId) external returns (string memory);
function setMinter(address minter) external;
function lockMinter() external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/Axons.sol
// contracts/Axons.sol
pragma solidity ^0.8.0;
contract Axons is IAxons, ERC721Enumerable, Ownable {
/*
_ _ _ _ _
/ \ / \ / \ / \ / \
( A | X | O | N | S |
\_/ \_/ \_/ \_/ \_/
credit to mouse dev and 0xinuarashi for making amazing on chain project with Anonymice
that was used as the basis for Filaments and this contract
*/
using AnonymiceLibrary for uint8;
// An address who has permissions to mint Axons
address public minter;
// Whether the minter can be updated
bool public isMinterLocked;
// IPFS content hash of contract-level metadata
string private _contractURIHash = '';
//Mappings
mapping(uint256 => bool) internal axonNumberToMinted;
mapping(uint256 => uint256) internal tokenIdToNumber;
//p5js url
string p5jsUrl = 'https%3A%2F%2Fcdnjs.cloudflare.com%2Fajax%2Flibs%2Fp5.js%2F1.4.0%2Fp5.js';
string p5jsIntegrity = 'sha256-maU2GxaUCz5WChkAGR40nt9sbWRPEfF8qo%2FprxhoKPQ%3D';
string imageUrl = 'https://axons.art/api/axons/image/';
string animationUrl = 'ipfs://QmepMLoRLNUX2ratx24a12oQFuRhLsgMhM6ni3HfMzK3Fu?x=';
/**
* @notice Require that the minter has not been locked.
*/
modifier whenMinterNotLocked() {
require(!isMinterLocked, 'Minter is locked');
_;
}
constructor() ERC721("Axons", "AXONS") {
}
/*
__ __ _ _ _ ___ _ _
| \/ (_)_ _| |_(_)_ _ __ _ | __| _ _ _ __| |_(_)___ _ _ ___
| |\/| | | ' \ _| | ' \/ _` | | _| || | ' \/ _| _| / _ \ ' \(_-<
|_| |_|_|_||_\__|_|_||_\__, | |_| \_,_|_||_\__|\__|_\___/_||_/__/
|___/
*/
/**
* @dev Generates a random axon number
* @param _a The address to be used within the hash.
*/
function randomAxonNumber(
address _a,
uint256 _c
) internal returns (uint256) {
uint256 _rand = uint256(
uint256(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
_a,
_c
)
)
) % 900719925474000
);
if (axonNumberToMinted[_rand]) return randomAxonNumber(_a, _c + 1);
return _rand;
}
/**
* @notice Require that the sender is the minter.
*/
modifier onlyMinter() {
require(msg.sender == minter, 'Sender is not the minter');
_;
}
/**
* @dev Mints new tokens.
*/
function mint(uint256 axonId) public override onlyMinter returns (uint256) {
if (totalSupply() <= 1830 && totalSupply() % 30 == 0 && totalSupply() > 0) {
_mintTo(owner(), randomAxonNumber(msg.sender, 1000)); // Mint every 30th Axon to creator
}
return _mintTo(msg.sender, axonId);
}
function _mintTo(address to, uint256 axonId) internal returns (uint256) {
uint256 thisTokenId = totalSupply();
tokenIdToNumber[thisTokenId] = axonId;
axonNumberToMinted[tokenIdToNumber[thisTokenId]] = true;
_mint(to, thisTokenId);
return thisTokenId;
}
/**
* @notice Burn an axon.
*/
function burn(uint256 axonId) public override onlyMinter {
_burn(axonId);
emit AxonBurned(axonId);
}
/*
____ ___ ____ ___ _____ __ __ ____ __ ______ ____ ___ ____ _____
| \ / _] / || \ | || | || \ / ] || |/ \ | \ / ___/
| D ) / [_ | o || \ | __|| | || _ | / /| | | || || _ ( \_
| / | _]| || D | | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| \ | [_ | _ || | | _] | : || | / \_ | | | || || | |/ \ |
| . \| || | || | | | | || | \ | | | | || || | |\ |
|__|\_||_____||__|__||_____| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @notice The IPFS URI of contract-level metadata.
*/
function contractURI() public view returns (string memory) {
return string(abi.encodePacked('ipfs://', _contractURIHash));
}
/**
* @dev Number to HTML function
*/
function dataURI(uint256 _tokenId)
public override
view
returns (string memory)
{
require(_exists(_tokenId));
uint256 axonNumber = tokenIdToNumber[_tokenId];
string memory htmlString = string(
abi.encodePacked(
'data:text/html,%3Chtml%3E%3Chead%3E%3Cscript%20src%3D%22',
p5jsUrl,
'%22%20integrity%3D%22',
p5jsIntegrity,
'%22%20crossorigin%3D%22anonymous%22%3E%3C%2Fscript%3E%3Cstyle%3Ehtml%7Bheight%3A100%25%3Boverflow%3Ahidden%7Dbody%7Bmin-height%3A100%25%3Bmargin%3A0%3Bpadding%3A0%3Boverflow%3Ahidden%3Bbackground-color%3A%23111%7Dcanvas%7Bpadding%3A0%3Bmargin%3Aauto%3Bdisplay%3Ablock%3Bposition%3Aabsolute%3Btop%3A0%3Bbottom%3A0%3Bleft%3A0%3Bright%3A0%3Bimage-rendering%3Apixelated%7D%3C%2Fstyle%3E%3Cmeta%20charset%3D%22utf-8%22%3E%3C%2Fhead%3E%3Cbody%3E%3Cscript%3Evar%20gs%3DparseInt%28',
AnonymiceLibrary.toString(axonNumber),
'%29%3Bclass%20Mx%7Bconstructor%28t%2Cr%29%7Bthis.rZ%3Dt%2Cthis.cols%3Dr%2Cthis.data%3DArray%28this.rZ%29.fill%28%29.map%28%28%28%29%3D%3EArray%28this.cols%29.fill%280%29%29%29%7Dcopy%28%29%7Blet%20t%3Dnew%20Mx%28this.rZ%2Cthis.cols%29%3Bfor%28let%20r%3D0%3Br%3Cthis.rZ%3Br%2B%2B%29for%28let%20s%3D0%3Bs%3Cthis.cols%3Bs%2B%2B%29t.data%5Br%5D%5Bs%5D%3Dthis.data%5Br%5D%5Bs%5D%3Breturn%20t%7Dstatic%20fromArray%28t%29%7Breturn%20new%20Mx%28t.length%2C1%29.map%28%28%28r%2Cs%29%3D%3Et%5Bs%5D%29%29%7Dstatic%20subtract%28t%2Cr%29%7Bif%28t.rZ%3D%3D%3Dr.rZ%26%26t.cols%3D%3D%3Dr.cols%29return%20new%20Mx%28t.rZ%2Ct.cols%29.map%28%28%28s%2Ca%2Ci%29%3D%3Et.data%5Ba%5D%5Bi%5D-r.data%5Ba%5D%5Bi%5D%29%29%7DtoArray%28%29%7Blet%20t%3D%5B%5D%3Bfor%28let%20r%3D0%3Br%3Cthis.rZ%3Br%2B%2B%29for%28let%20s%3D0%3Bs%3Cthis.cols%3Bs%2B%2B%29t.push%28this.data%5Br%5D%5Bs%5D%29%3Breturn%20t%7Drdz%28%29%7Breturn%20this.map%28%28t%3D%3E2%2Arng%28%29-1%29%29%7Dadd%28t%29%7Bif%28t%20instanceof%20Mx%29%7Bif%28this.rZ%21%3D%3Dt.rZ%7C%7Cthis.cols%21%3D%3Dt.cols%29return%3Breturn%20this.map%28%28%28r%2Cs%2Ca%29%3D%3Er%2Bt.data%5Bs%5D%5Ba%5D%29%29%7Dreturn%20this.map%28%28r%3D%3Er%2Bt%29%29%7Dstatic%20trp%28t%29%7Breturn%20new%20Mx%28t.cols%2Ct.rZ%29.map%28%28%28r%2Cs%2Ca%29%3D%3Et.data%5Ba%5D%5Bs%5D%29%29%7Dstatic%20mtp%28t%2Cr%29%7Bif%28t.cols%3D%3D%3Dr.rZ%29return%20new%20Mx%28t.rZ%2Cr.cols%29.map%28%28%28s%2Ca%2Ci%29%3D%3E%7Blet%20o%3D0%3Bfor%28let%20s%3D0%3Bs%3Ct.cols%3Bs%2B%2B%29o%2B%3Dt.data%5Ba%5D%5Bs%5D%2Ar.data%5Bs%5D%5Bi%5D%3Breturn%20o%7D%29%29%7Dmtp%28t%29%7Bif%28t%20instanceof%20Mx%29%7Bif%28this.rZ%21%3D%3Dt.rZ%7C%7Cthis.cols%21%3D%3Dt.cols%29return%3Breturn%20this.map%28%28%28r%2Cs%2Ca%29%3D%3Er%2At.data%5Bs%5D%5Ba%5D%29%29%7Dreturn%20this.map%28%28r%3D%3Er%2At%29%29%7Dmap%28t%29%7Bfor%28let%20r%3D0%3Br%3Cthis.rZ%3Br%2B%2B%29for%28let%20s%3D0%3Bs%3Cthis.cols%3Bs%2B%2B%29%7Blet%20a%3Dthis.data%5Br%5D%5Bs%5D%3Bthis.data%5Br%5D%5Bs%5D%3Dt%28a%2Cr%2Cs%29%7Dreturn%20this%7Dstatic%20map%28t%2Cr%29%7Breturn%20new%20Mx%28t.rZ%2Ct.cols%29.map%28%28%28s%2Ca%2Ci%29%3D%3Er%28t.data%5Ba%5D%5Bi%5D%2Ca%2Ci%29%29%29%7Dserialize%28%29%7Breturn%20JSON.stringify%28this%29%7Dstatic%20dsr%28t%29%7B%22string%22%3D%3Dtypeof%20t%26%26%28t%3DJSON.parse%28t%29%29%3Blet%20r%3Dnew%20Mx%28t.rZ%2Ct.cols%29%3Breturn%20r.data%3Dt.data%2Cr%7D%7D%22undefined%22%21%3Dtypeof%20module%26%26%28module.exports%3DMx%29%3C%2Fscript%3E%3Cscript%3Eclass%20AAF%7Bconstructor%28i%2Ct%29%7Bthis.func%3Di%2Cthis.dfunc%3Dt%7D%7Dlet%20sigmoid%3Dnew%20AAF%28%28i%3D%3E1%2F%281%2BMath.exp%28-i%29%29%29%2C%28i%3D%3Ei%2A%281-i%29%29%29%3Bclass%20NNN%7Bconstructor%28i%2Ct%2Cs%29%7B%28this.seed%3Dgs%2Crng%3Dsrand%28this.seed%29%2Cthis.i_n%3Di%2Cthis.h_n%3Dt%2Cthis.o_n%3Ds%2Cthis.w_hi%3Dnew%20Mx%28this.h_n%2Cthis.i_n%29%2Cthis.w_ho%3Dnew%20Mx%28this.o_n%2Cthis.h_n%29%2Cthis.w_hi.rdz%28%29%2Cthis.w_ho.rdz%28%29%2Cthis.bias_h%3Dnew%20Mx%28this.h_n%2C1%29%2Cthis.bias_o%3Dnew%20Mx%28this.o_n%2C1%29%2Cthis.bias_h.rdz%28%29%2Cthis.bias_o.rdz%28%29%29%2Cthis.setLearningRate%28%29%2Cthis.setAAF%28%29%7Dpredict%28i%29%7Blet%20t%3DMx.fromArray%28i%29%2Cs%3DMx.mtp%28this.w_hi%2Ct%29%3Bs.add%28this.bias_h%29%2Cs.map%28this.a_f.func%29%3Blet%20e%3DMx.mtp%28this.w_ho%2Cs%29%3Breturn%20e.add%28this.bias_o%29%2Ce.map%28this.a_f.func%29%2Ce.toArray%28%29%7DsetLearningRate%28i%3D.1%29%7Bthis.l_r%3Di%7DsetAAF%28i%3Dsigmoid%29%7Bthis.a_f%3Di%7Dserialize%28%29%7Breturn%20JSON.stringify%28this%29%7Dstatic%20dsr%28i%29%7B%22string%22%3D%3Dtypeof%20i%26%26%28i%3DJSON.parse%28i%29%29%3Blet%20t%3Dnew%20NNN%28i.i_n%2Ci.h_n%2Ci.o_n%29%3Breturn%20t.w_hi%3DMx.dsr%28i.w_hi%29%2Ct.w_ho%3DMx.dsr%28i.w_ho%29%2Ct.bias_h%3DMx.dsr%28i.bias_h%29%2Ct.bias_o%3DMx.dsr%28i.bias_o%29%2Ct.l_r%3Di.l_r%2Ct%7Dcopy%28%29%7Breturn%20new%20NNN%28this%29%7DmtT%28i%29%7Bfunction%20t%28t%29%7Breturn%20rng%28%29%3Ci%3Ft%2BrandomGaussian%280%2C.1%29%3At%7Dthis.w_hi.map%28t%29%2Cthis.w_ho.map%28t%29%2Cthis.bias_h.map%28t%29%2Cthis.bias_o.map%28t%29%7D%7D%3C%2Fscript%3E%3Cscript%3Eclass%20Art%7Bconstructor%28t%29%7Bthis.score%3D0%2Cthis.fitness%3D0%2Cthis.frame%3D0%2Cthis.rate%3D1%2Cthis.brain%3Dt%3Ft.copy%28%29%3Anew%20NNN%281%2C8%2C38%29%7DcvC%28t%2Cr%2Ce%29%7Breturn%5BMath.round%28255%2At%5B0%5D%2B.35%2Ar%2Athis.ouT%5B35%5D%29%2CMath.round%28255%2At%5B1%5D%2B.35%2Ar%2Athis.ouT%5B36%5D%29%2CMath.round%28255%2At%5B2%5D%29%2B.35%2Ar%2Athis.ouT%5B37%5D%5D%7DgCN%28t%2Cr%2Ce%29%7Bt%25%3D35%2Ct%3DMath.round%28%28Math.sin%28t%29%2B1%29%2F2%2A55%29-1%2Cthis.brain.seed%253%3D%3D0%3Ft%3D-1%2AMath.abs%28t%29%3Athis.brain.seed%253%3D%3D1%26%26%28t%3DMath.abs%28t%29%29%3Breturn%20this.ouT%5B6%2B3%2At%5D%3F%5Bthis.ouT%5B6%2B3%2At%5D%2Cthis.ouT%5B6%2B4%2At%5D%2Cthis.ouT%5B6%2B5%2At%5D%5D%3A%5B-1%2C-1%2C-1%5D%7Dshow%28t%2Cr%2Ce%29%7BpF%7C%7C%28pF%3Dcolor%280%29%2Cfill%28pF%29%29%3Bvar%20i%2Cn%3D0%2BMath.round%285%2Athis.ouT%5B0%5D%29%2Ca%3DMath.max%28this.ouT%5B1%5D%2B3e-7%2At%2C.01%29%2At%2F12%2Cs%3DMath.max%28this.ouT%5B2%5D%2B3e-7%2Ar%2C.01%29%2Ar%2F12%2Co%3D12e3%2Athis.ouT%5B4%5D%2B%281-8e3%2Athis.ouT%5B3%5D%29%2Cu%3DMath.round%28a%2Ao%2Bs%2A%281-o%29%2An%29%2Ch%3Dthis.gCN%28u%29%3B-1%3D%3Dh%5B0%5D%3Fthis.cf%3DpF%3A%28i%3Dthis.cvC%28h%2Ct%2Cr%29%2CdrawingContext.fillStyle%3D%22rgb%28%22%2Bi%5B0%5D%2B%22%2C%22%2Bi%5B1%5D%2B%22%2C%22%2Bi%5B2%5D%2B%22%29%22%2Cthis.cf%3Di%2C%22rgba%280%2C%200%2C%200%2C%200.00%29%22%3D%3D%3DdrawingContext.fillStyle%3F%28drawingContext.fillStyle%3D%60rgb%28%24%7BpF%5B0%5D%7D%2C%20%24%7BpF%5B1%5D%7D%2C%20%24%7BpF%5B2%5D%7D%29%60%2Cthis.cf%3DpF%29%3ApF%3Di%29%3Blet%20l%3D4%2A%28r%2Ae%2Awidth%2Bt%2Ae%29%2Cc%3D%5Bpixels%5Bl%5D%2Cpixels%5Bl%2B1%5D%2Cpixels%5Bl%2B2%5D%2Cpixels%5Bl%2B3%5D%5D%3Bc%5B0%5D%3D%3Dthis.cf%5B0%5D%26%26c%5B1%5D%3D%3Dthis.cf%5B1%5D%26%26c%5B2%5D%3D%3Dthis.cf%5B2%5D%7C%7CdrawingContext.fillRect%28t%2Ae%2Cr%2Ae%2Ce%2Ce%29%7DmtT%28%29%7Bthis.brain.mtT%28.9%29%7Dthink%28%29%7Bthis.frame%2B%3Dthis.rate%2C5e-6%2Athis.frame%3E15%26%26%28this.frame%3D-5%2CcrA.brain.mtT%28.9%29%29%3Blet%20t%3D%5B%5D%3Bt%5B0%5D%3D5e-6%2Athis.frame-5%3Blet%20r%3Dthis.brain.predict%28t%29%3Bthis.ouT%3Dr%7Dupdate%28%29%7Bthis.score%2B%2B%7D%7Dvar%20pF%3Bfunction%20pickOne%28%29%7Blet%20t%3D0%2Cr%3Drandom%281%29%3Bfor%28%3Br%3E0%3B%29r-%3DsvA%5Bt%5D.fitness%2Ct%2B%2B%3Bt--%3Blet%20e%3DsvA%5Bt%5D%2Ci%3Dnew%20Art%28e.brain%29%3Breturn%20i.mtT%28%29%2Ci%7Dfunction%20ccF%28%29%7Blet%20t%3D0%3Bfor%28let%20r%20of%20svA%29t%2B%3Dr.score%3Bfor%28let%20r%20of%20svA%29r.fitness%3Dr.score%2Ft%7Dfunction%20srand%28t%29%7Breturn%20function%28%29%7Bvar%20r%3Dt%2B%3D1831565813%3Breturn%20r%3DMath.imul%28r%5Er%3E%3E%3E15%2C1%7Cr%29%2C%28%28%28r%5E%3Dr%2BMath.imul%28r%5Er%3E%3E%3E7%2C61%7Cr%29%29%5Er%3E%3E%3E14%29%3E%3E%3E0%29%2F4294967296%7D%7Dconst%20TOTAL%3D10%3Blet%20crA%2ClastFill%2Crng%2Carts%3D%5B%5D%2CsvA%3D%5B%5D%2Ccnt%3D0%2CartIndex%3D0%3Bvar%20pS%3D5%2Ccol%3D%22black%22%3Bfunction%20windowResized%28%29%7BpS%3DMath.max%28Math.round%28Math.min%281e3%2CwindowWidth%29%2F200%29%2C3%29%2CresizeCanvas%28Math.min%281e3%2CMath.max%28windowWidth%2C500%29%29%2CMath.min%281e3%2CMath.max%28windowHeight%2C500%29%29%29%7Dfunction%20setup%28%29%7BpixelDensity%281%29%2CcolorMode%28RGB%29%2CcreateCanvas%28Math.min%281e3%2CMath.max%28windowWidth%2C500%29%29%2CMath.min%281e3%2CMath.max%28windowHeight%2C500%29%29%29%2CpS%3DMath.max%28Math.round%28Math.min%281e3%2CwindowWidth%29%2F200%29%2C3%29%3Bfor%28var%20t%3D0%3Bt%3CTOTAL%3Bt%2B%2B%29arts.push%28new%20Art%29%3BframeRate%2810%29%2CnextArt%28%29%7Dfunction%20nextArt%28%29%7BcrA%3Darts.shift%28%29%2CcrA.update%28%29%2Cconsole.log%28btoa%28crA.brain.seed%29%29%2Credraw%28%29%7Dfunction%20draw%28%29%7BnoStroke%28%29%2CloadPixels%28%29%2CcrA.think%28%29%3Bfor%28var%20t%3D0%3Bt%3Cheight%2FpS%3Bt%2B%2B%29for%28var%20r%3D0%3Br%3Cwidth%2FpS%3Br%2B%2B%29crA.show%28r%2Ct%2CpS%29%7Dfunction%20keyPressed%28%29%7B%22z%22%3D%3D%3Dkey%26%26crA.brain.mtT%28.1%29%2C%22d%22%3D%3D%3Dkey%26%26crA.rate%2B%2B%2C%22a%22%3D%3D%3Dkey%26%26crA.rate--%7D%3C%2Fscript%3E%3C%2Fbody%3E%3C%2Fhtml%3E'
)
);
return htmlString;
}
/**
* @dev Returns the SVG and metadata for a token Id
* @param _tokenId The tokenId to return the SVG and metadata for.
*/
function tokenURI(uint256 _tokenId)
public
view
override
returns (string memory)
{
require(_exists(_tokenId));
string memory description = '", "description": "Axons is an infinite collection of generative pixel art, looking into the mind of a neural network (thus, no distinct traits can be distilled). A new Axon is chosen and auctioned on-chain daily based on decentralized community voting. Art is mirrored permanently on-chain. Auctions are conducted using a free, untradeable token obtained by participating in the voting process.';
uint256 axonNumber = tokenIdToNumber[_tokenId];
string memory encodedAxonNumber = AnonymiceLibrary.encode(bytes(string(abi.encodePacked(AnonymiceLibrary.toString(axonNumber)))));
return
string(
abi.encodePacked(
"data:application/json;base64,",
AnonymiceLibrary.encode(
bytes(
string(
abi.encodePacked(
'{"name": "Axons #',
AnonymiceLibrary.toString(_tokenId),
description,
'","image":"',
imageUrl,
encodedAxonNumber,
'","animation_url":"',
animationUrl,
encodedAxonNumber,
'"}'
)
)
)
)
)
);
}
/**
* @dev Returns a hash for a given tokenId
* @param _tokenId The tokenId to return the hash for.
*/
function _tokenIdToAxonNumber(uint256 _tokenId)
public
view
returns (uint256)
{
uint256 axonNumber = tokenIdToNumber[_tokenId];
return axonNumber;
}
/*
___ __ __ ____ ___ ____ _____ __ __ ____ __ ______ ____ ___ ____ _____
/ \ | |__| || \ / _]| \ | || | || \ / ] || |/ \ | \ / ___/
| || | | || _ | / [_ | D ) | __|| | || _ | / /| | | || || _ ( \_
| O || | | || | || _]| / | |_ | | || | |/ / |_| |_| | || O || | |\__ |
| || ` ' || | || [_ | \ | _] | : || | / \_ | | | || || | |/ \ |
| | \ / | | || || . \ | | | || | \ | | | | || || | |\ |
\___/ \_/\_/ |__|__||_____||__|\_| |__| \__,_||__|__|\____| |__| |____|\___/ |__|__| \___|
*/
/**
* @dev Sets the p5js url
* @param _p5jsUrl The address of the p5js file hosted on CDN
*/
function setJsAddress(string memory _p5jsUrl) public onlyOwner {
p5jsUrl = _p5jsUrl;
}
/**
* @dev Sets the p5js resource integrity
* @param _p5jsIntegrity The hash of the p5js file (to protect w subresource integrity)
*/
function setJsIntegrity(string memory _p5jsIntegrity) public onlyOwner {
p5jsIntegrity = _p5jsIntegrity;
}
/**
* @dev Sets the base image url
* @param _imageUrl The base url for image field
*/
function setImageUrl(string memory _imageUrl) public onlyOwner {
imageUrl = _imageUrl;
}
/**
* @dev Sets the base animation url
* @param _animationUrl The base url for animations
*/
function setAnimationUrl(string memory _animationUrl) public onlyOwner {
animationUrl = _animationUrl;
}
/**
* @notice Set the token minter.
* @dev Only callable by the owner when not locked.
*/
function setMinter(address _minter) external override onlyOwner whenMinterNotLocked {
minter = _minter;
emit MinterUpdated(_minter);
}
/**
* @notice Lock the minter.
* @dev This cannot be reversed and is only callable by the owner when not locked.
*/
function lockMinter() external override onlyOwner whenMinterNotLocked {
isMinterLocked = true;
emit MinterLocked();
}
/**
* @notice Set the _contractURIHash.
* @dev Only callable by the owner.
*/
function setContractURIHash(string memory newContractURIHash) external onlyOwner {
_contractURIHash = newContractURIHash;
}
} | * @notice Set the token minter. @dev Only callable by the owner when not locked./ | function setMinter(address _minter) external override onlyOwner whenMinterNotLocked {
minter = _minter;
emit MinterUpdated(_minter);
}
| 6,197,432 | [
1,
694,
326,
1147,
1131,
387,
18,
225,
5098,
4140,
635,
326,
3410,
1347,
486,
8586,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
15430,
2761,
12,
2867,
389,
1154,
387,
13,
3903,
3849,
1338,
5541,
1347,
49,
2761,
1248,
8966,
288,
203,
3639,
1131,
387,
273,
389,
1154,
387,
31,
203,
540,
203,
3639,
3626,
490,
2761,
7381,
24899,
1154,
387,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
contract EthGods {
// imported contracts
EthGodsName private eth_gods_name;
function set_eth_gods_name_contract_address(address eth_gods_name_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_name = EthGodsName(eth_gods_name_contract_address);
return true;
}
EthGodsDice private eth_gods_dice;
function set_eth_gods_dice_contract_address(address eth_gods_dice_contract_address) public returns (bool) {
require(msg.sender == admin);
eth_gods_dice = EthGodsDice(eth_gods_dice_contract_address);
return true;
}
// end of imported contracts
// start of database
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private contact_email = "[email protected]";
string private official_url = "swarm-gateways.net/bzz:/ethgods.eth";
address private admin; // public when testing
address private controller1 = 0xcA5A9Db0EF9a0Bf5C38Fc86fdE6CB897d9d86adD; // controller can change admin at once;
address private controller2 = 0x8396D94046a099113E5fe5CBad7eC95e96c2B796; // controller can change admin at once;
address private v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
uint private block_hash_duration = 255; // can't get block hash, after 256 blocks, adjustable
// god
struct god {
uint god_id;
uint level;
uint exp;
uint pet_type;// 12 animals or zodiacs
uint pet_level;
uint listed; // 0 not a god, 1 - ... rank_score in god list
uint invite_price;
uint blessing_player_id;
bool hosted_pray; // auto waitlist, when enlisted. others can invite, once hosted pray
uint bid_eth; // bid to host pray
uint credit; // gained from the amulet invitation spending of invited fellows
uint count_amulets_generated;
uint first_amulet_generated;
uint count_amulets_at_hand;
uint count_amulets_selling;
uint amulets_start_id;
uint amulets_end_id;
uint count_token_orders;
uint first_active_token_order;
uint allowed_block; // allow another account to use my egst
uint block_number; // for pray
bytes32 gene;
bool gene_created;
bytes32 pray_hash; //hash created for each pray
uint inviter_id; // who invited this fellow to this world
uint count_gods_invited; // gods invited to this game by this god.
}
uint private count_gods = 0; // Used when generating id for a new player,
mapping(address => god) private gods; // everyone is a god
mapping(uint => address) private gods_address; // gods' address => god_id
uint [] private listed_gods; // id of listed gods
uint private max_listed_gods = 10000; // adjustable
uint private initial_invite_price = 0.02 ether; // grows with each invitation for this god
uint private invite_price_increase = 0.02 ether; // grows by this amount with each invitation
uint private max_invite_price = 1000 ether; // adjustable
uint private max_extra_eth = 0.001 ether; // adjustable
uint private list_level = 10; // start from level 10
uint private max_gas_price = 100000000000; // 100 gwei for invite and pray, adjustable
// amulet
struct amulet {
uint god_id;
address owner;
uint level;
uint bound_start_block;// can't sell, if just got
// bool selling;
uint start_selling_block; // can't bind & use in pk, if selling
uint price; // set to 0, when withdraw from selling or bought
// uint order_id; // should be 0, if not selling
}
uint private count_amulets = 0;
mapping(uint => amulet) private amulets; // public when testing
uint private bound_duration = 9000; // once bought, wait a while before sell it again, adjustable
uint private order_duration = 20000; // valid for about 3 days, then not to show to public in selling amulets/token orders, but still show in my_selling amulets/token orders. adjustable
// pray
address private pray_host_god; // public when testing
bool private pray_reward_top100; // if hosted by new god, reward top 100 gods egst
uint private pray_start_block; // public when testing
bool private rewarded_pray_winners = false;
uint private count_hosted_gods; // gods hosted pray (event started). If less than bidding gods, there are new gods waiting to host pray,
mapping (uint => address) private bidding_gods; // every listed god and bid to host pray
uint private initializer_reward = 36; // reward the god who burned gas to send pray rewards to community, adjustable
mapping(uint => uint) private max_winners; // max winners for each prize
uint private min_pray_interval = 2000; // 2000, 36 in CBT, 2 in dev, adjustable
uint private min_pray_duration = 6000; // 6000, 600 in CBT, 60 in dev, adjustable
uint private max_pray_duration = 9000; // 9000, 900 in CBT, 90 in dev, adjustable
uint private count_waiting_prayers;
mapping (uint => address) private waiting_prayers; // uint is waiting sequence
uint private waiting_prayer_index = 1; // waiting sequence of the prayer ready to draw lot
mapping(uint => uint) private pk_positions; // public when testing
mapping(uint => uint) private count_listed_winners; // count for 5 prizes, public in testing
mapping (uint => mapping(uint => address)) private listed_winners; // winners for 5 prizes
bool private reEntrancyMutex = false; // for sendnig eth to msg.sender
uint private pray_egses = 0; // 10% from reward pool to top 3 winners in each round of pray events
uint private pray_egst = 0; // 10% from reward pool to 3rd & 4th prize winners in each round of pray events
mapping(address => uint) egses_balances;
// eth_gods_token (EGST)
string public name = "EthGodsToken";
string public symbol = "EGST";
uint8 public decimals = 18; //same as ethereum
uint private _totalSupply;
mapping(address => uint) balances; // bought or gained from pray or revenue share
mapping(address => mapping(address => uint)) allowed;
uint private allowed_use_CD = 20; // if used allowed amount, have to wait a while before approve new allowed amount again, prevent cheating, adjustable
struct token_order {
uint id;
uint start_selling_block;
address seller;
uint unit_price;
uint egst_amount;
}
uint private count_token_orders = 0;
mapping (uint => token_order) token_orders;
uint private first_active_token_order = 0;
uint private min_unit_price = 20; // 1 egst min value is 0.0002 ether, adjustable
uint private max_unit_price = 200; // 1 egst max value is 0.002 ether, adjustable
uint private max_egst_amount = 1000000 ether; // for create_token_order, adjustable
uint private min_egst_amount = 0.00001 ether; // for create_token_order, adjustable
//logs
uint private count_rounds = 0;
struct winner_log { // win a prize and if pk
uint god_block_number;
bytes32 block_hash;
address prayer;
address previous_winner;
uint prize;
bool pk_result;
}
mapping (uint => uint) private count_rounds_winner_logs;
mapping(uint => mapping(uint => winner_log)) private winner_logs;
struct change_log {
uint block_number;
uint asset_type; // 1 egst, 2 eth_surplus
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token,
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward
uint reason; // > 10 is buy token unit_price
uint change_amount;
uint after_amount;
address _from;
address _to;
}
mapping (uint => uint) private count_rounds_change_logs;
mapping(uint => mapping(uint => change_log)) private change_logs;
// end of database
// start of constructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
create_god(admin, 0);
create_god(v_god, 0);
gods[v_god].level = 10;
enlist_god(v_god);
max_winners[1] = 1; // 1
max_winners[2] = 2; // 2
max_winners[3] = 8; // 8
max_winners[4] = 16; // 16
max_winners[5] = 100; // 100
_totalSupply = 6000000 ether;
pray_egst = 1000 ether;
balances[admin] = sub(_totalSupply, pray_egst);
initialize_pray();
}
// destruct for testing contracts. can't destruct since round 3
function finalize() public {
require(msg.sender == admin && count_rounds <= 3);
selfdestruct(admin);
}
function () public payable {
revert ();
}
// end of constructor
//start of contract information & administration
function get_controller () public view returns (address, address){
require (msg.sender == admin || msg.sender == controller1 || msg.sender == controller2);
return (controller1, controller2);
}
function set_controller (uint controller_index, address new_controller_address) public returns (bool){
if (controller_index == 1){
require(msg.sender == controller2);
controller1 = new_controller_address;
} else {
require(msg.sender == controller1);
controller2 = new_controller_address;
}
return true;
}
function set_admin (address new_admin_address) public returns (bool) {
require (msg.sender == controller1 || msg.sender == controller2);
// admin don't have game attributes, such as level'
// no need to transfer egses and egst to new_admin_address
delete gods[admin];
admin = new_admin_address;
gods_address[0] = admin;
gods[admin].god_id = 0;
return true;
}
// update system parameters
function set_parameters (uint parameter_type, uint new_parameter) public returns (bool){
require (msg.sender == admin);
if (parameter_type == 1) {
max_pray_duration = new_parameter;
} else if (parameter_type == 2) {
min_pray_duration = new_parameter;
} else if (parameter_type == 3) {
block_hash_duration = new_parameter;
} else if (parameter_type == 4) {
min_pray_interval = new_parameter;
} else if (parameter_type == 5) {
order_duration = new_parameter;
} else if (parameter_type == 6) {
bound_duration = new_parameter;
} else if (parameter_type == 7) {
initializer_reward = new_parameter;
} else if (parameter_type == 8) {
allowed_use_CD = new_parameter;
} else if (parameter_type == 9) {
min_unit_price = new_parameter;
} else if (parameter_type == 10) {
max_unit_price = new_parameter;
} else if (parameter_type == 11) {
max_listed_gods = new_parameter;
} else if (parameter_type == 12) {
max_gas_price = new_parameter;
} else if (parameter_type == 13) {
max_invite_price = new_parameter;
} else if (parameter_type == 14) {
min_egst_amount = new_parameter;
} else if (parameter_type == 15) {
max_egst_amount = new_parameter;
} else if (parameter_type == 16) {
max_extra_eth = new_parameter;
}
return true;
}
function set_strings (uint string_type, string new_string) public returns (bool){
require (msg.sender == admin);
if (string_type == 1){
official_url = new_string;
} else if (string_type == 2){
name = new_string; // egst name
} else if (string_type == 3){
symbol = new_string; // egst symbol
}
return true;
}
// for basic information to show to players, and to update parameter in sub-contracts
function query_contract () public view returns(uint, uint, address, uint, string, uint, uint){
return (count_gods,
listed_gods.length,
admin,
block_hash_duration,
official_url,
bound_duration,
min_pray_interval
);
}
function query_uints () public view returns (uint[7] uints){
uints[0] = max_invite_price;
uints[1] = list_level;
uints[2] = max_pray_duration;
uints[3] = min_pray_duration;
uints[4] = initializer_reward;
uints[5] = min_unit_price;
uints[6] = max_unit_price;
return uints;
}
function query_uints2 () public view returns (uint[6] uints){
uints[0] = allowed_use_CD;
uints[1] = max_listed_gods;
uints[2] = max_gas_price;
uints[3] = min_egst_amount;
uints[4] = max_egst_amount;
uints[5] = max_extra_eth;
return uints;
}
//end of contract information & administration
// god related functions: register, create_god, upgrade_pet, add_exp, burn_gas, invite, enlist
// if a new player comes when a round just completed, the new player may not want to initialize the next round
function register_god (uint inviter_id) public returns (uint) {
return create_god(msg.sender, inviter_id);
}
function create_god (address god_address, uint inviter_id) private returns(uint god_id){ // created by the contract // public when testing
// check if the god is already created
if (gods[god_address].credit == 0) { // create admin as god[0]
gods[god_address].credit = 1; // give 1 credit, so we know this address has a god
god_id = count_gods; // 1st god's id is admin 0
count_gods = add(count_gods, 1) ;
gods_address[god_id] = god_address;
gods[god_address].god_id = god_id;
if (god_id > 0){ // not admin
add_exp(god_address, 100);
set_inviter(inviter_id);
}
return god_id;
}
}
function set_inviter (uint inviter_id) public returns (bool){
if (inviter_id > 0 && gods_address[inviter_id] != address(0)
&& gods[msg.sender].inviter_id == 0
&& gods[gods_address[inviter_id]].inviter_id != gods[msg.sender].god_id){
gods[msg.sender].inviter_id = inviter_id;
address inviter_address = gods_address[inviter_id];
gods[inviter_address].count_gods_invited = add(gods[inviter_address].count_gods_invited, 1);
return true;
}
}
function add_exp (address god_address, uint exp_up) private returns(uint new_level, uint new_exp) { // public when testing
if (god_address == admin){
return (0,0);
}
if (gods[god_address].god_id == 0){
uint inviter_id = gods[god_address].inviter_id;
create_god(god_address, inviter_id);
}
new_exp = add(gods[god_address].exp, exp_up);
uint current_god_level = gods[god_address].level;
uint level_up_exp;
new_level = current_god_level;
for (uint i=0;i<10;i++){ // if still have extra exp, level up next time
if (current_god_level < 99){
level_up_exp = mul(10, add(new_level, 1));
} else {
level_up_exp = 1000;
}
if (new_exp >= level_up_exp){
new_exp = sub(new_exp, level_up_exp);
new_level = add(new_level, 1);
} else {
break;
}
}
gods[god_address].exp = new_exp;
if(new_level > current_god_level) {
gods[god_address].level = new_level;
if (gods[god_address].listed > 0) {
if (listed_gods.length > 1) {
sort_gods(gods[god_address].god_id);
}
} else if (new_level >= list_level && listed_gods.length < max_listed_gods) {
enlist_god(god_address);
}
}
return (new_level, new_exp);
}
function enlist_god (address god_address) private returns (uint) { // public when testing
require(gods[god_address].level >= list_level && god_address != admin);
// if the god is not listed yet, enlist and add level requirement for the next enlist
if (gods[god_address].listed == 0) {
uint god_id = gods[god_address].god_id;
if (god_id == 0){
god_id = create_god(god_address, 0); // get a god_id and set inviter as v god
}
gods[god_address].listed = listed_gods.push(god_id); // start from 1, 0 is not listed
gods[god_address].invite_price = initial_invite_price;
list_level = add(list_level, 1);
bidding_gods[listed_gods.length] = god_address;
}
return list_level;
}
function sort_gods_admin(uint god_id) public returns (bool){
require (msg.sender == admin);
sort_gods(god_id);
return true;
}
// when a listed god level up and is not top 1 of the list, compare power with higher god, if higher than the higher god, swap position
function sort_gods (uint god_id) private returns (uint){
require (god_id > 0);
uint list_length = listed_gods.length;
if (list_length > 1) {
address god_address = gods_address[god_id];
uint this_god_listed = gods[god_address].listed;
if (this_god_listed < list_length) {
uint higher_god_listed = add(this_god_listed, 1);
uint higher_god_id = listed_gods[sub(higher_god_listed, 1)];
address higher_god = gods_address[higher_god_id];
if(gods[god_address].level > gods[higher_god].level
|| (gods[god_address].level == gods[higher_god].level
&& gods[god_address].exp > gods[higher_god].exp)){
listed_gods[sub(this_god_listed, 1)] = higher_god_id;
listed_gods[sub(higher_god_listed, 1)] = god_id;
gods[higher_god].listed = this_god_listed;
gods[god_address].listed = higher_god_listed;
}
}
}
return gods[god_address].listed;
}
function burn_gas (uint god_id) public returns (uint god_new_level, uint god_new_exp) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].listed > 0);
add_exp(god_address, 1);
add_exp(msg.sender, 1);
return (gods[god_address].level, gods[god_address].exp); // return bool, if out of gas
}
function invite (uint god_id) public payable returns (uint new_invite_price) {
address god_address = gods_address[god_id];
require(god_id > 0
&& god_id <= count_gods
&& gods[god_address].hosted_pray == true
&& tx.gasprice <= max_gas_price
);
uint invite_price = gods[god_address].invite_price;
require(msg.value >= invite_price);
if (gods[god_address].invite_price < max_invite_price) {
gods[god_address].invite_price = add(invite_price, invite_price_increase);
}
uint exp_up = div(invite_price, (10 ** 15)); // 1000 exp for each eth
add_exp(god_address, exp_up);
add_exp(msg.sender, exp_up);
//generate a new amulet of this god for the inviter
count_amulets ++;
amulets[count_amulets].god_id = god_id;
amulets[count_amulets].owner = msg.sender;
gods[god_address].count_amulets_generated = add(gods[god_address].count_amulets_generated, 1);
if (gods[god_address].count_amulets_generated == 1){
gods[god_address].first_amulet_generated = count_amulets;
}
gods[msg.sender].count_amulets_at_hand = add(gods[msg.sender].count_amulets_at_hand, 1);
update_amulets_count(msg.sender, count_amulets, true);
// invite_price to egses: 60% to pray_egses, 20% to god, changed
// pray_egses = add(pray_egses, div(mul(60, invite_price), 100));
// egses_from_contract(gods_address[god_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited
// reduce reward pool share from 60 to 50%, reduce god reward from 20% to 10%
// add 20% share to blessing player (the last player invited this god)
pray_egses = add(pray_egses, div(mul(50, invite_price), 100));
egses_from_contract(god_address, div(mul(10, invite_price), 100), 2); //2 reward god for being invited
egses_from_contract(gods_address[gods[god_address].blessing_player_id], div(mul(20, invite_price), 100), 2); //2 reward god for being invited, no need to check if blessing player id is > 0
gods[god_address].blessing_player_id = gods[msg.sender].god_id;
reward_inviter(msg.sender, invite_price);
emit invited_god (msg.sender, god_id);
return gods[god_address].invite_price;
}
event invited_god (address msg_sender, uint god_id);
function reward_inviter (address inviter_address, uint invite_price) private returns (bool){
// the fellow spending eth also get credit and share
uint previous_share = 0;
uint inviter_share = 0;
uint share_diff;
// uint invite_credit = div(invite_price, 10 ** 15);
for (uint i = 0; i < 9; i++){ // max trace 9 layers of inviter
if (inviter_address != address(0) && inviter_address != admin){ // admin doesn't get reward or credit
share_diff = 0;
// gods[inviter_address].credit = add(gods[inviter_address].credit, invite_credit);
gods[inviter_address].credit = add(gods[inviter_address].credit, invite_price);
inviter_share = get_vip_level(inviter_address);
if (inviter_share > previous_share) {
share_diff = sub(inviter_share, previous_share);
if (share_diff > 18) {
share_diff = 18;
}
previous_share = inviter_share;
}
if (share_diff > 0) {
egses_from_contract(inviter_address, div(mul(share_diff, invite_price), 100), 3); // 3 inviter_reward
}
inviter_address = gods_address[gods[inviter_address].inviter_id]; // get the address of inviter's inviter'
} else{
break;
}
}
// invite_price to egses: sub(20%, previous_share) to admin
share_diff = sub(20, inviter_share);
egses_from_contract(admin, div(mul(share_diff, invite_price), 100), 2); // remaining goes to admin, 2 god_reward for being invited
return true;
}
function upgrade_pet () public returns(bool){
//use egst to level up pet;
uint egst_cost = mul(add(gods[msg.sender].pet_level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 6);// 6 upgrade_pet
gods[msg.sender].pet_level = add(gods[msg.sender].pet_level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
emit upgradeAmulet(msg.sender, 0, gods[msg.sender].pet_level);
return true;
}
event upgradeAmulet (address owner, uint amulet_id, uint new_level);
function set_pet_type (uint new_type) public returns (bool){
if (gods[msg.sender].pet_type != new_type) {
gods[msg.sender].pet_type = new_type;
return true;
}
}
function get_vip_level (address god_address) public view returns (uint vip_level){
uint inviter_credit = gods[god_address].credit;
if (inviter_credit > 500 ether){
vip_level = 18;
} else if (inviter_credit > 200 ether){
vip_level = 15;
} else if (inviter_credit > 100 ether){
vip_level = 12;
} else if (inviter_credit > 50 ether){
vip_level = 10;
} else if (inviter_credit > 20 ether){
vip_level = 8;
} else if (inviter_credit > 10 ether){
vip_level = 6;
} else if (inviter_credit > 5 ether){
vip_level = 5;
} else if (inviter_credit > 2 ether){
vip_level = 4;
} else if (inviter_credit > 1 ether){
vip_level = 3;
} else if (inviter_credit > 0.5 ether){
vip_level = 2;
} else {
vip_level = 1;
}
return vip_level;
}
// view god's information
function get_god_id (address god_address) public view returns (uint god_id){
return gods[god_address].god_id;
}
function get_god_address(uint god_id) public view returns (address){
return gods_address[god_id];
}
function get_god (uint god_id) public view returns(uint, string, uint, uint, uint, uint, uint) {
address god_address = gods_address[god_id];
string memory god_name;
god_name = eth_gods_name.get_god_name(god_address);
if (bytes(god_name).length == 0){
god_name = "Unknown";
}
return (gods[god_address].god_id,
god_name,
gods[god_address].level,
gods[god_address].exp,
gods[god_address].invite_price,
gods[god_address].listed,
gods[god_address].blessing_player_id
);
}
function get_god_info (address god_address) public view returns (uint, bytes32, bool, uint, uint, uint, bytes32){
return (gods[god_address].block_number,
gods[god_address].gene,
gods[god_address].gene_created,
gods[god_address].pet_type,
gods[god_address].pet_level,
gods[god_address].bid_eth,
gods[god_address].pray_hash
);
}
function get_god_hosted_pray (uint god_id) public view returns (bool){
return gods[gods_address[god_id]].hosted_pray;
}
function get_my_info () public view returns(uint, uint, uint, uint, uint, uint, uint) { //private information
return (gods[msg.sender].god_id,
egses_balances[msg.sender], //egses
balances[msg.sender], //egst
get_vip_level(msg.sender),
gods[msg.sender].credit, // inviter_credit
gods[msg.sender].inviter_id,
gods[msg.sender].count_gods_invited
);
}
function get_listed_gods (uint page_number) public view returns (uint[]){
uint count_listed_gods = listed_gods.length;
require(count_listed_gods <= mul(page_number, 20));
uint[] memory tempArray = new uint[] (20);
if (page_number < 1) {
page_number = 1;
}
for (uint i = 0; i < 20; i++){
if(count_listed_gods > add(i, mul(20, sub(page_number, 1)))) {
tempArray[i] = listed_gods[sub(sub(sub(count_listed_gods, i), 1), mul(20, sub(page_number, 1)))];
} else {
break;
}
}
return tempArray;
}
// amulets
function upgrade_amulet (uint amulet_id) public returns(uint){
require(amulets[amulet_id].owner == msg.sender);
uint egst_cost = mul(add(amulets[amulet_id].level, 1), 10 ether);
egst_to_contract(msg.sender, egst_cost, 7);// reason 7, upgrade_amulet
pray_egst = add(pray_egst, egst_cost);
// pray_egst = add(pray_egst, div(egst_cost, 2));
// egst_from_contract(admin, div(egst_cost, 2), 8); // 8 admin reward
amulets[amulet_id].level = add(amulets[amulet_id].level, 1);
add_exp(msg.sender, div(egst_cost, 1 ether));
emit upgradeAmulet(msg.sender, amulet_id, amulets[amulet_id].level);
return amulets[amulet_id].level;
}
function create_amulet_order (uint amulet_id, uint price) public returns (uint) {
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block == 0
&& add(amulets[amulet_id].bound_start_block, bound_duration) < block.number
&& price > 0);
amulets[amulet_id].start_selling_block = block.number;
amulets[amulet_id].price = price;
gods[msg.sender].count_amulets_at_hand = sub(gods[msg.sender].count_amulets_at_hand, 1);
gods[msg.sender].count_amulets_selling = add(gods[msg.sender].count_amulets_selling, 1);
return gods[msg.sender].count_amulets_selling;
}
function buy_amulet (uint amulet_id) public payable returns (bool) {
uint price = amulets[amulet_id].price;
require(msg.value >= price && msg.value < add(price, max_extra_eth)
&& amulets[amulet_id].start_selling_block > 0
&& amulets[amulet_id].owner != msg.sender
&& price > 0);
address seller = amulets[amulet_id].owner;
amulets[amulet_id].owner = msg.sender;
amulets[amulet_id].bound_start_block = block.number;
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
update_amulets_count(msg.sender, amulet_id, true);
gods[seller].count_amulets_selling--;
update_amulets_count(seller, amulet_id, false);
egses_from_contract(seller, price, 6); // 6 sell amulet
return true;
}
function withdraw_amulet_order (uint amulet_id) public returns (uint){
// an amulet can only have one order_id, so withdraw amulet_id instead of withdraw order_id, since only amulet_id is shown in amulets_at_hand
require(msg.sender == amulets[amulet_id].owner
&& amulet_id >= 1 && amulet_id <= count_amulets
&& amulets[amulet_id].start_selling_block > 0);
amulets[amulet_id].start_selling_block = 0;
gods[msg.sender].count_amulets_at_hand++;
gods[msg.sender].count_amulets_selling--;
return gods[msg.sender].count_amulets_selling;
}
function update_amulets_count (address god_address, uint amulet_id, bool obtained) private returns (uint){
if (obtained == true){
if (amulet_id < gods[god_address].amulets_start_id) {
gods[god_address].amulets_start_id = amulet_id;
}
} else {
if (amulet_id == gods[god_address].amulets_start_id){
for (uint i = amulet_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && i > amulet_id){
gods[god_address].amulets_start_id = i;
break;
}
}
}
}
return gods[god_address].amulets_start_id;
}
function get_amulets_generated (uint god_id) public view returns (uint[]) {
address god_address = gods_address[god_id];
uint count_amulets_generated = gods[god_address].count_amulets_generated;
uint [] memory temp_list = new uint[](count_amulets_generated);
uint count_elements = 0;
for (uint i = gods[god_address].first_amulet_generated; i <= count_amulets; i++){
if (amulets[i].god_id == god_id){
temp_list [count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_generated){
break;
}
}
}
return temp_list;
}
function get_amulets_at_hand (address god_address) public view returns (uint[]) {
uint count_amulets_at_hand = gods[god_address].count_amulets_at_hand;
uint [] memory temp_list = new uint[] (count_amulets_at_hand);
uint count_elements = 0;
for (uint i = gods[god_address].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_at_hand){
break;
}
}
}
return temp_list;
}
function get_my_amulets_selling () public view returns (uint[]){
uint count_amulets_selling = gods[msg.sender].count_amulets_selling;
uint [] memory temp_list = new uint[] (count_amulets_selling);
uint count_elements = 0;
for (uint i = gods[msg.sender].amulets_start_id; i <= count_amulets; i++){
if (amulets[i].owner == msg.sender
&& amulets[i].start_selling_block > 0){
temp_list[count_elements] = i;
count_elements++;
if (count_elements >= count_amulets_selling){
break;
}
}
}
return temp_list;
}
// to calculate how many pages
function get_amulet_orders_overview () public view returns(uint){
uint count_amulets_selling = 0;
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
count_amulets_selling ++;
}
}
return count_amulets_selling; // to show page numbers when getting amulet_orders
}
function get_amulet_orders (uint page_number) public view returns (uint[]){
uint[] memory temp_list = new uint[] (20);
uint count_amulets_selling = 0;
uint count_list_elements = 0;
if ((page_number < 1)
|| count_amulets <= 20) {
page_number = 1; // chose a page out of range
}
uint start_amulets_count = mul(sub(page_number, 1), 20);
for (uint i = 1; i <= count_amulets; i++){
if (add(amulets[i].start_selling_block, order_duration) > block.number && amulets[i].owner != msg.sender){
if (count_amulets_selling <= start_amulets_count) {
count_amulets_selling ++;
}
if (count_amulets_selling > start_amulets_count){
temp_list[count_list_elements] = i;
count_list_elements ++;
if (count_list_elements >= 20){
break;
}
}
}
}
return temp_list;
}
function get_amulet (uint amulet_id) public view returns(address, string, uint, uint, uint, uint, uint){
uint god_id = amulets[amulet_id].god_id;
// address god_address = gods_address[god_id];
string memory god_name = eth_gods_name.get_god_name(gods_address[god_id]);
uint god_level = gods[gods_address[god_id]].level;
uint amulet_level = amulets[amulet_id].level;
uint start_selling_block = amulets[amulet_id].start_selling_block;
uint price = amulets[amulet_id].price;
return(amulets[amulet_id].owner,
god_name,
god_id,
god_level,
amulet_level,
start_selling_block,
price
);
}
function get_amulet2 (uint amulet_id) public view returns(uint){
return amulets[amulet_id].bound_start_block;
}
// end of amulet
// start of pray
function admin_deposit (uint egst_amount) public payable returns (bool) {
require (msg.sender == admin);
if (msg.value > 0){
pray_egses = add(pray_egses, msg.value);
egses_from_contract(admin, msg.value, 4); // 4 admin_deposit to reward_pool
}
if (egst_amount > 0){
pray_egst = add(pray_egst, egst_amount);
egst_to_contract(admin, egst_amount, 4); // 4 admin_deposit to reward_pool
}
return true;
}
function initialize_pray () private returns (bool){
if (pray_start_block > 0) {
require (check_event_completed() == true
&& rewarded_pray_winners == true);
}
count_rounds = add(count_rounds, 1);
count_rounds_winner_logs[count_rounds] = 0;
pray_start_block = block.number;
rewarded_pray_winners = false;
for (uint i = 1; i <= 5; i++){
pk_positions[i] = max_winners[i]; // pk start from the last slot
count_listed_winners[i] = 0;
}
if (listed_gods.length > count_hosted_gods) {
// a new god's turn
count_hosted_gods = add(count_hosted_gods, 1);
pray_host_god = bidding_gods[count_hosted_gods];
gods[pray_host_god].hosted_pray = true;
pray_reward_top100 = true;
} else {
//choose highest bidder
(uint highest_bid, address highest_bidder) = compare_bid_eth();
gods[highest_bidder].bid_eth = 0;
pray_host_god = highest_bidder;
pray_egses = add(pray_egses, highest_bid);
pray_reward_top100 = false;
}
return true;
}
function bid_host () public payable returns (bool) {
require (msg.value > 0 && gods[msg.sender].listed > 0);
gods[msg.sender].bid_eth = add (gods[msg.sender].bid_eth, msg.value);
return true;
}
function withdraw_bid () public returns (bool) {
require(gods[msg.sender].bid_eth > 0);
gods[msg.sender].bid_eth = 0;
egses_from_contract(msg.sender, gods[msg.sender].bid_eth, 8); // 8 withdraw bid
return true;
}
// if browser web3 didn't get god's credit, use pray_create in the pray button to create god_id first
function pray_create (uint inviter_id) public returns (bool) {
// when create a new god, set credit as 1, so credit <= 0 means god_id not created yet
create_god(msg.sender, inviter_id);
pray();
}
// if browser web3 got god's credit, use pray in the pray button
function pray () public returns (bool){
require (add(gods[msg.sender].block_number, min_pray_interval) < block.number
&& tx.gasprice <= max_gas_price
&& check_event_completed() == false);
if (waiting_prayer_index <= count_waiting_prayers) {
address waiting_prayer = waiting_prayers[waiting_prayer_index];
uint god_block_number = gods[waiting_prayer].block_number;
bytes32 block_hash;
if ((add(god_block_number, 1)) < block.number) {// can only get previous block hash
if (add(god_block_number, block_hash_duration) < block.number) {// make sure this god has a valid block_number to generate block hash
gods[waiting_prayer].block_number = block.number; // refresh this god's expired block_id
// delete waiting_prayers[waiting_prayer_index];
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = waiting_prayer;
} else {// draw lottery and/or create gene for the waiting prayer
block_hash = keccak256(abi.encodePacked(blockhash(add(god_block_number, 1))));
if(gods[waiting_prayer].gene_created == false){
gods[waiting_prayer].gene = block_hash;
gods[waiting_prayer].gene_created = true;
}
gods[waiting_prayer].pray_hash = block_hash;
uint dice_result = eth_gods_dice.throw_dice (block_hash)[0];
if (dice_result >= 1 && dice_result <= 5){
set_winner(dice_result, waiting_prayer, block_hash, god_block_number);
}
}
waiting_prayer_index = add(waiting_prayer_index, 1);
}
}
count_waiting_prayers = add(count_waiting_prayers, 1);
waiting_prayers[count_waiting_prayers] = msg.sender;
gods[msg.sender].block_number = block.number;
add_exp(msg.sender, 1);
add_exp(pray_host_god, 1);
return true;
}
function set_winner (uint prize, address waiting_prayer, bytes32 block_hash, uint god_block_number) private returns (uint){
count_rounds_winner_logs[count_rounds] = add(count_rounds_winner_logs[count_rounds], 1);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].god_block_number = god_block_number;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].block_hash = block_hash;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prayer = waiting_prayer;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].prize = prize;
if (count_listed_winners[prize] >= max_winners[prize]){ // winner_list maxed, so the new prayer challenge previous winners
uint pk_position = pk_positions[prize];
address previous_winner = listed_winners[prize][pk_position];
bool pk_result = pk(waiting_prayer, previous_winner, block_hash);
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].pk_result = pk_result;
winner_logs[count_rounds][count_rounds_winner_logs[count_rounds]].previous_winner = previous_winner;
if (pk_result == true) {
listed_winners[prize][pk_position] = waiting_prayer; // attacker defeat defender
}
if (prize > 1) { // no need to change pk_pos for champion
if (pk_positions[prize] > 1){
pk_positions[prize] = sub(pk_positions[prize], 1);
} else {
pk_positions[prize] = max_winners[prize];
}
}
} else {
count_listed_winners[prize] = add(count_listed_winners[prize], 1);
listed_winners[prize][count_listed_winners[prize]] = waiting_prayer;
}
return count_listed_winners[prize];
}
function reward_pray_winners () public returns (bool){
require (check_event_completed() == true);
uint this_reward_egses;
uint reward_pool_egses = div(pray_egses, 10);
pray_egses = sub(pray_egses, reward_pool_egses);
uint this_reward_egst;
uint reward_pool_egst = div(pray_egst, 10);
pray_egst = sub(pray_egst, reward_pool_egst); // reduce sum for less calculation
egst_from_contract(pray_host_god, mul(div(reward_pool_egst, 100), 60), 1); // 1 pray_reward for hosting event
for (uint i = 1; i<=5; i++){
this_reward_egses = 0;
this_reward_egst = 0;
if (i == 1) {
this_reward_egses = mul(div(reward_pool_egses, 100), 60);
} else if (i == 2){
this_reward_egses = mul(div(reward_pool_egses, 100), 20);
} else if (i == 3){
this_reward_egst = mul(div(reward_pool_egst, 100), 3);
} else if (i == 4){
this_reward_egst = div(reward_pool_egst, 100);
}
for (uint reward_i = 1; reward_i <= count_listed_winners[i]; reward_i++){
address rewarding_winner = listed_winners[i][reward_i];
if (this_reward_egses > 0 ) {
egses_from_contract(rewarding_winner, this_reward_egses, 1); // 1 pray_reward
} else if (this_reward_egst > 0) {
egst_from_contract(rewarding_winner, this_reward_egst, 1); // 1 pray_reward
}
add_exp(rewarding_winner, 6);
}
}
if(pray_reward_top100 == true) {
reward_top_gods();
}
// a small gift of exp & egst to the god who burned gas to send rewards to the community
egst_from_contract(msg.sender, mul(initializer_reward, 1 ether), 1); // 1 pray_reward
_totalSupply = add(_totalSupply, mul(initializer_reward, 1 ether));
add_exp(msg.sender, initializer_reward);
rewarded_pray_winners = true;
initialize_pray();
return true;
}
// more listed gods, more reward to the top gods, highest reward 600 egst
function reward_top_gods () private returns (bool){ // public when testing
uint count_listed_gods = listed_gods.length;
uint last_god_index;
if (count_listed_gods > 100) {
last_god_index = sub(count_listed_gods, 100);
} else {
last_god_index = 0;
}
uint reward_egst = 0;
uint base_reward = 6 ether;
if (count_rounds == 6){
base_reward = mul(base_reward, 6);
}
for (uint i = last_god_index; i < count_listed_gods; i++) {
reward_egst = mul(base_reward, sub(add(i, 1), last_god_index));
egst_from_contract(gods_address[listed_gods[i]], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
if (gods[gods_address[listed_gods[i]]].blessing_player_id > 0){
egst_from_contract(gods_address[gods[gods_address[listed_gods[i]]].blessing_player_id], reward_egst, 2);// 2 top_gods_reward
_totalSupply = add(_totalSupply, reward_egst);
}
}
return true;
}
function compare_bid_eth () private view returns (uint, address) {
uint highest_bid = 0;
address highest_bidder = v_god; // if no one bid, v god host this event
for (uint j = 1; j <= listed_gods.length; j++){
if (gods[bidding_gods[j]].bid_eth > highest_bid){
highest_bid = gods[bidding_gods[j]].bid_eth;
highest_bidder = bidding_gods[j];
}
}
return (highest_bid, highest_bidder);
}
function check_event_completed () public view returns (bool){
// check min and max pray_event duration
if (add(pray_start_block, max_pray_duration) > block.number){
if (add(pray_start_block, min_pray_duration) < block.number){
for (uint i = 1; i <= 5; i++){
if(count_listed_winners[i] < max_winners[i]){
return false;
}
}
return true;
} else {
return false;
}
} else {
return true;
}
}
function pk (address attacker, address defender, bytes32 block_hash) public view returns (bool pk_result){// make it public, view only, other contract may use it
(uint attacker_sum_god_levels, uint attacker_sum_amulet_levels) = get_sum_levels_pk(attacker);
(uint defender_sum_god_levels, uint defender_sum_amulet_levels) = get_sum_levels_pk(defender);
pk_result = eth_gods_dice.pk(block_hash, attacker_sum_god_levels, attacker_sum_amulet_levels, defender_sum_god_levels, defender_sum_amulet_levels);
return pk_result;
}
function get_sum_levels_pk (address god_address) public view returns (uint sum_gods_level, uint sum_amulets_level){
sum_gods_level = gods[god_address].level;
sum_amulets_level = gods[god_address].pet_level; // add pet level to the sum
uint amulet_god_id;
uint amulet_god_level;
for (uint i = 1; i <= count_amulets; i++){
if (amulets[i].owner == god_address && amulets[i].start_selling_block == 0){
amulet_god_id = amulets[i].god_id;
amulet_god_level = gods[gods_address[amulet_god_id]].level;
sum_gods_level = add(sum_gods_level, amulet_god_level);
sum_amulets_level = add(sum_amulets_level, amulets[i].level);
}
}
return (sum_gods_level, sum_amulets_level);
}
//admin need this function
function get_listed_winners (uint prize) public view returns (address[]){
address [] memory temp_list = new address[] (count_listed_winners[prize]);
for (uint i = 0; i < count_listed_winners[prize]; i++){
temp_list[i] = listed_winners[prize][add(i,1)];
}
return temp_list;
}
function query_pray () public view returns (uint, uint, uint, address, address, uint, bool){
(uint highest_bid, address highest_bidder) = compare_bid_eth();
return (highest_bid,
pray_egses,
pray_egst,
pray_host_god,
highest_bidder,
count_rounds,
pray_reward_top100);
}
// end of pray
// start of egses
function egses_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
if (reason == 1) {
require (pray_egses > tokens);
pray_egses = sub(pray_egses, tokens);
}
egses_balances[to] = add(egses_balances[to], tokens);
create_change_log(1, reason, tokens, egses_balances[to], contract_address, to);
return true;
}
function egses_withdraw () public returns (uint tokens){
tokens = egses_balances[msg.sender];
require (tokens > 0 && contract_address.balance >= tokens && reEntrancyMutex == false);
reEntrancyMutex = true; // if met problem, it will use up gas from msg.sender and roll back to false
egses_balances[msg.sender] = 0;
msg.sender.transfer(tokens);
reEntrancyMutex = false;
emit withdraw_egses(msg.sender, tokens);
create_change_log(1, 5, tokens, 0, contract_address, msg.sender); // 5 withdraw egses
return tokens;
}
event withdraw_egses (address receiver, uint tokens);
// end of egses
// start of erc20 for egst
function totalSupply () public view returns (uint){
return _totalSupply;
}
function balanceOf (address tokenOwner) public view returns (uint){
return balances[tokenOwner]; // will return 0 if doesn't exist
}
function allowance (address tokenOwner, address spender) public view returns (uint) {
return allowed[tokenOwner][spender];
}
function transfer (address to, uint tokens) public returns (bool success){
require (balances[msg.sender] >= tokens);
balances[msg.sender] = sub(balances[msg.sender], tokens);
balances[to] = add(balances[to], tokens);
emit Transfer(msg.sender, to, tokens);
create_change_log(2, 9, tokens, balances[to], msg.sender, to);
return true;
}
event Transfer (address indexed from, address indexed to, uint tokens);
function approve (address spender, uint tokens) public returns (bool success) {
// if allowed amount used and owner tries to reset allowed amount within a short time,
// the allowed account might be cheating the owner
require (balances[msg.sender] >= tokens);
if (tokens > 0){
require (add(gods[msg.sender].allowed_block, allowed_use_CD) < block.number);
}
allowed[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
event Approval (address indexed tokenOwner, address indexed spender, uint tokens);
function transferFrom (address from, address to, uint tokens) public returns (bool success) {
require (balances[from] >= tokens);
allowed[from][msg.sender] = sub(allowed[from][msg.sender], tokens);
balances[from] = sub(balances[from], tokens);
balances[to] = add(balances[to], tokens);
gods[from].allowed_block = block.number;
emit Transfer(from, to, tokens);
create_change_log(2, 10, tokens, balances[to], from, to);
return true;
}
// end of erc20 for egst
// egst
function egst_from_contract (address to, uint tokens, uint reason) private returns (bool) { // public when testing
balances[to] = add(balances[to], tokens);
create_change_log(2, reason, tokens, balances[to], contract_address, to);
return true;
}
function egst_to_contract (address from, uint tokens, uint reason) private returns (bool) { // public when testing
require (balances[from] >= tokens);
balances[from] = sub(balances[from], tokens);
emit spend_egst(from, tokens, reason);
create_change_log(2, reason, tokens, balances[from], from, contract_address);
return true;
}
event spend_egst (address from, uint tokens, uint reason);
function create_token_order (uint unit_price, uint egst_amount) public returns (uint) {
require(unit_price >= min_unit_price && unit_price <= max_unit_price
&& balances[msg.sender] >= egst_amount
&& egst_amount <= max_egst_amount
&& egst_amount >= min_egst_amount);
count_token_orders = add(count_token_orders, 1);
egst_to_contract(msg.sender, egst_amount, 3); // 3 create_token_order
token_orders[count_token_orders].start_selling_block = block.number;
token_orders[count_token_orders].seller = msg.sender;
token_orders[count_token_orders].unit_price = unit_price;
token_orders[count_token_orders].egst_amount = egst_amount;
gods[msg.sender].count_token_orders++;
update_first_active_token_order(msg.sender);
return gods[msg.sender].count_token_orders++;
}
function withdraw_token_order (uint order_id) public returns (bool) {
require (msg.sender == token_orders[order_id].seller
&& token_orders[order_id].egst_amount > 0);
uint egst_amount = token_orders[order_id].egst_amount;
token_orders[order_id].start_selling_block = 0;
token_orders[order_id].egst_amount = 0;
// balances[msg.sender] = add(balances[msg.sender], tokens);
egst_from_contract(msg.sender, egst_amount, 4); // 4 withdraw token_order
gods[msg.sender].count_token_orders = sub(gods[msg.sender].count_token_orders, 1);
update_first_active_token_order(msg.sender);
emit WithdrawTokenOrder(msg.sender, order_id);
return true;
}
event WithdrawTokenOrder (address seller, uint order_id);
function buy_token (uint order_id, uint egst_amount) public payable returns (uint) {
require(order_id >= first_active_token_order
&& order_id <= count_token_orders
&& egst_amount <= token_orders[order_id].egst_amount
&& token_orders[order_id].egst_amount > 0);
// unit_price 100 means 1 egst = 0.001 ether
uint eth_cost = div(mul(token_orders[order_id].unit_price, egst_amount), 100000);
require(msg.value >= eth_cost && msg.value < add(eth_cost, max_extra_eth) );
token_orders[order_id].egst_amount = sub(token_orders[order_id].egst_amount, egst_amount);
egst_from_contract(msg.sender, egst_amount, token_orders[order_id].unit_price); // uint price (> 10) will be recorded as reason in change log and translated by front end as buy token & unit_price
// balances[msg.sender] = add(balances[msg.sender], egst_amount);
address seller = token_orders[order_id].seller;
egses_from_contract(seller, eth_cost, 7); // 7 sell egst
if (token_orders[order_id].egst_amount <= 0){
token_orders[order_id].start_selling_block = 0;
gods[seller].count_token_orders = sub(gods[seller].count_token_orders, 1);
update_first_active_token_order(seller);
}
emit BuyToken(msg.sender, order_id, egst_amount);
return token_orders[order_id].egst_amount;
}
event BuyToken (address buyer, uint order_id, uint egst_amount);
function update_first_active_token_order (address god_address) private returns (uint, uint){ // public when testing
if (count_token_orders > 0
&& first_active_token_order == 0){
first_active_token_order = 1;
} else {
for (uint i = first_active_token_order; i <= count_token_orders; i++) {
if (add(token_orders[i].start_selling_block, order_duration) > block.number){
// find the first active order and compare with the currect index
if (i > first_active_token_order){
first_active_token_order = i;
}
break;
}
}
}
if (gods[god_address].count_token_orders > 0
&& gods[god_address].first_active_token_order == 0){
gods[god_address].first_active_token_order = 1; // may not be 1, but it will correct next time
} else {
for (uint j = gods[god_address].first_active_token_order; j < count_token_orders; j++){
if (token_orders[j].seller == god_address
&& token_orders[j].start_selling_block > 0){ // don't check duration, show it to selling, even if expired
// find the first active order and compare with the currect index
if(j > gods[god_address].first_active_token_order){
gods[god_address].first_active_token_order = j;
}
break;
}
}
}
return (first_active_token_order, gods[msg.sender].first_active_token_order);
}
function get_token_order (uint order_id) public view returns(uint, address, uint, uint){
require(order_id >= 1 && order_id <= count_token_orders);
return(token_orders[order_id].start_selling_block,
token_orders[order_id].seller,
token_orders[order_id].unit_price,
token_orders[order_id].egst_amount);
}
// return total orders and lowest price to browser, browser query each active order and show at most three orders of lowest price
function get_token_orders () public view returns(uint, uint, uint, uint, uint) {
uint lowest_price = max_unit_price;
for (uint i = first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].unit_price < lowest_price
&& token_orders[i].egst_amount > 0
&& add(token_orders[i].start_selling_block, order_duration) > block.number){
lowest_price = token_orders[i].unit_price;
}
}
return (count_token_orders, first_active_token_order, order_duration, max_unit_price, lowest_price);
}
function get_my_token_orders () public view returns(uint []) {
uint my_count_token_orders = gods[msg.sender].count_token_orders;
uint [] memory temp_list = new uint[] (my_count_token_orders);
uint count_list_elements = 0;
for (uint i = gods[msg.sender].first_active_token_order; i <= count_token_orders; i++){
if (token_orders[i].seller == msg.sender
&& token_orders[i].start_selling_block > 0){
temp_list[count_list_elements] = i;
count_list_elements++;
if (count_list_elements >= my_count_token_orders){
break;
}
}
}
return temp_list;
}
// end of egst
// logs
function get_winner_log (uint pray_round, uint log_id) public view returns (uint, bytes32, address, address, uint, bool){
require(log_id >= 1 && log_id <= count_rounds_winner_logs[pray_round]);
winner_log storage this_winner_log = winner_logs[pray_round][log_id];
return (this_winner_log.god_block_number,
this_winner_log.block_hash,
this_winner_log.prayer,
this_winner_log.previous_winner,
this_winner_log.prize,
this_winner_log.pk_result);
}
function get_count_rounds_winner_logs (uint pray_round) public view returns (uint){
return count_rounds_winner_logs[pray_round];
}
// egses change reasons:
// 1 pray_reward, 2 god_reward for being invited, 3 inviter_reward,
// 4 admin_deposit to reward_pool, 5 withdraw egses
// 6 sell amulet, 7 sell egst, 8 withdraw bid
// egst_change reasons:
// 1 pray_reward, 2 top_gods_reward,
// 3 create_token_order, 4 withdraw token_order, 5 buy token (> 10),
// 6 upgrade pet, 7 upgrade amulet, 8 admin_reward,
// 9 transfer, 10 transferFrom(owner & receiver)
function create_change_log (uint asset_type, uint reason, uint change_amount, uint after_amount, address _from, address _to) private returns (uint) {
count_rounds_change_logs[count_rounds] = add(count_rounds_change_logs[count_rounds], 1);
uint log_id = count_rounds_change_logs[count_rounds];
change_logs[count_rounds][log_id].block_number = block.number;
change_logs[count_rounds][log_id].asset_type = asset_type;
change_logs[count_rounds][log_id].reason = reason;
change_logs[count_rounds][log_id].change_amount = change_amount;
change_logs[count_rounds][log_id].after_amount = after_amount;
change_logs[count_rounds][log_id]._from = _from;
change_logs[count_rounds][log_id]._to = _to;
return log_id;
}
function get_change_log (uint pray_round, uint log_id) public view returns (uint, uint, uint, uint, uint, address, address){ // public
change_log storage this_log = change_logs[pray_round][log_id];
return (this_log.block_number,
this_log.asset_type,
this_log.reason, // reason > 10 is buy_token unit_price
this_log.change_amount,
this_log.after_amount, // god's after amount. transfer or transferFrom doesn't record log
this_log._from,
this_log._to);
}
function get_count_rounds_change_logs (uint pray_round) public view returns(uint){
return count_rounds_change_logs[pray_round];
}
// end of logs
// common functions
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 EthGodsDice {
// ethgods
EthGods private eth_gods;
address private ethgods_contract_address = address(0);// publish ethgods first, then use that address in constructor
function set_eth_gods_contract_address(address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
uint private block_hash_duration;
function update_admin () public returns (bool){
(,,address new_admin, uint new_block_hash_duration,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
block_hash_duration = new_block_hash_duration;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
}
function finalize () public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
function () public payable {
revert(); // if received eth for no reason, reject
}
// end of constructor and destructor
function tell_fortune_blockhash () public view returns (bytes32){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return block_hash;
}
function tell_fortune () public view returns (uint[]){
bytes32 block_hash;
(uint god_block_number,,,,,,) = eth_gods.get_god_info(msg.sender);
if (god_block_number > 0
&& add(god_block_number, 1) < block.number
&& add(god_block_number, block_hash_duration) > block.number) {
block_hash = keccak256(abi.encodePacked(blockhash(god_block_number + 1)));
} else {
block_hash = keccak256(abi.encodePacked(blockhash(block.number - 1)));
}
return throw_dice (block_hash);
}
function throw_dice (bytes32 block_hash) public pure returns (uint[]) {// 0 for prize, 1-6 for 6 numbers should be pure
uint[] memory dice_numbers = new uint[](7);
//uint [7] memory dice_numbers;
uint hash_number;
uint[] memory count_dice_numbers = new uint[](7);
//uint [7] memory count_dice_numbers; // how many times for each dice number
uint i; // for loop
for (i = 1; i <= 6; i++) {
hash_number = uint(block_hash[i]);
// hash_number=1;
if (hash_number >= 214) { // 214
dice_numbers[i] = 6;
} else if (hash_number >= 172) { // 172
dice_numbers[i] = 5;
} else if (hash_number >= 129) { // 129
dice_numbers[i] = 4;
} else if (hash_number >= 86) { // 86
dice_numbers[i] = 3;
} else if (hash_number >= 43) { // 43
dice_numbers[i] = 2;
} else {
dice_numbers[i] = 1;
}
count_dice_numbers[dice_numbers[i]] ++;
}
bool won_super_prize = false;
uint count_super_eth = 0;
for (i = 1; i <= 6; i++) {
if (count_dice_numbers[i] >= 5) {
dice_numbers[0] = 1; //champion_eth
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 4) {
dice_numbers[0] = 3; // super_egst
won_super_prize = true;
break;
}else if (count_dice_numbers[i] == 1) {
count_super_eth ++;
if (count_super_eth == 6) {
dice_numbers[0] = 2; // super_eth
won_super_prize = true;
}
}
}
if (won_super_prize == false) {
if (count_dice_numbers[6] >= 2){
dice_numbers[0] = 4; // primary_egst
} else if (count_dice_numbers[6] == 1){
dice_numbers[0] = 5; // lucky_star
}
}
return dice_numbers;
}
function pk (bytes32 block_hash, uint attacker_sum_god_levels, uint attacker_sum_amulet_levels, uint defender_sum_god_levels, uint defender_sum_amulet_levels) public pure returns (bool){
uint god_win_chance;
attacker_sum_god_levels = add(attacker_sum_god_levels, 10);
if (attacker_sum_god_levels < defender_sum_god_levels){
god_win_chance = 0;
} else {
god_win_chance = sub(attacker_sum_god_levels, defender_sum_god_levels);
if (god_win_chance > 20) {
god_win_chance = 100;
} else { // equal level, 50% chance to win
god_win_chance = mul(god_win_chance, 5);
}
}
uint amulet_win_chance;
attacker_sum_amulet_levels = add(attacker_sum_amulet_levels, 10);
if (attacker_sum_amulet_levels < defender_sum_amulet_levels){
amulet_win_chance = 0;
} else {
amulet_win_chance = sub(attacker_sum_amulet_levels, defender_sum_amulet_levels);
if (amulet_win_chance > 20) {
amulet_win_chance = 100;
} else { // equal level, 50% chance to win
amulet_win_chance = mul(amulet_win_chance, 5);
}
}
uint attacker_win_chance = div(add(god_win_chance, amulet_win_chance), 2);
if (attacker_win_chance >= div(mul(uint(block_hash[3]),2),5)){
return true;
} else {
return false;
}
}
// common functions
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 EthGodsName {
// EthGods
EthGods private eth_gods;
address private ethgods_contract_address;
function set_eth_gods_contract_address (address eth_gods_contract_address) public returns (bool){
require (msg.sender == admin);
ethgods_contract_address = eth_gods_contract_address;
eth_gods = EthGods(ethgods_contract_address);
return true;
}
address private admin; // manually update to ethgods' admin
function update_admin () public returns (bool){
(,,address new_admin,,,,) = eth_gods.query_contract();
require (msg.sender == new_admin);
admin = new_admin;
return true;
}
//contract information & administration
bool private contract_created; // in case constructor logic change in the future
address private contract_address; //shown at the top of the home page
string private invalid_chars = "\\\"";
bytes private invalid_bytes = bytes(invalid_chars);
function set_invalid_chars (string new_invalid_chars) public returns (bool) {
require(msg.sender == admin);
invalid_chars = new_invalid_chars;
invalid_bytes = bytes(invalid_chars);
return true;
}
uint private valid_length = 16;
function set_valid_length (uint new_valid_length) public returns (bool) {
require(msg.sender == admin);
valid_length = new_valid_length;
return true;
}
struct god_name {
string god_name;
uint block_number;
uint block_duration;
}
mapping (address => god_name) private gods_name;
// start of constructor and destructor
constructor () public {
require (contract_created == false);
contract_created = true;
contract_address = address(this);
admin = msg.sender;
address v_god = 0xfB6916095ca1df60bB79Ce92cE3Ea74c37c5d359;
gods_name[v_god].god_name = "V";
}
function () public payable {
revert(); // if received eth for no reason, reject
}
function finalize() public {
require (msg.sender == admin);
selfdestruct(msg.sender);
}
// end of constructor and destructor
function set_god_name (string new_name) public returns (bool){
address god_address = msg.sender;
require (add(gods_name[god_address].block_number, gods_name[god_address].block_duration) < block.number );
bytes memory bs = bytes(new_name);
require (bs.length <= valid_length);
for (uint i = 0; i < bs.length; i++){
for (uint j = 0; j < invalid_bytes.length; j++) {
if (bs[i] == invalid_bytes[j]){
return false;
}
}
}
gods_name[god_address].god_name = new_name;
emit set_name(god_address, new_name);
return true;
}
event set_name (address indexed god_address, string new_name);
function get_god_name (address god_address) public view returns (string) {
return gods_name[god_address].god_name;
}
function block_god_name (address god_address, uint block_duration) public {
require (msg.sender == admin);
gods_name[god_address].god_name = "Unkown";
gods_name[god_address].block_number = block.number;
gods_name[god_address].block_duration = block_duration;
}
function add (uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
} | start of erc20 for egst | function totalSupply () public view returns (uint){
return _totalSupply;
}
| 997,297 | [
1,
1937,
434,
6445,
71,
3462,
364,
9130,
334,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
2078,
3088,
1283,
1832,
1071,
1476,
1135,
261,
11890,
15329,
203,
3639,
327,
389,
4963,
3088,
1283,
31,
203,
27699,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
/**
* Audited by VZ Chains (vzchains.com)
* HashRushICO.sol creates the client's token for crowdsale and allows for subsequent token sales and minting of tokens
* Crowdsale contracts edited from original contract code at https://www.ethereum.org/crowdsale#crowdfund-your-idea
* Additional crowdsale contracts, functions, libraries from OpenZeppelin
* at https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token
* Token contract edited from original contract code at https://www.ethereum.org/token
* ERC20 interface and certain token functions adapted from https://github.com/ConsenSys/Tokens
**/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 {
//Sets events and functions for ERC20 token
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
function totalSupply() public view returns (uint256);
function balanceOf(address _owner) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
function allowance(address _owner, address _spender) public view returns (uint256);
function approve(address _spender, uint256 _value) public returns (bool);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool);
}
/**
* @title Owned
* @dev The Owned contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Owned {
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) onlyOwner public {
owner = newOwner;
}
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
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;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
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 sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
uint256 c = a - b;
return c;
}
}
contract HashRush is ERC20, Owned {
// Applies SafeMath library to uint256 operations
using SafeMath for uint256;
// Public variables
string public name;
string public symbol;
uint256 public decimals;
// Variables
uint256 totalSupply_;
uint256 multiplier;
// Arrays for balances & allowance
mapping (address => uint256) balance;
mapping (address => mapping (address => uint256)) allowed;
// Modifier to prevent short address attack
modifier onlyPayloadSize(uint size) {
if(msg.data.length < size.add(4)) revert();
_;
}
constructor(string tokenName, string tokenSymbol, uint8 decimalUnits, uint256 decimalMultiplier) public {
name = tokenName;
symbol = tokenSymbol;
decimals = decimalUnits;
multiplier = decimalMultiplier;
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @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 Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _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 balance[_owner];
}
/**
* @dev Transfer token to a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) onlyPayloadSize(2 * 32) public returns (bool) {
require(_to != address(0));
require(_value <= balance[msg.sender]);
if ((balance[msg.sender] >= _value)
&& (balance[_to].add(_value) > balance[_to])
) {
balance[msg.sender] = balance[msg.sender].sub(_value);
balance[_to] = balance[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3 * 32) public returns (bool) {
require(_to != address(0));
require(_value <= balance[_from]);
require(_value <= allowed[_from][msg.sender]);
if ((balance[_from] >= _value) && (allowed[_from][msg.sender] >= _value) && (balance[_to].add(_value) > balance[_to])) {
balance[_to] = balance[_to].add(_value);
balance[_from] = balance[_from].sub(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
}
contract HashRushICO is Owned, HashRush {
// Applies SafeMath library to uint256 operations
using SafeMath for uint256;
// Public Variables
address public multiSigWallet;
uint256 public amountRaised;
uint256 public startTime;
uint256 public stopTime;
uint256 public fixedTotalSupply;
uint256 public price;
uint256 public minimumInvestment;
uint256 public crowdsaleTarget;
// Variables
bool crowdsaleClosed = true;
string tokenName = "HashRush";
string tokenSymbol = "RUSH";
uint256 multiplier = 100000000;
uint8 decimalUnits = 8;
// Initializes the token
constructor()
HashRush(tokenName, tokenSymbol, decimalUnits, multiplier) public {
multiSigWallet = msg.sender;
fixedTotalSupply = 70000000;
fixedTotalSupply = fixedTotalSupply.mul(multiplier);
}
/**
* @dev Fallback function creates tokens and sends to investor when crowdsale is open
*/
function () public payable {
require(!crowdsaleClosed
&& (now < stopTime)
&& (msg.value >= minimumInvestment)
&& (totalSupply_.add(msg.value.mul(price).mul(multiplier).div(1 ether)) <= fixedTotalSupply)
&& (amountRaised.add(msg.value.div(1 ether)) <= crowdsaleTarget)
);
address recipient = msg.sender;
amountRaised = amountRaised.add(msg.value.div(1 ether));
uint256 tokens = msg.value.mul(price).mul(multiplier).div(1 ether);
totalSupply_ = totalSupply_.add(tokens);
}
/**
* @dev Function to mint tokens
* @param target 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 mintToken(address target, uint256 amount) onlyOwner public returns (bool) {
require(amount > 0);
require(totalSupply_.add(amount) <= fixedTotalSupply);
uint256 addTokens = amount;
balance[target] = balance[target].add(addTokens);
totalSupply_ = totalSupply_.add(addTokens);
emit Transfer(0, target, addTokens);
return true;
}
/**
* @dev Function to set token price
* @param newPriceperEther New price.
* @return A boolean that indicates if the operation was successful.
*/
function setPrice(uint256 newPriceperEther) onlyOwner public returns (uint256) {
require(newPriceperEther > 0);
price = newPriceperEther;
return price;
}
/**
* @dev Function to set the multisig wallet for a crowdsale
* @param wallet Wallet address.
* @return A boolean that indicates if the operation was successful.
*/
function setMultiSigWallet(address wallet) onlyOwner public returns (bool) {
multiSigWallet = wallet;
return true;
}
/**
* @dev Function to set the minimum investment to participate in crowdsale
* @param minimum minimum amount in wei.
* @return A boolean that indicates if the operation was successful.
*/
function setMinimumInvestment(uint256 minimum) onlyOwner public returns (bool) {
minimumInvestment = minimum;
return true;
}
/**
* @dev Function to set the crowdsale target
* @param target Target amount in ETH.
* @return A boolean that indicates if the operation was successful.
*/
function setCrowdsaleTarget(uint256 target) onlyOwner public returns (bool) {
crowdsaleTarget = target;
return true;
}
/**
* @dev Function to start the crowdsale specifying startTime and stopTime
* @param saleStart Sale start timestamp.
* @param saleStop Sale stop timestamo.
* @param salePrice Token price per ether.
* @param setBeneficiary Beneficiary address.
* @param minInvestment Minimum investment to participate in crowdsale (wei).
* @param saleTarget Crowdsale target in ETH
* @return A boolean that indicates if the operation was successful.
*/
function startSale(uint256 saleStart, uint256 saleStop, uint256 salePrice, address setBeneficiary, uint256 minInvestment, uint256 saleTarget) onlyOwner public returns (bool) {
require(saleStop > now);
startTime = saleStart;
stopTime = saleStop;
amountRaised = 0;
crowdsaleClosed = false;
setPrice(salePrice);
setMultiSigWallet(setBeneficiary);
setMinimumInvestment(minInvestment);
setCrowdsaleTarget(saleTarget);
return true;
}
/**
* @dev Function that allows owner to stop the crowdsale immediately
* @return A boolean that indicates if the operation was successful.
*/
function stopSale() onlyOwner public returns (bool) {
stopTime = now;
crowdsaleClosed = true;
return true;
}
} | * @dev Function to set the multisig wallet for a crowdsale @param wallet Wallet address. @return A boolean that indicates if the operation was successful./ | function setMultiSigWallet(address wallet) onlyOwner public returns (bool) {
multiSigWallet = wallet;
return true;
}
| 14,075,569 | [
1,
2083,
358,
444,
326,
22945,
360,
9230,
364,
279,
276,
492,
2377,
5349,
225,
9230,
20126,
1758,
18,
327,
432,
1250,
716,
8527,
309,
326,
1674,
1703,
6873,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
5002,
8267,
16936,
12,
2867,
9230,
13,
1338,
5541,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
3309,
8267,
16936,
273,
9230,
31,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.0;
import "./multiOwnable.sol";
import "./fkxToken.sol";
contract ethBridge is Multiownable {
FKX private token;
mapping(address => uint256) public tokensSent;
mapping(address => uint256) public tokensRecieved;
mapping(address => uint256) public tokensRecievedButNotSent;
address public tokenAddress;
constructor (address _token) public {
tokenAddress = _token;
token = FKX(_token);
}
bool transferStatus;
bool avoidReentrancy = false;
function sendTokens(uint256 amount) public {
require(msg.sender != address(0), "Zero account");
require(amount > 0,"Amount of tokens should be more then 0");
require(token.balanceOf(msg.sender) >= amount,"Not enough balance");
transferStatus = token.transferFrom(msg.sender, address(this), amount);
if (transferStatus == true) {
tokensRecieved[msg.sender] += amount;
}
}
function writeTransaction(address user, uint256 amount) public onlyAllOwners {
require(user != address(0), "Zero account");
require(amount > 0,"Amount of tokens should be more then 0");
require(!avoidReentrancy);
avoidReentrancy = true;
tokensRecievedButNotSent[user] += amount;
avoidReentrancy = false;
}
function recieveTokens(uint256[] memory commissions) public payable {
if (tokensRecievedButNotSent[msg.sender] != 0) {
require(commissions.length == owners.length, "The number of commissions and owners does not match");
uint256 sum;
for(uint i = 0; i < commissions.length; i++) {
sum += commissions[i];
}
require(msg.value >= sum, "Not enough BNB (The amount of BNB is less than the amount of commissions.)");
require(msg.value >= owners.length * 150000 * 10**9, "Not enough BNB (The amount of BNB is less than the internal commission.)");
for (uint i = 0; i < owners.length; i++) {
address payable owner = payable(owners[i]);
uint256 commission = commissions[i];
owner.transfer(commission);
}
uint256 amountToSent;
amountToSent = tokensRecievedButNotSent[msg.sender] - tokensSent[msg.sender];
transferStatus = token.transfer(msg.sender, amountToSent);
if (transferStatus == true) {
tokensSent[msg.sender] += amountToSent;
}
}
}
function withdrawTokens(uint256 amount, address reciever) public onlyAllOwners {
require(amount > 0,"Amount of tokens should be more then 0");
require(reciever != address(0), "Zero account");
require(token.balanceOf(address(this)) >= amount,"Not enough balance");
token.transfer(reciever, amount);
}
function withdrawEther(uint256 amount, address payable reciever) public onlyAllOwners {
require(amount > 0,"Amount of tokens should be more then 0");
require(reciever != address(0), "Zero account");
require(address(this).balance >= amount,"Not enough balance");
reciever.transfer(amount);
}
}
// SPDX-License-Identifier: MIT
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;
}
}
//
/**
* @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 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) {
// 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 Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
//
/**
* @title FKX
*/
contract FKX is ERC20 {
constructor() public ERC20("Knoxstertoken", "FKX") {
_mint(msg.sender, 150000000 ether); // Mint fixed supply of 150 Million FKX
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
contract Multiownable {
// VARIABLES
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
// Reverse lookup tables for owners and allOperations
mapping(address => uint) public ownersIndices; // Starts from 1
mapping(bytes32 => uint) public allOperationsIndicies;
// Owners voting mask per operations
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
// EVENTS
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
// ACCESSORS
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
// MODIFIERS
/**
* @dev Allows to perform method by any of the owners
*/
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after many owners call it with the same arguments
*/
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after all owners call it with the same arguments
*/
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
/**
* @dev Allows to perform method only after some owners call it with the same arguments
*/
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
// CONSTRUCTOR
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
// INTERNAL METHODS
/**
* @dev onlyManyOwners modifier helper
*/
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
// If enough owners confirmed the same operation
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
/**
* @dev Used to delete cancelled or performed operation
* @param operation defines which operation to delete
*/
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
if (index < allOperations.length - 1) { // Not last
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
//allOperations.length-1
allOperations.pop();
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
}
// PUBLIC METHODS
/**
* @dev Allows owners to change their mind by cacnelling votesMaskByOperation operations
* @param operation defines which operation to delete
*/
function cancelPending(bytes32 operation) public onlyAnyOwner {
uint ownerIndex = ownersIndices[msg.sender] - 1;
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) != 0, "cancelPending: operation not found for this user");
votesMaskByOperation[operation] &= ~(2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] - 1;
votesCountByOperation[operation] = operationVotesCount;
emit OperationDownvoted(operation, operationVotesCount, owners.length, msg.sender);
if (operationVotesCount == 0) {
deleteOperation(operation);
emit OperationCancelled(operation, msg.sender);
}
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
*/
function transferOwnership(address[] memory newOwners) public {
transferOwnershipWithHowMany(newOwners, newOwners.length);
}
/**
* @dev Allows owners to change ownership
* @param newOwners defines array of addresses of new owners
* @param newHowManyOwnersDecide defines how many owners can decide
*/
function transferOwnershipWithHowMany(address[] memory newOwners, uint256 newHowManyOwnersDecide) public onlyManyOwners {
require(newOwners.length > 0, "transferOwnershipWithHowMany: owners array is empty");
require(newOwners.length <= 256, "transferOwnershipWithHowMany: owners count is greater then 256");
require(newHowManyOwnersDecide > 0, "transferOwnershipWithHowMany: newHowManyOwnersDecide equal to 0");
require(newHowManyOwnersDecide <= newOwners.length, "transferOwnershipWithHowMany: newHowManyOwnersDecide exceeds the number of owners");
// Reset owners reverse lookup table
for (uint j = 0; j < owners.length; j++) {
delete ownersIndices[owners[j]];
}
for (uint i = 0; i < newOwners.length; i++) {
require(newOwners[i] != address(0), "transferOwnershipWithHowMany: owners array contains zero");
require(ownersIndices[newOwners[i]] == 0, "transferOwnershipWithHowMany: owners array contains duplicates");
ownersIndices[newOwners[i]] = i + 1;
}
emit OwnershipTransferred(owners, howManyOwnersDecide, newOwners, newHowManyOwnersDecide);
owners = newOwners;
howManyOwnersDecide = newHowManyOwnersDecide;
// allOperations.length = 0;
allOperations.push();
ownersGeneration++;
}
}
| VARIABLES Reverse lookup tables for owners and allOperations Owners voting mask per operations EVENTS ACCESSORS | contract Multiownable {
uint256 public ownersGeneration;
uint256 public howManyOwnersDecide;
address[] public owners;
bytes32[] public allOperations;
address internal insideCallSender;
uint256 internal insideCallCount;
mapping(bytes32 => uint) public allOperationsIndicies;
mapping(bytes32 => uint256) public votesMaskByOperation;
mapping(bytes32 => uint256) public votesCountByOperation;
event OwnershipTransferred(address[] previousOwners, uint howManyOwnersDecide, address[] newOwners, uint newHowManyOwnersDecide);
event OperationCreated(bytes32 operation, uint howMany, uint ownersCount, address proposer);
event OperationUpvoted(bytes32 operation, uint votes, uint howMany, uint ownersCount, address upvoter);
event OperationPerformed(bytes32 operation, uint howMany, uint ownersCount, address performer);
event OperationDownvoted(bytes32 operation, uint votes, uint ownersCount, address downvoter);
event OperationCancelled(bytes32 operation, address lastCanceller);
pragma solidity ^0.6.0;
function isOwner(address wallet) public view returns(bool) {
return ownersIndices[wallet] > 0;
}
function ownersCount() public view returns(uint) {
return owners.length;
}
function allOperationsCount() public view returns(uint) {
return allOperations.length;
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAnyOwner {
if (checkHowManyOwners(1)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = 1;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyManyOwners {
if (checkHowManyOwners(howManyOwnersDecide)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howManyOwnersDecide;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlyAllOwners {
if (checkHowManyOwners(owners.length)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = owners.length;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
modifier onlySomeOwners(uint howMany) {
require(howMany > 0, "onlySomeOwners: howMany argument is zero");
require(howMany <= owners.length, "onlySomeOwners: howMany argument exceeds the number of owners");
if (checkHowManyOwners(howMany)) {
bool update = (insideCallSender == address(0));
if (update) {
insideCallSender = msg.sender;
insideCallCount = howMany;
}
_;
if (update) {
insideCallSender = address(0);
insideCallCount = 0;
}
}
}
constructor() public {
owners.push(msg.sender);
ownersIndices[msg.sender] = 1;
howManyOwnersDecide = 1;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function checkHowManyOwners(uint howMany) internal returns(bool) {
if (insideCallSender == msg.sender) {
require(howMany <= insideCallCount, "checkHowManyOwners: nested owners modifier check require more owners");
return true;
}
uint ownerIndex = ownersIndices[msg.sender] - 1;
require(ownerIndex < owners.length, "checkHowManyOwners: msg.sender is not an owner");
bytes32 operation = keccak256(abi.encodePacked(msg.data, ownersGeneration));
require((votesMaskByOperation[operation] & (2 ** ownerIndex)) == 0, "checkHowManyOwners: owner already voted for the operation");
votesMaskByOperation[operation] |= (2 ** ownerIndex);
uint operationVotesCount = votesCountByOperation[operation] + 1;
votesCountByOperation[operation] = operationVotesCount;
if (operationVotesCount == 1) {
allOperationsIndicies[operation] = allOperations.length;
allOperations.push(operation);
emit OperationCreated(operation, howMany, owners.length, msg.sender);
}
emit OperationUpvoted(operation, operationVotesCount, howMany, owners.length, msg.sender);
if (votesCountByOperation[operation] == howMany) {
deleteOperation(operation);
emit OperationPerformed(operation, howMany, owners.length, msg.sender);
return true;
}
return false;
}
function deleteOperation(bytes32 operation) internal {
uint index = allOperationsIndicies[operation];
allOperations[index] = allOperations[allOperations.length - 1];
allOperationsIndicies[allOperations[index]] = index;
}
delete votesMaskByOperation[operation];
delete votesCountByOperation[operation];
delete allOperationsIndicies[operation];
allOperations.pop();
}
| 14,902,206 | [
1,
16444,
55,
18469,
3689,
4606,
364,
25937,
471,
777,
9343,
14223,
9646,
331,
17128,
3066,
1534,
5295,
9964,
55,
13255,
14006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
5991,
995,
429,
288,
203,
203,
203,
565,
2254,
5034,
1071,
25937,
13842,
31,
203,
565,
2254,
5034,
1071,
3661,
5594,
5460,
414,
1799,
831,
31,
203,
565,
1758,
8526,
1071,
25937,
31,
203,
565,
1731,
1578,
8526,
1071,
777,
9343,
31,
203,
565,
1758,
2713,
4832,
1477,
12021,
31,
203,
565,
2254,
5034,
2713,
4832,
1477,
1380,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
13,
1071,
777,
9343,
3866,
335,
606,
31,
203,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
1071,
19588,
5796,
858,
2988,
31,
203,
565,
2874,
12,
3890,
1578,
516,
2254,
5034,
13,
1071,
19588,
1380,
858,
2988,
31,
203,
203,
203,
565,
871,
14223,
9646,
5310,
1429,
4193,
12,
2867,
8526,
2416,
5460,
414,
16,
2254,
3661,
5594,
5460,
414,
1799,
831,
16,
1758,
8526,
394,
5460,
414,
16,
2254,
394,
44,
543,
5594,
5460,
414,
1799,
831,
1769,
203,
565,
871,
4189,
6119,
12,
3890,
1578,
1674,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
450,
5607,
1769,
203,
565,
871,
4189,
1211,
90,
16474,
12,
3890,
1578,
1674,
16,
2254,
19588,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
731,
90,
20005,
1769,
203,
565,
871,
4189,
13889,
12,
3890,
1578,
1674,
16,
2254,
3661,
5594,
16,
2254,
25937,
1380,
16,
1758,
3073,
264,
1769,
203,
565,
871,
4189,
4164,
90,
16474,
12,
3890,
1578,
1674,
16,
2254,
19588,
16,
2254,
25937,
1380,
16,
225,
1758,
2588,
90,
20005,
1769,
203,
565,
871,
4189,
21890,
12,
2
] |
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TradingAction.sol";
import "./ActionGuards.sol";
import "./nTokenMintAction.sol";
import "./nTokenRedeemAction.sol";
import "../SettleAssetsExternal.sol";
import "../FreeCollateralExternal.sol";
import "../../math/SafeInt256.sol";
import "../../global/StorageLayoutV1.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/AccountContextHandler.sol";
import "../../../interfaces/notional/NotionalCallback.sol";
contract BatchAction is StorageLayoutV1, ActionGuards {
using BalanceHandler for BalanceState;
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using SafeInt256 for int256;
/// @notice Executes a batch of balance transfers including minting and redeeming nTokens.
/// @param account the account for the action
/// @param actions array of balance actions to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAction(address account, BalanceAction[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
// Return any settle amounts here to reduce the number of storage writes to balances
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
for (uint256 i = 0; i < actions.length; i++) {
BalanceAction calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions
/// @param account the account for the action
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:msg.sender auth:ERC1155
function batchBalanceAndTradeAction(address account, BalanceActionWithTrades[] calldata actions)
external
payable
nonReentrant
{
require(account == msg.sender || msg.sender == address(this), "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
_finalizeAccountContext(account, accountContext);
}
/// @notice Executes a batch of balance transfers and trading actions via an authorized callback contract. This
/// can be used as a "flash loan" facility for special contracts that migrate assets between protocols or perform
/// other actions on behalf of the user.
/// Contracts can borrow from Notional and receive a callback prior to an FC check, this can be useful if the contract
/// needs to perform a trade or repay a debt on a different protocol before depositing collateral. Since Notional's AMM
/// will never be as capital efficient or gas efficient as other flash loan facilities, this method requires whitelisting
/// and will mainly be used for contracts that make migrating assets a better user experience.
/// @param account the account that will take all the actions
/// @param actions array of balance actions with trades to take, must be sorted by currency id
/// @param callbackData arbitrary bytes to be passed backed to the caller in the callback
/// @dev emit:CashBalanceChange, emit:nTokenSupplyChange, emit:LendBorrowTrade, emit:AddRemoveLiquidity,
/// @dev emit:SettledCashDebt, emit:nTokenResidualPurchase, emit:ReserveFeeAccrued
/// @dev auth:authorizedCallbackContract
function batchBalanceAndTradeActionWithCallback(
address account,
BalanceActionWithTrades[] calldata actions,
bytes calldata callbackData
) external payable {
// NOTE: Re-entrancy is allowed for authorized callback functions.
require(authorizedCallbackContract[msg.sender], "Unauthorized");
requireValidAccount(account);
AccountContext memory accountContext = _batchBalanceAndTradeAction(account, actions);
accountContext.setAccountContext(account);
// Be sure to set the account context before initiating the callback, all stateful updates
// have been finalized at this point so we are safe to issue a callback. This callback may
// re-enter Notional safely to deposit or take other actions.
NotionalCallback(msg.sender).notionalCallback(msg.sender, account, callbackData);
if (accountContext.hasDebt != 0x00) {
// NOTE: this method may update the account context to turn off the hasDebt flag, this
// is ok because the worst case would be causing an extra free collateral check when it
// is not required. This check will be entered if the account hasDebt prior to the callback
// being triggered above, so it will happen regardless of what the callback function does.
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
function _batchBalanceAndTradeAction(
address account,
BalanceActionWithTrades[] calldata actions
) internal returns (AccountContext memory) {
AccountContext memory accountContext = _settleAccountIfRequired(account);
BalanceState memory balanceState;
// NOTE: loading the portfolio state must happen after settle account to get the
// correct portfolio, it will have changed if the account is settled.
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
for (uint256 i = 0; i < actions.length; i++) {
BalanceActionWithTrades calldata action = actions[i];
// msg.value will only be used when currency id == 1, referencing ETH. The requirement
// to sort actions by increasing id enforces that msg.value will only be used once.
if (i > 0) {
require(action.currencyId > actions[i - 1].currencyId, "Unsorted actions");
}
// Loads the currencyId into balance state
balanceState.loadBalanceState(account, action.currencyId, accountContext);
// Does not revert on invalid action types here, they also have no effect.
_executeDepositAction(
account,
balanceState,
action.actionType,
action.depositActionAmount
);
if (action.trades.length > 0) {
int256 netCash;
if (accountContext.isBitmapEnabled()) {
require(
accountContext.bitmapCurrencyId == action.currencyId,
"Invalid trades for account"
);
bool didIncurDebt;
(netCash, didIncurDebt) = TradingAction.executeTradesBitmapBatch(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
action.trades
);
if (didIncurDebt) {
accountContext.hasDebt = Constants.HAS_ASSET_DEBT | accountContext.hasDebt;
}
} else {
// NOTE: we return portfolio state here instead of setting it inside executeTradesArrayBatch
// because we want to only write to storage once after all trades are completed
(portfolioState, netCash) = TradingAction.executeTradesArrayBatch(
account,
action.currencyId,
portfolioState,
action.trades
);
}
// If the account owes cash after trading, ensure that it has enough
if (netCash < 0) _checkSufficientCash(balanceState, netCash.neg());
balanceState.netCashChange = balanceState.netCashChange.add(netCash);
}
_calculateWithdrawActionAndFinalize(
account,
accountContext,
balanceState,
action.withdrawAmountInternalPrecision,
action.withdrawEntireCashBalance,
action.redeemToUnderlying
);
}
// Update the portfolio state if bitmap is not enabled. If bitmap is already enabled
// then all the assets have already been updated in in storage.
if (!accountContext.isBitmapEnabled()) {
// NOTE: account context is updated in memory inside this method call.
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
// NOTE: free collateral and account context will be set outside of this method call.
return accountContext;
}
/// @dev Executes deposits
function _executeDepositAction(
address account,
BalanceState memory balanceState,
DepositActionType depositType,
uint256 depositActionAmount_
) private {
int256 depositActionAmount = SafeInt256.toInt(depositActionAmount_);
int256 assetInternalAmount;
require(depositActionAmount >= 0);
if (depositType == DepositActionType.None) {
return;
} else if (
depositType == DepositActionType.DepositAsset ||
depositType == DepositActionType.DepositAssetAndMintNToken
) {
// NOTE: this deposit will NOT revert on a failed transfer unless there is a
// transfer fee. The actual transfer will take effect later in balanceState.finalize
assetInternalAmount = balanceState.depositAssetToken(
account,
depositActionAmount,
false // no force transfer
);
} else if (
depositType == DepositActionType.DepositUnderlying ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken
) {
// NOTE: this deposit will revert on a failed transfer immediately
assetInternalAmount = balanceState.depositUnderlyingToken(account, depositActionAmount);
} else if (depositType == DepositActionType.ConvertCashToNToken) {
// _executeNTokenAction will check if the account has sufficient cash
assetInternalAmount = depositActionAmount;
}
_executeNTokenAction(
balanceState,
depositType,
depositActionAmount,
assetInternalAmount
);
}
/// @dev Executes nToken actions
function _executeNTokenAction(
BalanceState memory balanceState,
DepositActionType depositType,
int256 depositActionAmount,
int256 assetInternalAmount
) private {
// After deposits have occurred, check if we are minting nTokens
if (
depositType == DepositActionType.DepositAssetAndMintNToken ||
depositType == DepositActionType.DepositUnderlyingAndMintNToken ||
depositType == DepositActionType.ConvertCashToNToken
) {
// Will revert if trying to mint ntokens and results in a negative cash balance
_checkSufficientCash(balanceState, assetInternalAmount);
balanceState.netCashChange = balanceState.netCashChange.sub(assetInternalAmount);
// Converts a given amount of cash (denominated in internal precision) into nTokens
int256 tokensMinted = nTokenMintAction.nTokenMint(
balanceState.currencyId,
assetInternalAmount
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.add(
tokensMinted
);
} else if (depositType == DepositActionType.RedeemNToken) {
require(
// prettier-ignore
balanceState
.storedNTokenBalance
.add(balanceState.netNTokenTransfer) // transfers would not occur at this point
.add(balanceState.netNTokenSupplyChange) >= depositActionAmount,
"Insufficient token balance"
);
balanceState.netNTokenSupplyChange = balanceState.netNTokenSupplyChange.sub(
depositActionAmount
);
int256 assetCash = nTokenRedeemAction.nTokenRedeemViaBatch(
balanceState.currencyId,
depositActionAmount
);
balanceState.netCashChange = balanceState.netCashChange.add(assetCash);
}
}
/// @dev Calculations any withdraws and finalizes balances
function _calculateWithdrawActionAndFinalize(
address account,
AccountContext memory accountContext,
BalanceState memory balanceState,
uint256 withdrawAmountInternalPrecision,
bool withdrawEntireCashBalance,
bool redeemToUnderlying
) private {
int256 withdrawAmount = SafeInt256.toInt(withdrawAmountInternalPrecision);
require(withdrawAmount >= 0); // dev: withdraw action overflow
// NOTE: if withdrawEntireCashBalance is set it will override the withdrawAmountInternalPrecision input
if (withdrawEntireCashBalance) {
// This option is here so that accounts do not end up with dust after lending since we generally
// cannot calculate exact cash amounts from the liquidity curve.
withdrawAmount = balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision);
// If the account has a negative cash balance then cannot withdraw
if (withdrawAmount < 0) withdrawAmount = 0;
}
// prettier-ignore
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.sub(withdrawAmount);
balanceState.finalize(account, accountContext, redeemToUnderlying);
}
function _finalizeAccountContext(address account, AccountContext memory accountContext)
private
{
// At this point all balances, market states and portfolio states should be finalized. Just need to check free
// collateral if required.
accountContext.setAccountContext(account);
if (accountContext.hasDebt != 0x00) {
FreeCollateralExternal.checkFreeCollateralAndRevert(account);
}
}
/// @notice When lending, adding liquidity or minting nTokens the account must have a sufficient cash balance
/// to do so.
function _checkSufficientCash(BalanceState memory balanceState, int256 amountInternalPrecision)
private
pure
{
// The total cash position at this point is: storedCashBalance + netCashChange + netAssetTransferInternalPrecision
require(
amountInternalPrecision >= 0 &&
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= amountInternalPrecision,
"Insufficient cash"
);
}
function _settleAccountIfRequired(address account)
private
returns (AccountContext memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
// Returns a new memory reference to account context
return SettleAssetsExternal.settleAccount(account, accountContext);
} else {
return accountContext;
}
}
/// @notice Get a list of deployed library addresses (sorted by library name)
function getLibInfo() external view returns (address, address, address, address, address, address) {
return (
address(FreeCollateralExternal),
address(MigrateIncentives),
address(SettleAssetsExternal),
address(TradingAction),
address(nTokenMintAction),
address(nTokenRedeemAction)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../FreeCollateralExternal.sol";
import "../SettleAssetsExternal.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library TradingAction {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
using SafeInt256 for int256;
using SafeMath for uint256;
event LendBorrowTrade(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash
);
event AddRemoveLiquidity(
address indexed account,
uint16 indexed currencyId,
uint40 maturity,
int256 netAssetCash,
int256 netfCash,
int256 netLiquidityTokens
);
event SettledCashDebt(
address indexed settledAccount,
uint16 indexed currencyId,
address indexed settler,
int256 amountToSettleAsset,
int256 fCashAmount
);
event nTokenResidualPurchase(
uint16 indexed currencyId,
uint40 indexed maturity,
address indexed purchaser,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
);
/// @dev Used internally to manage stack issues
struct TradeContext {
int256 cash;
int256 fCashAmount;
int256 fee;
int256 netCash;
int256 totalFee;
uint256 blockTime;
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param bitmapCurrencyId currency id of the bitmap
/// @param nextSettleTime used to calculate the relative positions in the bitmap
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return netCash generated by trading
/// @return didIncurDebt if the bitmap had an fCash position go negative
function executeTradesBitmapBatch(
address account,
uint16 bitmapCurrencyId,
uint40 nextSettleTime,
bytes32[] calldata trades
) external returns (int256, bool) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(bitmapCurrencyId);
MarketParameters memory market;
bool didIncurDebt;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
c.fCashAmount = BitmapAssetsHandler.addifCashAsset(
account,
bitmapCurrencyId,
maturity,
nextSettleTime,
c.fCashAmount
);
didIncurDebt = didIncurDebt || (c.fCashAmount < 0);
c.netCash = c.netCash.add(c.cash);
}
return (c.netCash, didIncurDebt);
}
/// @notice Executes trades for a bitmapped portfolio, cannot be called directly
/// @param account account to put fCash assets in
/// @param currencyId currency id to trade
/// @param portfolioState used to update the positions in the portfolio
/// @param trades tightly packed array of trades, schema is defined in global/Types.sol
/// @return resulting portfolio state
/// @return netCash generated by trading
function executeTradesArrayBatch(
address account,
uint16 currencyId,
PortfolioState memory portfolioState,
bytes32[] calldata trades
) external returns (PortfolioState memory, int256) {
CashGroupParameters memory cashGroup = CashGroup.buildCashGroupStateful(currencyId);
MarketParameters memory market;
TradeContext memory c;
c.blockTime = block.timestamp;
for (uint256 i = 0; i < trades.length; i++) {
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trades[i]))));
if (
tradeType == TradeActionType.AddLiquidity ||
tradeType == TradeActionType.RemoveLiquidity
) {
revert("Disabled");
/**
* Manual adding and removing of liquidity is currently disabled.
*
* // Liquidity tokens can only be added by array portfolio
* c.cash = _executeLiquidityTrade(
* account,
* cashGroup,
* market,
* tradeType,
* trades[i],
* portfolioState,
* c.netCash
* );
*/
} else {
uint256 maturity;
(maturity, c.cash, c.fCashAmount) = _executeTrade(
account,
cashGroup,
market,
trades[i],
c.blockTime
);
portfolioState.addAsset(
currencyId,
maturity,
Constants.FCASH_ASSET_TYPE,
c.fCashAmount
);
}
c.netCash = c.netCash.add(c.cash);
}
return (portfolioState, c.netCash);
}
/// @notice Executes a non-liquidity token trade
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param trade bytes32 encoding of the particular trade
/// @param blockTime the current block time
/// @return maturity of the asset that was traded
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
bytes32 trade,
uint256 blockTime
)
private
returns (
uint256 maturity,
int256 cashAmount,
int256 fCashAmount
)
{
TradeActionType tradeType = TradeActionType(uint256(uint8(bytes1(trade))));
if (tradeType == TradeActionType.PurchaseNTokenResidual) {
(maturity, cashAmount, fCashAmount) = _purchaseNTokenResidual(
account,
cashGroup,
blockTime,
trade
);
} else if (tradeType == TradeActionType.SettleCashDebt) {
(maturity, cashAmount, fCashAmount) = _settleCashDebt(account, cashGroup, blockTime, trade);
} else if (tradeType == TradeActionType.Lend || tradeType == TradeActionType.Borrow) {
(cashAmount, fCashAmount) = _executeLendBorrowTrade(
cashGroup,
market,
tradeType,
blockTime,
trade
);
// This is a little ugly but required to deal with stack issues. We know the market is loaded
// with the proper maturity inside _executeLendBorrowTrade
maturity = market.maturity;
emit LendBorrowTrade(
account,
uint16(cashGroup.currencyId),
uint40(maturity),
cashAmount,
fCashAmount
);
} else {
revert("Invalid trade type");
}
}
/// @notice Executes a liquidity token trade, no fees incurred and only array portfolios may hold
/// liquidity tokens.
/// @param account the initiator of the trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param trade bytes32 encoding of the particular trade
/// @param portfolioState the current account's portfolio state
/// @param netCash the current net cash accrued in this batch of trades, can be
// used for adding liquidity
/// @return cashAmount: a positive or negative cash amount accrued to the account
function _executeLiquidityTrade(
address account,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
bytes32 trade,
PortfolioState memory portfolioState,
int256 netCash
) private returns (int256) {
uint256 marketIndex = uint8(bytes1(trade << 8));
// NOTE: this loads the market in memory
cashGroup.loadMarket(market, marketIndex, true, block.timestamp);
int256 cashAmount;
int256 fCashAmount;
int256 tokens;
if (tradeType == TradeActionType.AddLiquidity) {
cashAmount = int256((uint256(trade) >> 152) & type(uint88).max);
// Setting cash amount to zero will deposit all net cash accumulated in this trade into
// liquidity. This feature allows accounts to borrow in one maturity to provide liquidity
// in another in a single transaction without dust. It also allows liquidity providers to
// sell off the net cash residuals and use the cash amount in the new market without dust
if (cashAmount == 0) cashAmount = netCash;
// Add liquidity will check cash amount is positive
(tokens, fCashAmount) = market.addLiquidity(cashAmount);
cashAmount = cashAmount.neg(); // Report a negative cash amount in the event
} else {
tokens = int256((uint256(trade) >> 152) & type(uint88).max);
(cashAmount, fCashAmount) = market.removeLiquidity(tokens);
tokens = tokens.neg(); // Report a negative amount tokens in the event
}
{
uint256 minImpliedRate = uint32(uint256(trade) >> 120);
uint256 maxImpliedRate = uint32(uint256(trade) >> 88);
// If minImpliedRate is not set then it will be zero
require(market.lastImpliedRate >= minImpliedRate, "Trade failed, slippage");
if (maxImpliedRate != 0)
require(market.lastImpliedRate <= maxImpliedRate, "Trade failed, slippage");
}
// Add the assets in this order so they are sorted
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
Constants.FCASH_ASSET_TYPE,
fCashAmount
);
// Adds the liquidity token asset
portfolioState.addAsset(
cashGroup.currencyId,
market.maturity,
marketIndex + 1,
tokens
);
emit AddRemoveLiquidity(
account,
cashGroup.currencyId,
// This will not overflow for a long time
uint40(market.maturity),
cashAmount,
fCashAmount,
tokens
);
return cashAmount;
}
/// @notice Executes a lend or borrow trade
/// @param cashGroup parameters for the trade
/// @param market market memory location to use
/// @param tradeType whether this is add or remove liquidity
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return cashAmount - a positive or negative cash amount accrued to the account
/// @return fCashAmount - a positive or negative fCash amount accrued to the account
function _executeLendBorrowTrade(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
TradeActionType tradeType,
uint256 blockTime,
bytes32 trade
)
private
returns (
int256 cashAmount,
int256 fCashAmount
)
{
uint256 marketIndex = uint256(uint8(bytes1(trade << 8)));
// NOTE: this updates the market in memory
cashGroup.loadMarket(market, marketIndex, false, blockTime);
fCashAmount = int256(uint88(bytes11(trade << 16)));
// fCash to account will be negative here
if (tradeType == TradeActionType.Borrow) fCashAmount = fCashAmount.neg();
cashAmount = market.executeTrade(
cashGroup,
fCashAmount,
market.maturity.sub(blockTime),
marketIndex
);
require(cashAmount != 0, "Trade failed, liquidity");
uint256 rateLimit = uint256(uint32(bytes4(trade << 104)));
if (rateLimit != 0) {
if (tradeType == TradeActionType.Borrow) {
// Do not allow borrows over the rate limit
require(market.lastImpliedRate <= rateLimit, "Trade failed, slippage");
} else {
// Do not allow lends under the rate limit
require(market.lastImpliedRate >= rateLimit, "Trade failed, slippage");
}
}
}
/// @notice If an account has a negative cash balance we allow anyone to lend to to that account at a penalty
/// rate to the 3 month market.
/// @param account the account initiating the trade, used to check that self settlement is not possible
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the three month maturity where fCash will be exchanged
/// @return cashAmount: a negative cash amount that the account must pay to the settled account
/// @return fCashAmount: a positive fCash amount that the account will receive
function _settleCashDebt(
address account,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
address counterparty = address(uint256(trade) >> 88);
// Allowing an account to settle itself would result in strange outcomes
require(account != counterparty, "Cannot settle self");
int256 amountToSettleAsset = int256(uint88(uint256(trade)));
AccountContext memory counterpartyContext =
AccountContextHandler.getAccountContext(counterparty);
if (counterpartyContext.mustSettleAssets()) {
counterpartyContext = SettleAssetsExternal.settleAccount(counterparty, counterpartyContext);
}
// This will check if the amountToSettleAsset is valid and revert if it is not. Amount to settle is a positive
// number denominated in asset terms. If amountToSettleAsset is set equal to zero on the input, will return the
// max amount to settle. This will update the balance storage on the counterparty.
amountToSettleAsset = BalanceHandler.setBalanceStorageForSettleCashDebt(
counterparty,
cashGroup,
amountToSettleAsset,
counterpartyContext
);
// Settled account must borrow from the 3 month market at a penalty rate. This will fail if the market
// is not initialized.
uint256 threeMonthMaturity = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
int256 fCashAmount =
_getfCashSettleAmount(cashGroup, threeMonthMaturity, blockTime, amountToSettleAsset);
// Defensive check to ensure that we can't inadvertently cause the settler to lose fCash.
require(fCashAmount >= 0);
// It's possible that this action will put an account into negative free collateral. In this case they
// will immediately become eligible for liquidation and the account settling the debt can also liquidate
// them in the same transaction. Do not run a free collateral check here to allow this to happen.
{
PortfolioAsset[] memory assets = new PortfolioAsset[](1);
assets[0].currencyId = cashGroup.currencyId;
assets[0].maturity = threeMonthMaturity;
assets[0].notional = fCashAmount.neg(); // This is the debt the settled account will incur
assets[0].assetType = Constants.FCASH_ASSET_TYPE;
// Can transfer assets, we have settled above
counterpartyContext = TransferAssets.placeAssetsInAccount(
counterparty,
counterpartyContext,
assets
);
}
counterpartyContext.setAccountContext(counterparty);
emit SettledCashDebt(
counterparty,
uint16(cashGroup.currencyId),
account,
amountToSettleAsset,
fCashAmount.neg()
);
return (threeMonthMaturity, amountToSettleAsset.neg(), fCashAmount);
}
/// @dev Helper method to calculate the fCashAmount from the penalty settlement rate
function _getfCashSettleAmount(
CashGroupParameters memory cashGroup,
uint256 threeMonthMaturity,
uint256 blockTime,
int256 amountToSettleAsset
) private view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(threeMonthMaturity, blockTime);
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(
oracleRate.add(cashGroup.getSettlementPenalty()),
threeMonthMaturity.sub(blockTime)
);
// Amount to settle is positive, this returns the fCashAmount that the settler will
// receive as a positive number
return
cashGroup.assetRate
.convertToUnderlying(amountToSettleAsset)
// Exchange rate converts from cash to fCash when multiplying
.mulInRatePrecision(exchangeRate);
}
/// @notice Allows an account to purchase ntoken residuals
/// @param purchaser account that is purchasing the residuals
/// @param cashGroup parameters for the trade
/// @param blockTime the current block time
/// @param trade bytes32 encoding of the particular trade
/// @return maturity: the date of the idiosyncratic maturity where fCash will be exchanged
/// @return cashAmount: a positive or negative cash amount that the account will receive or pay
/// @return fCashAmount: a positive or negative fCash amount that the account will receive
function _purchaseNTokenResidual(
address purchaser,
CashGroupParameters memory cashGroup,
uint256 blockTime,
bytes32 trade
)
internal
returns (
uint256,
int256,
int256
)
{
uint256 maturity = uint256(uint32(uint256(trade) >> 216));
int256 fCashAmountToPurchase = int88(uint88(uint256(trade) >> 128));
require(maturity > blockTime, "Invalid maturity");
// Require that the residual to purchase does not fall on an existing maturity (i.e.
// it is an idiosyncratic maturity)
require(
!DateTime.isValidMarketMaturity(cashGroup.maxMarketIndex, maturity, blockTime),
"Non idiosyncratic maturity"
);
address nTokenAddress = nTokenHandler.nTokenAddress(cashGroup.currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
/* assetArrayLength */,
bytes5 parameters
) = nTokenHandler.getNTokenContext(nTokenAddress);
// Restrict purchasing until some amount of time after the last initialized time to ensure that arbitrage
// opportunities are not available (by generating residuals and then immediately purchasing them at a discount)
// This is always relative to the last initialized time which is set at utc0 when initialized, not the
// reference time. Therefore we will always restrict residual purchase relative to initialization, not reference.
// This is safer, prevents an attack if someone forces residuals and then somehow prevents market initialization
// until the residual time buffer passes.
require(
blockTime >
lastInitializedTime.add(
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_TIME_BUFFER])) * 1 hours
),
"Insufficient block time"
);
int256 notional =
BitmapAssetsHandler.getifCashNotional(nTokenAddress, cashGroup.currencyId, maturity);
// Check if amounts are valid and set them to the max available if necessary
if (notional < 0 && fCashAmountToPurchase < 0) {
// Does not allow purchasing more negative notional than available
if (fCashAmountToPurchase < notional) fCashAmountToPurchase = notional;
} else if (notional > 0 && fCashAmountToPurchase > 0) {
// Does not allow purchasing more positive notional than available
if (fCashAmountToPurchase > notional) fCashAmountToPurchase = notional;
} else {
// Does not allow moving notional in the opposite direction
revert("Invalid amount");
}
// If fCashAmount > 0 then this will return netAssetCash > 0, if fCashAmount < 0 this will return
// netAssetCash < 0. fCashAmount will go to the purchaser and netAssetCash will go to the nToken.
int256 netAssetCashNToken =
_getResidualPriceAssetCash(
cashGroup,
maturity,
blockTime,
fCashAmountToPurchase,
parameters
);
_updateNTokenPortfolio(
nTokenAddress,
cashGroup.currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase,
netAssetCashNToken
);
emit nTokenResidualPurchase(
uint16(cashGroup.currencyId),
uint40(maturity),
purchaser,
fCashAmountToPurchase,
netAssetCashNToken
);
return (maturity, netAssetCashNToken.neg(), fCashAmountToPurchase);
}
/// @notice Returns the amount of asset cash required to purchase the nToken residual
function _getResidualPriceAssetCash(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime,
int256 fCashAmount,
bytes6 parameters
) internal view returns (int256) {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
// Residual purchase incentive is specified in ten basis point increments
uint256 purchaseIncentive =
uint256(uint8(parameters[Constants.RESIDUAL_PURCHASE_INCENTIVE])) *
Constants.TEN_BASIS_POINTS;
if (fCashAmount > 0) {
// When fCash is positive then we add the purchase incentive, the purchaser
// can pay less cash for the fCash relative to the oracle rate
oracleRate = oracleRate.add(purchaseIncentive);
} else if (oracleRate > purchaseIncentive) {
// When fCash is negative, we reduce the interest rate that the purchaser will
// borrow at, we do this check to ensure that we floor the oracle rate at zero.
oracleRate = oracleRate.sub(purchaseIncentive);
} else {
// If the oracle rate is less than the purchase incentive floor the interest rate at zero
oracleRate = 0;
}
int256 exchangeRate =
Market.getExchangeRateFromImpliedRate(oracleRate, maturity.sub(blockTime));
// Returns the net asset cash from the nToken perspective, which is the same sign as the fCash amount
return
cashGroup.assetRate.convertFromUnderlying(fCashAmount.divInRatePrecision(exchangeRate));
}
function _updateNTokenPortfolio(
address nTokenAddress,
uint256 currencyId,
uint256 maturity,
uint256 lastInitializedTime,
int256 fCashAmountToPurchase,
int256 netAssetCashNToken
) private {
int256 finalNotional = BitmapAssetsHandler.addifCashAsset(
nTokenAddress,
currencyId,
maturity,
lastInitializedTime,
fCashAmountToPurchase.neg() // the nToken takes on the negative position
);
// Defensive check to ensure that fCash amounts do not flip signs
require(
(fCashAmountToPurchase > 0 && finalNotional >= 0) ||
(fCashAmountToPurchase < 0 && finalNotional <= 0)
);
// prettier-ignore
(
int256 nTokenCashBalance,
/* storedNTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nTokenAddress, currencyId);
nTokenCashBalance = nTokenCashBalance.add(netAssetCashNToken);
// This will ensure that the cash balance is not negative
BalanceHandler.setBalanceStorageForNToken(nTokenAddress, currencyId, nTokenCashBalance);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/StorageLayoutV1.sol";
import "../../internal/nToken/nTokenHandler.sol";
abstract contract ActionGuards is StorageLayoutV1 {
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
function initializeReentrancyGuard() internal {
require(reentrancyStatus == 0);
// Initialize the guard to a non-zero value, see the OZ reentrancy guard
// description for why this is more gas efficient:
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol
reentrancyStatus = _NOT_ENTERED;
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(reentrancyStatus != _ENTERED, "Reentrant call");
// Any calls to nonReentrant after this point will fail
reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
reentrancyStatus = _NOT_ENTERED;
}
// These accounts cannot receive deposits, transfers, fCash or any other
// types of value transfers.
function requireValidAccount(address account) internal view {
require(account != Constants.RESERVE); // Reserve address is address(0)
require(account != address(this));
(
uint256 isNToken,
/* incentiveAnnualEmissionRate */,
/* lastInitializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(account);
require(isNToken == 0);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/markets/Market.sol";
import "../../internal/markets/CashGroup.sol";
import "../../internal/markets/AssetRate.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenMintAction {
using SafeInt256 for int256;
using BalanceHandler for BalanceState;
using CashGroup for CashGroupParameters;
using Market for MarketParameters;
using nTokenHandler for nTokenPortfolio;
using PortfolioHandler for PortfolioState;
using AssetRate for AssetRateParameters;
using SafeMath for uint256;
using nTokenHandler for nTokenPortfolio;
/// @notice Converts the given amount of cash to nTokens in the same currency.
/// @param currencyId the currency associated the nToken
/// @param amountToDepositInternal the amount of asset tokens to deposit denominated in internal decimals
/// @return nTokens minted by this action
function nTokenMint(uint16 currencyId, int256 amountToDepositInternal)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
int256 tokensToMint = calculateTokensToMint(nToken, amountToDepositInternal, blockTime);
require(tokensToMint >= 0, "Invalid token amount");
if (nToken.portfolioState.storedAssets.length == 0) {
// If the token does not have any assets, then the markets must be initialized first.
nToken.cashBalance = nToken.cashBalance.add(amountToDepositInternal);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
currencyId,
nToken.cashBalance
);
} else {
_depositIntoPortfolio(nToken, amountToDepositInternal, blockTime);
}
// NOTE: token supply does not change here, it will change after incentives have been claimed
// during BalanceHandler.finalize
return tokensToMint;
}
/// @notice Calculates the tokens to mint to the account as a ratio of the nToken
/// present value denominated in asset cash terms.
/// @return the amount of tokens to mint, the ifCash bitmap
function calculateTokensToMint(
nTokenPortfolio memory nToken,
int256 amountToDepositInternal,
uint256 blockTime
) internal view returns (int256) {
require(amountToDepositInternal >= 0); // dev: deposit amount negative
if (amountToDepositInternal == 0) return 0;
if (nToken.lastInitializedTime != 0) {
// For the sake of simplicity, nTokens cannot be minted if they have assets
// that need to be settled. This is only done during market initialization.
uint256 nextSettleTime = nToken.getNextSettleTime();
// If next settle time <= blockTime then the token can be settled
require(nextSettleTime > blockTime, "Requires settlement");
}
int256 assetCashPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// Defensive check to ensure PV remains positive
require(assetCashPV >= 0);
// Allow for the first deposit
if (nToken.totalSupply == 0) {
return amountToDepositInternal;
} else {
// assetCashPVPost = assetCashPV + amountToDeposit
// (tokenSupply + tokensToMint) / tokenSupply == (assetCashPV + amountToDeposit) / assetCashPV
// (tokenSupply + tokensToMint) == (assetCashPV + amountToDeposit) * tokenSupply / assetCashPV
// (tokenSupply + tokensToMint) == tokenSupply + (amountToDeposit * tokenSupply) / assetCashPV
// tokensToMint == (amountToDeposit * tokenSupply) / assetCashPV
return amountToDepositInternal.mul(nToken.totalSupply).div(assetCashPV);
}
}
/// @notice Portions out assetCashDeposit into amounts to deposit into individual markets. When
/// entering this method we know that assetCashDeposit is positive and the nToken has been
/// initialized to have liquidity tokens.
function _depositIntoPortfolio(
nTokenPortfolio memory nToken,
int256 assetCashDeposit,
uint256 blockTime
) private {
(int256[] memory depositShares, int256[] memory leverageThresholds) =
nTokenHandler.getDepositParameters(
nToken.cashGroup.currencyId,
nToken.cashGroup.maxMarketIndex
);
// Loop backwards from the last market to the first market, the reasoning is a little complicated:
// If we have to deleverage the markets (i.e. lend instead of provide liquidity) it's quite gas inefficient
// to calculate the cash amount to lend. We do know that longer term maturities will have more
// slippage and therefore the residual from the perMarketDeposit will be lower as the maturities get
// closer to the current block time. Any residual cash from lending will be rolled into shorter
// markets as this loop progresses.
int256 residualCash;
MarketParameters memory market;
for (uint256 marketIndex = nToken.cashGroup.maxMarketIndex; marketIndex > 0; marketIndex--) {
int256 fCashAmount;
// Loads values into the market memory slot
nToken.cashGroup.loadMarket(
market,
marketIndex,
true, // Needs liquidity to true
blockTime
);
// If market has not been initialized, continue. This can occur when cash groups extend maxMarketIndex
// before initializing
if (market.totalLiquidity == 0) continue;
// Checked that assetCashDeposit must be positive before entering
int256 perMarketDeposit =
assetCashDeposit
.mul(depositShares[marketIndex - 1])
.div(Constants.DEPOSIT_PERCENT_BASIS)
.add(residualCash);
(fCashAmount, residualCash) = _lendOrAddLiquidity(
nToken,
market,
perMarketDeposit,
leverageThresholds[marketIndex - 1],
marketIndex,
blockTime
);
if (fCashAmount != 0) {
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
market.maturity,
nToken.lastInitializedTime,
fCashAmount
);
}
}
// nToken is allowed to store assets directly without updating account context.
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// Defensive check to ensure that we do not somehow accrue negative residual cash.
require(residualCash >= 0, "Negative residual cash");
// This will occur if the three month market is over levered and we cannot lend into it
if (residualCash > 0) {
// Any remaining residual cash will be put into the nToken balance and added as liquidity on the
// next market initialization
nToken.cashBalance = nToken.cashBalance.add(residualCash);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
}
/// @notice For a given amount of cash to deposit, decides how much to lend or provide
/// given the market conditions.
function _lendOrAddLiquidity(
nTokenPortfolio memory nToken,
MarketParameters memory market,
int256 perMarketDeposit,
int256 leverageThreshold,
uint256 marketIndex,
uint256 blockTime
) private returns (int256 fCashAmount, int256 residualCash) {
// We start off with the entire per market deposit as residuals
residualCash = perMarketDeposit;
// If the market is over leveraged then we will lend to it instead of providing liquidity
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
(residualCash, fCashAmount) = _deleverageMarket(
nToken.cashGroup,
market,
perMarketDeposit,
blockTime,
marketIndex
);
// Recalculate this after lending into the market, if it is still over leveraged then
// we will not add liquidity and just exit.
if (_isMarketOverLeveraged(nToken.cashGroup, market, leverageThreshold)) {
// Returns the residual cash amount
return (fCashAmount, residualCash);
}
}
// Add liquidity to the market only if we have successfully delevered.
// (marketIndex - 1) is the index of the nToken portfolio array where the asset is stored
// If deleveraged, residualCash is what remains
// If not deleveraged, residual cash is per market deposit
fCashAmount = fCashAmount.add(
_addLiquidityToMarket(nToken, market, marketIndex - 1, residualCash)
);
// No residual cash if we're adding liquidity
return (fCashAmount, 0);
}
/// @notice Markets are over levered when their proportion is greater than a governance set
/// threshold. At this point, providing liquidity will incur too much negative fCash on the nToken
/// account for the given amount of cash deposited, putting the nToken account at risk of liquidation.
/// If the market is over leveraged, we call `deleverageMarket` to lend to the market instead.
function _isMarketOverLeveraged(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 leverageThreshold
) private pure returns (bool) {
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// Comparison we want to do:
// (totalfCash) / (totalfCash + totalCashUnderlying) > leverageThreshold
// However, the division will introduce rounding errors so we change this to:
// totalfCash * RATE_PRECISION > leverageThreshold * (totalfCash + totalCashUnderlying)
// Leverage threshold is denominated in rate precision.
return (
market.totalfCash.mul(Constants.RATE_PRECISION) >
leverageThreshold.mul(market.totalfCash.add(totalCashUnderlying))
);
}
function _addLiquidityToMarket(
nTokenPortfolio memory nToken,
MarketParameters memory market,
uint256 index,
int256 perMarketDeposit
) private returns (int256) {
// Add liquidity to the market
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[index];
// We expect that all the liquidity tokens are in the portfolio in order.
require(
asset.maturity == market.maturity &&
// Ensures that the asset type references the proper liquidity token
asset.assetType == index + Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
// Ensures that the storage state will not be overwritten
asset.storageState == AssetStorageState.NoChange,
"PT: invalid liquidity token"
);
// This will update the market state as well, fCashAmount returned here is negative
(int256 liquidityTokens, int256 fCashAmount) = market.addLiquidity(perMarketDeposit);
asset.notional = asset.notional.add(liquidityTokens);
asset.storageState = AssetStorageState.Update;
return fCashAmount;
}
/// @notice Lends into the market to reduce the leverage that the nToken will add liquidity at. May fail due
/// to slippage or result in some amount of residual cash.
function _deleverageMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
int256 perMarketDeposit,
uint256 blockTime,
uint256 marketIndex
) private returns (int256, int256) {
uint256 timeToMaturity = market.maturity.sub(blockTime);
// Shift the last implied rate by some buffer and calculate the exchange rate to fCash. Hope that this
// is sufficient to cover all potential slippage. We don't use the `getfCashGivenCashAmount` method here
// because it is very gas inefficient.
int256 assumedExchangeRate;
if (market.lastImpliedRate < Constants.DELEVERAGE_BUFFER) {
// Floor the exchange rate at zero interest rate
assumedExchangeRate = Constants.RATE_PRECISION;
} else {
assumedExchangeRate = Market.getExchangeRateFromImpliedRate(
market.lastImpliedRate.sub(Constants.DELEVERAGE_BUFFER),
timeToMaturity
);
}
int256 fCashAmount;
{
int256 perMarketDepositUnderlying =
cashGroup.assetRate.convertToUnderlying(perMarketDeposit);
// NOTE: cash * exchangeRate = fCash
fCashAmount = perMarketDepositUnderlying.mulInRatePrecision(assumedExchangeRate);
}
int256 netAssetCash = market.executeTrade(cashGroup, fCashAmount, timeToMaturity, marketIndex);
// This means that the trade failed
if (netAssetCash == 0) {
return (perMarketDeposit, 0);
} else {
// Ensure that net the per market deposit figure does not drop below zero, this should not be possible
// given how we've calculated the exchange rate but extra caution here
int256 residual = perMarketDeposit.add(netAssetCash);
require(residual >= 0); // dev: insufficient cash
return (residual, fCashAmount);
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../internal/markets/Market.sol";
import "../../internal/nToken/nTokenHandler.sol";
import "../../internal/nToken/nTokenCalculations.sol";
import "../../internal/portfolio/PortfolioHandler.sol";
import "../../internal/portfolio/TransferAssets.sol";
import "../../internal/balances/BalanceHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenRedeemAction {
using SafeInt256 for int256;
using SafeMath for uint256;
using Bitmap for bytes32;
using BalanceHandler for BalanceState;
using Market for MarketParameters;
using CashGroup for CashGroupParameters;
using PortfolioHandler for PortfolioState;
using nTokenHandler for nTokenPortfolio;
/// @notice When redeeming nTokens via the batch they must all be sold to cash and this
/// method will return the amount of asset cash sold.
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @return amount of asset cash to return to the account, denominated in internal token decimals
function nTokenRedeemViaBatch(uint16 currencyId, int256 tokensToRedeem)
external
returns (int256)
{
uint256 blockTime = block.timestamp;
// prettier-ignore
(
int256 totalAssetCash,
bool hasResidual,
/* PortfolioAssets[] memory newfCashAssets */
) = _redeem(currencyId, tokensToRedeem, true, false, blockTime);
require(!hasResidual, "Cannot redeem via batch, residual");
return totalAssetCash;
}
/// @notice Redeems nTokens for asset cash and fCash
/// @param currencyId the currency associated the nToken
/// @param tokensToRedeem the amount of nTokens to convert to cash
/// @param sellTokenAssets attempt to sell residual fCash and convert to cash, if unsuccessful then place
/// back into the account's portfolio
/// @param acceptResidualAssets if true, then ifCash residuals will be placed into the account and there will
/// be no penalty assessed
/// @return assetCash positive amount of asset cash to the account
/// @return hasResidual true if there are fCash residuals left
/// @return assets an array of fCash asset residuals to place into the account
function redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets
) external returns (int256, bool, PortfolioAsset[] memory) {
return _redeem(
currencyId,
tokensToRedeem,
sellTokenAssets,
acceptResidualAssets,
block.timestamp
);
}
function _redeem(
uint16 currencyId,
int256 tokensToRedeem,
bool sellTokenAssets,
bool acceptResidualAssets,
uint256 blockTime
) internal returns (int256, bool, PortfolioAsset[] memory) {
require(tokensToRedeem > 0);
nTokenPortfolio memory nToken;
nToken.loadNTokenPortfolioStateful(currencyId);
// nTokens cannot be redeemed during the period of time where they require settlement.
require(nToken.getNextSettleTime() > blockTime, "Requires settlement");
require(tokensToRedeem < nToken.totalSupply, "Cannot redeem");
PortfolioAsset[] memory newifCashAssets;
// Get the ifCash bits that are idiosyncratic
bytes32 ifCashBits = nTokenCalculations.getNTokenifCashBits(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
if (ifCashBits != 0 && acceptResidualAssets) {
// This will remove all the ifCash assets proportionally from the account
newifCashAssets = _reduceifCashAssetsProportional(
nToken.tokenAddress,
currencyId,
nToken.lastInitializedTime,
tokensToRedeem,
nToken.totalSupply,
ifCashBits
);
// Once the ifCash bits have been withdrawn, set this to zero so that getLiquidityTokenWithdraw
// simply gets the proportional amount of liquidity tokens to remove
ifCashBits = 0;
}
// Returns the liquidity tokens to withdraw per market and the netfCash amounts. Net fCash amounts are only
// set when ifCashBits != 0. Otherwise they must be calculated in _withdrawLiquidityTokens
(int256[] memory tokensToWithdraw, int256[] memory netfCash) = nTokenCalculations.getLiquidityTokenWithdraw(
nToken,
tokensToRedeem,
blockTime,
ifCashBits
);
// Returns the totalAssetCash as a result of withdrawing liquidity tokens and cash. netfCash will be updated
// in memory if required and will contain the fCash to be sold or returned to the portfolio
int256 totalAssetCash = _reduceLiquidAssets(
nToken,
tokensToRedeem,
tokensToWithdraw,
netfCash,
ifCashBits == 0, // If there are no residuals then we need to populate netfCash amounts
blockTime
);
bool netfCashRemaining = true;
if (sellTokenAssets) {
int256 assetCash;
// NOTE: netfCash is modified in place and set to zero if the fCash is sold
(assetCash, netfCashRemaining) = _sellfCashAssets(nToken, netfCash, blockTime);
totalAssetCash = totalAssetCash.add(assetCash);
}
if (netfCashRemaining) {
// If the account is unwilling to accept residuals then will fail here.
require(acceptResidualAssets, "Residuals");
newifCashAssets = _addResidualsToAssets(nToken.portfolioState.storedAssets, newifCashAssets, netfCash);
}
return (totalAssetCash, netfCashRemaining, newifCashAssets);
}
/// @notice Removes liquidity tokens and cash from the nToken
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @param blockTime current block time
/// @return assetCashShare amount of cash the redeemer will receive from withdrawing cash assets from the nToken
function _reduceLiquidAssets(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
bool mustCalculatefCash,
uint256 blockTime
) private returns (int256 assetCashShare) {
// Get asset cash share for the nToken, if it exists. It is required in balance handler that the
// nToken can never have a negative cash asset cash balance so what we get here is always positive
// or zero.
assetCashShare = nToken.cashBalance.mul(nTokensToRedeem).div(nToken.totalSupply);
if (assetCashShare > 0) {
nToken.cashBalance = nToken.cashBalance.subNoNeg(assetCashShare);
BalanceHandler.setBalanceStorageForNToken(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.cashBalance
);
}
// Get share of liquidity tokens to remove, netfCash is modified in memory during this method if mustCalculatefcash
// is set to true
assetCashShare = assetCashShare.add(
_removeLiquidityTokens(nToken, nTokensToRedeem, tokensToWithdraw, netfCash, blockTime, mustCalculatefCash)
);
nToken.portfolioState.storeAssets(nToken.tokenAddress);
// NOTE: Token supply change will happen when we finalize balances and after minting of incentives
return assetCashShare;
}
/// @notice Removes nToken liquidity tokens and updates the netfCash figures.
/// @param nToken portfolio object
/// @param nTokensToRedeem tokens to redeem
/// @param tokensToWithdraw array of liquidity tokens to withdraw
/// @param netfCash array of netfCash figures
/// @param blockTime current block time
/// @param mustCalculatefCash true if netfCash must be calculated in the removeLiquidityTokens step
/// @return totalAssetCashClaims is the amount of asset cash raised from liquidity token cash claims
function _removeLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
int256[] memory tokensToWithdraw,
int256[] memory netfCash,
uint256 blockTime,
bool mustCalculatefCash
) private returns (int256 totalAssetCashClaims) {
MarketParameters memory market;
for (uint256 i = 0; i < nToken.portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = nToken.portfolioState.storedAssets[i];
asset.notional = asset.notional.sub(tokensToWithdraw[i]);
// Cannot redeem liquidity tokens down to zero or this will cause many issues with
// market initialization.
require(asset.notional > 0, "Cannot redeem to zero");
require(asset.storageState == AssetStorageState.NoChange);
asset.storageState = AssetStorageState.Update;
// This will load a market object in memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
int256 fCashClaim;
{
int256 assetCash;
// Remove liquidity from the market
(assetCash, fCashClaim) = market.removeLiquidity(tokensToWithdraw[i]);
totalAssetCashClaims = totalAssetCashClaims.add(assetCash);
}
int256 fCashToNToken;
if (mustCalculatefCash) {
// Do this calculation if net ifCash is not set, will happen if there are no residuals
int256 fCashShare = BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
asset.maturity
);
fCashShare = fCashShare.mul(nTokensToRedeem).div(nToken.totalSupply);
// netfCash = fCashClaim + fCashShare
netfCash[i] = fCashClaim.add(fCashShare);
fCashToNToken = fCashShare.neg();
} else {
// Account will receive netfCash amount. Deduct that from the fCash claim and add the
// remaining back to the nToken to net off the nToken's position
// fCashToNToken = -fCashShare
// netfCash = fCashClaim + fCashShare
// fCashToNToken = -(netfCash - fCashClaim)
// fCashToNToken = fCashClaim - netfCash
fCashToNToken = fCashClaim.sub(netfCash[i]);
}
// Removes the account's fCash position from the nToken
BitmapAssetsHandler.addifCashAsset(
nToken.tokenAddress,
asset.currencyId,
asset.maturity,
nToken.lastInitializedTime,
fCashToNToken
);
}
return totalAssetCashClaims;
}
/// @notice Sells fCash assets back into the market for cash. Negative fCash assets will decrease netAssetCash
/// as a result. The aim here is to ensure that accounts can redeem nTokens without having to take on
/// fCash assets.
function _sellfCashAssets(
nTokenPortfolio memory nToken,
int256[] memory netfCash,
uint256 blockTime
) private returns (int256 totalAssetCash, bool hasResidual) {
MarketParameters memory market;
hasResidual = false;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] == 0) continue;
nToken.cashGroup.loadMarket(market, i + 1, false, blockTime);
int256 netAssetCash = market.executeTrade(
nToken.cashGroup,
// Use the negative of fCash notional here since we want to net it out
netfCash[i].neg(),
nToken.portfolioState.storedAssets[i].maturity.sub(blockTime),
i + 1
);
if (netAssetCash == 0) {
// This means that the trade failed
hasResidual = true;
} else {
totalAssetCash = totalAssetCash.add(netAssetCash);
netfCash[i] = 0;
}
}
}
/// @notice Combines newifCashAssets array with netfCash assets into a single finalfCashAssets array
function _addResidualsToAssets(
PortfolioAsset[] memory liquidityTokens,
PortfolioAsset[] memory newifCashAssets,
int256[] memory netfCash
) internal pure returns (PortfolioAsset[] memory finalfCashAssets) {
uint256 numAssetsToExtend;
for (uint256 i = 0; i < netfCash.length; i++) {
if (netfCash[i] != 0) numAssetsToExtend++;
}
uint256 newLength = newifCashAssets.length + numAssetsToExtend;
finalfCashAssets = new PortfolioAsset[](newLength);
uint index = 0;
for (; index < newifCashAssets.length; index++) {
finalfCashAssets[index] = newifCashAssets[index];
}
uint netfCashIndex = 0;
for (; index < finalfCashAssets.length; ) {
if (netfCash[netfCashIndex] != 0) {
PortfolioAsset memory asset = finalfCashAssets[index];
asset.currencyId = liquidityTokens[netfCashIndex].currencyId;
asset.maturity = liquidityTokens[netfCashIndex].maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = netfCash[netfCashIndex];
index++;
}
netfCashIndex++;
}
return finalfCashAssets;
}
/// @notice Used to reduce an nToken ifCash assets portfolio proportionately when redeeming
/// nTokens to its underlying assets.
function _reduceifCashAssetsProportional(
address account,
uint256 currencyId,
uint256 lastInitializedTime,
int256 tokensToRedeem,
int256 totalSupply,
bytes32 assetsBitmap
) internal returns (PortfolioAsset[] memory) {
uint256 index = assetsBitmap.totalBitsSet();
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(lastInitializedTime, bitNum);
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
int256 notional = fCashSlot.notional;
int256 notionalToTransfer = notional.mul(tokensToRedeem).div(totalSupply);
int256 finalNotional = notional.sub(notionalToTransfer);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notionalToTransfer;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../internal/portfolio/PortfolioHandler.sol";
import "../internal/balances/BalanceHandler.sol";
import "../internal/settlement/SettlePortfolioAssets.sol";
import "../internal/settlement/SettleBitmapAssets.sol";
import "../internal/AccountContextHandler.sol";
/// @notice External library for settling assets
library SettleAssetsExternal {
using PortfolioHandler for PortfolioState;
using AccountContextHandler for AccountContext;
event AccountSettled(address indexed account);
/// @notice Settles an account, returns the new account context object after settlement.
/// @dev The memory location of the account context object is not the same as the one returned.
function settleAccount(
address account,
AccountContext memory accountContext
) external returns (AccountContext memory) {
// Defensive check to ensure that this is a valid settlement
require(accountContext.mustSettleAssets());
SettleAmount[] memory settleAmounts;
PortfolioState memory portfolioState;
if (accountContext.isBitmapEnabled()) {
(int256 settledCash, uint256 blockTimeUTC0) =
SettleBitmapAssets.settleBitmappedCashGroup(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
block.timestamp
);
require(blockTimeUTC0 < type(uint40).max); // dev: block time utc0 overflow
accountContext.nextSettleTime = uint40(blockTimeUTC0);
settleAmounts = new SettleAmount[](1);
settleAmounts[0] = SettleAmount(accountContext.bitmapCurrencyId, settledCash);
} else {
portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
0
);
settleAmounts = SettlePortfolioAssets.settlePortfolio(portfolioState, block.timestamp);
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
BalanceHandler.finalizeSettleAmounts(account, accountContext, settleAmounts);
emit AccountSettled(account);
return accountContext;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../external/SettleAssetsExternal.sol";
import "../internal/AccountContextHandler.sol";
import "../internal/valuation/FreeCollateral.sol";
/// @title Externally deployed library for free collateral calculations
library FreeCollateralExternal {
using AccountContextHandler for AccountContext;
/// @notice Returns the ETH denominated free collateral of an account, represents the amount of
/// debt that the account can incur before liquidation. If an account's assets need to be settled this
/// will revert, either settle the account or use the off chain SDK to calculate free collateral.
/// @dev Called via the Views.sol method to return an account's free collateral. Does not work
/// for the nToken, the nToken does not have an account context.
/// @param account account to calculate free collateral for
/// @return total free collateral in ETH w/ 8 decimal places
/// @return array of net local values in asset values ordered by currency id
function getFreeCollateralView(address account)
external
view
returns (int256, int256[] memory)
{
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
// The internal free collateral function does not account for settled assets. The Notional SDK
// can calculate the free collateral off chain if required at this point.
require(!accountContext.mustSettleAssets(), "Assets not settled");
return FreeCollateral.getFreeCollateralView(account, accountContext, block.timestamp);
}
/// @notice Calculates free collateral and will revert if it falls below zero. If the account context
/// must be updated due to changes in debt settings, will update. Cannot check free collateral if assets
/// need to be settled first.
/// @dev Cannot be called directly by users, used during various actions that require an FC check. Must be
/// called before the end of any transaction for accounts where FC can decrease.
/// @param account account to calculate free collateral for
function checkFreeCollateralAndRevert(address account) external {
AccountContext memory accountContext = AccountContextHandler.getAccountContext(account);
require(!accountContext.mustSettleAssets(), "Assets not settled");
(int256 ethDenominatedFC, bool updateContext) =
FreeCollateral.getFreeCollateralStateful(account, accountContext, block.timestamp);
if (updateContext) {
accountContext.setAccountContext(account);
}
require(ethDenominatedFC >= 0, "Insufficient free collateral");
}
/// @notice Calculates liquidation factors for an account
/// @dev Only called internally by liquidation actions, does some initial validation of currencies. If a currency is
/// specified that the account does not have, a asset available figure of zero will be returned. If this is the case then
/// liquidation actions will revert.
/// @dev an ntoken account will return 0 FC and revert if called
/// @param account account to liquidate
/// @param localCurrencyId currency that the debts are denominated in
/// @param collateralCurrencyId collateral currency to liquidate against, set to zero in the case of local currency liquidation
/// @return accountContext the accountContext of the liquidated account
/// @return factors struct of relevant factors for liquidation
/// @return portfolio the portfolio array of the account (bitmap accounts will return an empty array)
function getLiquidationFactors(
address account,
uint256 localCurrencyId,
uint256 collateralCurrencyId
)
external
returns (
AccountContext memory accountContext,
LiquidationFactors memory factors,
PortfolioAsset[] memory portfolio
)
{
accountContext = AccountContextHandler.getAccountContext(account);
if (accountContext.mustSettleAssets()) {
accountContext = SettleAssetsExternal.settleAccount(account, accountContext);
}
if (accountContext.isBitmapEnabled()) {
// A bitmap currency can only ever hold debt in this currency
require(localCurrencyId == accountContext.bitmapCurrencyId);
}
(factors, portfolio) = FreeCollateral.getLiquidationFactors(
account,
accountContext,
block.timestamp,
localCurrencyId,
collateralCurrencyId
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../global/Constants.sol";
library SafeInt256 {
int256 private constant _INT256_MIN = type(int256).min;
/// @dev Returns the multiplication of two signed integers, reverting on
/// overflow.
/// Counterpart to Solidity's `*` operator.
/// Requirements:
/// - Multiplication cannot overflow.
function mul(int256 a, int256 b) internal pure returns (int256 c) {
c = a * b;
if (a == -1) require (b == 0 || c / b == a);
else require (a == 0 || c / a == b);
}
/// @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256 c) {
require(!(b == -1 && a == _INT256_MIN)); // dev: int256 div overflow
// NOTE: solidity will automatically revert on divide by zero
c = a / b;
}
function sub(int256 x, int256 y) internal pure returns (int256 z) {
// taken from uniswap v3
require((z = x - y) <= x == (y >= 0));
}
function add(int256 x, int256 y) internal pure returns (int256 z) {
require((z = x + y) >= x == (y >= 0));
}
function neg(int256 x) internal pure returns (int256 y) {
return mul(-1, x);
}
function abs(int256 x) internal pure returns (int256) {
if (x < 0) return neg(x);
else return x;
}
function subNoNeg(int256 x, int256 y) internal pure returns (int256 z) {
z = sub(x, y);
require(z >= 0); // dev: int256 sub to negative
return z;
}
/// @dev Calculates x * RATE_PRECISION / y while checking overflows
function divInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, Constants.RATE_PRECISION), y);
}
/// @dev Calculates x * y / RATE_PRECISION while checking overflows
function mulInRatePrecision(int256 x, int256 y) internal pure returns (int256) {
return div(mul(x, y), Constants.RATE_PRECISION);
}
function toUint(int256 x) internal pure returns (uint256) {
require(x >= 0);
return uint256(x);
}
function toInt(uint256 x) internal pure returns (int256) {
require (x <= uint256(type(int256).max)); // dev: toInt overflow
return int256(x);
}
function max(int256 x, int256 y) internal pure returns (int256) {
return x > y ? x : y;
}
function min(int256 x, int256 y) internal pure returns (int256) {
return x < y ? x : y;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
/**
* @notice Storage layout for the system. Do not change this file once deployed, future storage
* layouts must inherit this and increment the version number.
*/
contract StorageLayoutV1 {
// The current maximum currency id
uint16 internal maxCurrencyId;
// Sets the state of liquidations being enabled during a paused state. Each of the four lower
// bits can be turned on to represent one of the liquidation types being enabled.
bytes1 internal liquidationEnabledState;
// Set to true once the system has been initialized
bool internal hasInitialized;
/* Authentication Mappings */
// This is set to the timelock contract to execute governance functions
address public owner;
// This is set to an address of a router that can only call governance actions
address public pauseRouter;
// This is set to an address of a router that can only call governance actions
address public pauseGuardian;
// On upgrades this is set in the case that the pause router is used to pass the rollback check
address internal rollbackRouterImplementation;
// A blanket allowance for a spender to transfer any of an account's nTokens. This would allow a user
// to set an allowance on all nTokens for a particular integrating contract system.
// owner => spender => transferAllowance
mapping(address => mapping(address => uint256)) internal nTokenWhitelist;
// Individual transfer allowances for nTokens used for ERC20
// owner => spender => currencyId => transferAllowance
mapping(address => mapping(address => mapping(uint16 => uint256))) internal nTokenAllowance;
// Transfer operators
// Mapping from a global ERC1155 transfer operator contract to an approval value for it
mapping(address => bool) internal globalTransferOperator;
// Mapping from an account => operator => approval status for that operator. This is a specific
// approval between two addresses for ERC1155 transfers.
mapping(address => mapping(address => bool)) internal accountAuthorizedTransferOperator;
// Approval for a specific contract to use the `batchBalanceAndTradeActionWithCallback` method in
// BatchAction.sol, can only be set by governance
mapping(address => bool) internal authorizedCallbackContract;
// Reverse mapping from token addresses to currency ids, only used for referencing in views
// and checking for duplicate token listings.
mapping(address => uint16) internal tokenAddressToCurrencyId;
// Reentrancy guard
uint256 internal reentrancyStatus;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Incentives.sol";
import "./TokenHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/FloatingPoint56.sol";
library BalanceHandler {
using SafeInt256 for int256;
using TokenHandler for Token;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
/// @notice Emitted when a cash balance changes
event CashBalanceChange(address indexed account, uint16 indexed currencyId, int256 netCashChange);
/// @notice Emitted when nToken supply changes (not the same as transfers)
event nTokenSupplyChange(address indexed account, uint16 indexed currencyId, int256 tokenSupplyChange);
/// @notice Emitted when reserve fees are accrued
event ReserveFeeAccrued(uint16 indexed currencyId, int256 fee);
/// @notice Emitted when reserve balance is updated
event ReserveBalanceUpdated(uint16 indexed currencyId, int256 newBalance);
/// @notice Emitted when reserve balance is harvested
event ExcessReserveBalanceHarvested(uint16 indexed currencyId, int256 harvestAmount);
/// @notice Deposits asset tokens into an account
/// @dev Handles two special cases when depositing tokens into an account.
/// - If a token has transfer fees then the amount specified does not equal the amount that the contract
/// will receive. Complete the deposit here rather than in finalize so that the contract has the correct
/// balance to work with.
/// - Force a transfer before finalize to allow a different account to deposit into an account
/// @return assetAmountInternal which is the converted asset amount accounting for transfer fees
function depositAssetToken(
BalanceState memory balanceState,
address account,
int256 assetAmountExternal,
bool forceTransfer
) internal returns (int256 assetAmountInternal) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0); // dev: deposit asset token amount negative
Token memory token = TokenHandler.getAssetToken(balanceState.currencyId);
if (token.tokenType == TokenType.aToken) {
// Handles special accounting requirements for aTokens
assetAmountExternal = AaveHandler.convertToScaledBalanceExternal(
balanceState.currencyId,
assetAmountExternal
);
}
// Force transfer is used to complete the transfer before going to finalize
if (token.hasTransferFee || forceTransfer) {
// If the token has a transfer fee the deposit amount may not equal the actual amount
// that the contract will receive. We handle the deposit here and then update the netCashChange
// accordingly which is denominated in internal precision.
int256 assetAmountExternalPrecisionFinal = token.transfer(account, balanceState.currencyId, assetAmountExternal);
// Convert the external precision to internal, it's possible that we lose dust amounts here but
// this is unavoidable because we do not know how transfer fees are calculated.
assetAmountInternal = token.convertToInternal(assetAmountExternalPrecisionFinal);
// Transfer has been called
balanceState.netCashChange = balanceState.netCashChange.add(assetAmountInternal);
return assetAmountInternal;
} else {
assetAmountInternal = token.convertToInternal(assetAmountExternal);
// Otherwise add the asset amount here. It may be net off later and we want to only do
// a single transfer during the finalize method. Use internal precision to ensure that internal accounting
// and external account remain in sync.
// Transfer will be deferred
balanceState.netAssetTransferInternalPrecision = balanceState
.netAssetTransferInternalPrecision
.add(assetAmountInternal);
// Returns the converted assetAmountExternal to the internal amount
return assetAmountInternal;
}
}
/// @notice Handle deposits of the underlying token
/// @dev In this case we must wrap the underlying token into an asset token, ensuring that we do not end up
/// with any underlying tokens left as dust on the contract.
function depositUnderlyingToken(
BalanceState memory balanceState,
address account,
int256 underlyingAmountExternal
) internal returns (int256) {
if (underlyingAmountExternal == 0) return 0;
require(underlyingAmountExternal > 0); // dev: deposit underlying token negative
Token memory underlyingToken = TokenHandler.getUnderlyingToken(balanceState.currencyId);
// This is the exact amount of underlying tokens the account has in external precision.
if (underlyingToken.tokenType == TokenType.Ether) {
// Underflow checked above
require(uint256(underlyingAmountExternal) == msg.value, "ETH Balance");
} else {
underlyingAmountExternal = underlyingToken.transfer(account, balanceState.currencyId, underlyingAmountExternal);
}
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
int256 assetTokensReceivedExternalPrecision =
assetToken.mint(balanceState.currencyId, SafeInt256.toUint(underlyingAmountExternal));
// cTokens match INTERNAL_TOKEN_PRECISION so this will short circuit but we leave this here in case a different
// type of asset token is listed in the future. It's possible if those tokens have a different precision dust may
// accrue but that is not relevant now.
int256 assetTokensReceivedInternal =
assetToken.convertToInternal(assetTokensReceivedExternalPrecision);
// Transfer / mint has taken effect
balanceState.netCashChange = balanceState.netCashChange.add(assetTokensReceivedInternal);
return assetTokensReceivedInternal;
}
/// @notice Finalizes an account's balances, handling any transfer logic required
/// @dev This method SHOULD NOT be used for nToken accounts, for that use setBalanceStorageForNToken
/// as the nToken is limited in what types of balances it can hold.
function finalize(
BalanceState memory balanceState,
address account,
AccountContext memory accountContext,
bool redeemToUnderlying
) internal returns (int256 transferAmountExternal) {
bool mustUpdate;
if (balanceState.netNTokenTransfer < 0) {
require(
balanceState.storedNTokenBalance
.add(balanceState.netNTokenSupplyChange)
.add(balanceState.netNTokenTransfer) >= 0,
"Neg nToken"
);
}
if (balanceState.netAssetTransferInternalPrecision < 0) {
require(
balanceState.storedCashBalance
.add(balanceState.netCashChange)
.add(balanceState.netAssetTransferInternalPrecision) >= 0,
"Neg Cash"
);
}
// Transfer amount is checked inside finalize transfers in case when converting to external we
// round down to zero. This returns the actual net transfer in internal precision as well.
(
transferAmountExternal,
balanceState.netAssetTransferInternalPrecision
) = _finalizeTransfers(balanceState, account, redeemToUnderlying);
// No changes to total cash after this point
int256 totalCashChange = balanceState.netCashChange.add(balanceState.netAssetTransferInternalPrecision);
if (totalCashChange != 0) {
balanceState.storedCashBalance = balanceState.storedCashBalance.add(totalCashChange);
mustUpdate = true;
emit CashBalanceChange(
account,
uint16(balanceState.currencyId),
totalCashChange
);
}
if (balanceState.netNTokenTransfer != 0 || balanceState.netNTokenSupplyChange != 0) {
// Final nToken balance is used to calculate the account incentive debt
int256 finalNTokenBalance = balanceState.storedNTokenBalance
.add(balanceState.netNTokenTransfer)
.add(balanceState.netNTokenSupplyChange);
// The toUint() call here will ensure that nToken balances never become negative
Incentives.claimIncentives(balanceState, account, finalNTokenBalance.toUint());
balanceState.storedNTokenBalance = finalNTokenBalance;
if (balanceState.netNTokenSupplyChange != 0) {
emit nTokenSupplyChange(
account,
uint16(balanceState.currencyId),
balanceState.netNTokenSupplyChange
);
}
mustUpdate = true;
}
if (mustUpdate) {
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
accountContext.setActiveCurrency(
balanceState.currencyId,
// Set active currency to true if either balance is non-zero
balanceState.storedCashBalance != 0 || balanceState.storedNTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (balanceState.storedCashBalance < 0) {
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check where all balances
// are examined
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
}
/// @dev Returns the amount transferred in underlying or asset terms depending on how redeem to underlying
/// is specified.
function _finalizeTransfers(
BalanceState memory balanceState,
address account,
bool redeemToUnderlying
) private returns (int256 actualTransferAmountExternal, int256 assetTransferAmountInternal) {
Token memory assetToken = TokenHandler.getAssetToken(balanceState.currencyId);
// Dust accrual to the protocol is possible if the token decimals is less than internal token precision.
// See the comments in TokenHandler.convertToExternal and TokenHandler.convertToInternal
int256 assetTransferAmountExternal =
assetToken.convertToExternal(balanceState.netAssetTransferInternalPrecision);
if (assetTransferAmountExternal == 0) {
return (0, 0);
} else if (redeemToUnderlying && assetTransferAmountExternal < 0) {
// We only do the redeem to underlying if the asset transfer amount is less than zero. If it is greater than
// zero then we will do a normal transfer instead.
// We use the internal amount here and then scale it to the external amount so that there is
// no loss of precision between our internal accounting and the external account. In this case
// there will be no dust accrual in underlying tokens since we will transfer the exact amount
// of underlying that was received.
actualTransferAmountExternal = assetToken.redeem(
balanceState.currencyId,
account,
// No overflow, checked above
uint256(assetTransferAmountExternal.neg())
);
// In this case we're transferring underlying tokens, we want to convert the internal
// asset transfer amount to store in cash balances
assetTransferAmountInternal = assetToken.convertToInternal(assetTransferAmountExternal);
} else {
// NOTE: in the case of aTokens assetTransferAmountExternal is the scaledBalanceOf in external precision, it
// will be converted to balanceOf denomination inside transfer
actualTransferAmountExternal = assetToken.transfer(account, balanceState.currencyId, assetTransferAmountExternal);
// Convert the actual transferred amount
assetTransferAmountInternal = assetToken.convertToInternal(actualTransferAmountExternal);
}
}
/// @notice Special method for settling negative current cash debts. This occurs when an account
/// has a negative fCash balance settle to cash. A settler may come and force the account to borrow
/// at the prevailing 3 month rate
/// @dev Use this method to avoid any nToken and transfer logic in finalize which is unnecessary.
function setBalanceStorageForSettleCashDebt(
address account,
CashGroupParameters memory cashGroup,
int256 amountToSettleAsset,
AccountContext memory accountContext
) internal returns (int256) {
require(amountToSettleAsset >= 0); // dev: amount to settle negative
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, cashGroup.currencyId);
// Prevents settlement of positive balances
require(cashBalance < 0, "Invalid settle balance");
if (amountToSettleAsset == 0) {
// Symbolizes that the entire debt should be settled
amountToSettleAsset = cashBalance.neg();
cashBalance = 0;
} else {
// A partial settlement of the debt
require(amountToSettleAsset <= cashBalance.neg(), "Invalid amount to settle");
cashBalance = cashBalance.add(amountToSettleAsset);
}
// NOTE: we do not update HAS_CASH_DEBT here because it is possible that the other balances
// also have cash debts
if (cashBalance == 0 && nTokenBalance == 0) {
accountContext.setActiveCurrency(
cashGroup.currencyId,
false,
Constants.ACTIVE_IN_BALANCES
);
}
_setBalanceStorage(
account,
cashGroup.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, cashGroup.currencyId, amountToSettleAsset);
return amountToSettleAsset;
}
/**
* @notice A special balance storage method for fCash liquidation to reduce the bytecode size.
*/
function setBalanceStorageForfCashLiquidation(
address account,
AccountContext memory accountContext,
uint16 currencyId,
int256 netCashChange
) internal {
(int256 cashBalance, int256 nTokenBalance, uint256 lastClaimTime, uint256 accountIncentiveDebt) =
getBalanceStorage(account, currencyId);
int256 newCashBalance = cashBalance.add(netCashChange);
// If a cash balance is negative already we cannot put an account further into debt. In this case
// the netCashChange must be positive so that it is coming out of debt.
if (newCashBalance < 0) {
require(netCashChange > 0, "Neg Cash");
// NOTE: HAS_CASH_DEBT cannot be extinguished except by a free collateral check
// where all balances are examined. In this case the has cash debt flag should
// already be set (cash balances cannot get more negative) but we do it again
// here just to be safe.
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
bool isActive = newCashBalance != 0 || nTokenBalance != 0;
accountContext.setActiveCurrency(currencyId, isActive, Constants.ACTIVE_IN_BALANCES);
// Emit the event here, we do not call finalize
emit CashBalanceChange(account, currencyId, netCashChange);
_setBalanceStorage(
account,
currencyId,
newCashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
/// @notice Helper method for settling the output of the SettleAssets method
function finalizeSettleAmounts(
address account,
AccountContext memory accountContext,
SettleAmount[] memory settleAmounts
) internal {
for (uint256 i = 0; i < settleAmounts.length; i++) {
SettleAmount memory amt = settleAmounts[i];
if (amt.netCashChange == 0) continue;
(
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) = getBalanceStorage(account, amt.currencyId);
cashBalance = cashBalance.add(amt.netCashChange);
accountContext.setActiveCurrency(
amt.currencyId,
cashBalance != 0 || nTokenBalance != 0,
Constants.ACTIVE_IN_BALANCES
);
if (cashBalance < 0) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_CASH_DEBT;
}
emit CashBalanceChange(
account,
uint16(amt.currencyId),
amt.netCashChange
);
_setBalanceStorage(
account,
amt.currencyId,
cashBalance,
nTokenBalance,
lastClaimTime,
accountIncentiveDebt
);
}
}
/// @notice Special method for setting balance storage for nToken
function setBalanceStorageForNToken(
address nTokenAddress,
uint256 currencyId,
int256 cashBalance
) internal {
require(cashBalance >= 0); // dev: invalid nToken cash balance
_setBalanceStorage(nTokenAddress, currencyId, cashBalance, 0, 0, 0);
}
/// @notice increments fees to the reserve
function incrementFeeToReserve(uint256 currencyId, int256 fee) internal {
require(fee >= 0); // dev: invalid fee
// prettier-ignore
(int256 totalReserve, /* */, /* */, /* */) = getBalanceStorage(Constants.RESERVE, currencyId);
totalReserve = totalReserve.add(fee);
_setBalanceStorage(Constants.RESERVE, currencyId, totalReserve, 0, 0, 0);
emit ReserveFeeAccrued(uint16(currencyId), fee);
}
/// @notice harvests excess reserve balance
function harvestExcessReserveBalance(uint16 currencyId, int256 reserve, int256 assetInternalRedeemAmount) internal {
// parameters are validated by the caller
reserve = reserve.subNoNeg(assetInternalRedeemAmount);
_setBalanceStorage(Constants.RESERVE, currencyId, reserve, 0, 0, 0);
emit ExcessReserveBalanceHarvested(currencyId, assetInternalRedeemAmount);
}
/// @notice sets the reserve balance, see TreasuryAction.setReserveCashBalance
function setReserveCashBalance(uint16 currencyId, int256 newBalance) internal {
require(newBalance >= 0); // dev: invalid balance
_setBalanceStorage(Constants.RESERVE, currencyId, newBalance, 0, 0, 0);
emit ReserveBalanceUpdated(currencyId, newBalance);
}
/// @notice Sets internal balance storage.
function _setBalanceStorage(
address account,
uint256 currencyId,
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
) private {
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
require(cashBalance >= type(int88).min && cashBalance <= type(int88).max); // dev: stored cash balance overflow
// Allows for 12 quadrillion nToken balance in 1e8 decimals before overflow
require(nTokenBalance >= 0 && nTokenBalance <= type(uint80).max); // dev: stored nToken balance overflow
if (lastClaimTime == 0) {
// In this case the account has migrated and we set the accountIncentiveDebt
// The maximum NOTE supply is 100_000_000e8 (1e16) which is less than 2^56 (7.2e16) so we should never
// encounter an overflow for accountIncentiveDebt
require(accountIncentiveDebt <= type(uint56).max); // dev: account incentive debt overflow
balanceStorage.accountIncentiveDebt = uint56(accountIncentiveDebt);
} else {
// In this case the last claim time has not changed and we do not update the last integral supply
// (stored in the accountIncentiveDebt position)
require(lastClaimTime == balanceStorage.lastClaimTime);
}
balanceStorage.lastClaimTime = uint32(lastClaimTime);
balanceStorage.nTokenBalance = uint80(nTokenBalance);
balanceStorage.cashBalance = int88(cashBalance);
}
/// @notice Gets internal balance storage, nTokens are stored alongside cash balances
function getBalanceStorage(address account, uint256 currencyId)
internal
view
returns (
int256 cashBalance,
int256 nTokenBalance,
uint256 lastClaimTime,
uint256 accountIncentiveDebt
)
{
mapping(address => mapping(uint256 => BalanceStorage)) storage store = LibStorage.getBalanceStorage();
BalanceStorage storage balanceStorage = store[account][currencyId];
nTokenBalance = balanceStorage.nTokenBalance;
lastClaimTime = balanceStorage.lastClaimTime;
if (lastClaimTime > 0) {
// NOTE: this is only necessary to support the deprecated integral supply values, which are stored
// in the accountIncentiveDebt slot
accountIncentiveDebt = FloatingPoint56.unpackFrom56Bits(balanceStorage.accountIncentiveDebt);
} else {
accountIncentiveDebt = balanceStorage.accountIncentiveDebt;
}
cashBalance = balanceStorage.cashBalance;
}
/// @notice Loads a balance state memory object
/// @dev Balance state objects occupy a lot of memory slots, so this method allows
/// us to reuse them if possible
function loadBalanceState(
BalanceState memory balanceState,
address account,
uint16 currencyId,
AccountContext memory accountContext
) internal view {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
balanceState.currencyId = currencyId;
if (accountContext.isActiveInBalances(currencyId)) {
(
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
) = getBalanceStorage(account, currencyId);
} else {
balanceState.storedCashBalance = 0;
balanceState.storedNTokenBalance = 0;
balanceState.lastClaimTime = 0;
balanceState.accountIncentiveDebt = 0;
}
balanceState.netCashChange = 0;
balanceState.netAssetTransferInternalPrecision = 0;
balanceState.netNTokenTransfer = 0;
balanceState.netNTokenSupplyChange = 0;
}
/// @notice Used when manually claiming incentives in nTokenAction. Also sets the balance state
/// to storage to update the accountIncentiveDebt. lastClaimTime will be set to zero as accounts
/// are migrated to the new incentive calculation
function claimIncentivesManual(BalanceState memory balanceState, address account)
internal
returns (uint256 incentivesClaimed)
{
incentivesClaimed = Incentives.claimIncentives(
balanceState,
account,
balanceState.storedNTokenBalance.toUint()
);
_setBalanceStorage(
account,
balanceState.currencyId,
balanceState.storedCashBalance,
balanceState.storedNTokenBalance,
balanceState.lastClaimTime,
balanceState.accountIncentiveDebt
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TransferAssets.sol";
import "../valuation/AssetHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
/// @notice Handles the management of an array of assets including reading from storage, inserting
/// updating, deleting and writing back to storage.
library PortfolioHandler {
using SafeInt256 for int256;
using AssetHandler for PortfolioAsset;
// Mirror of LibStorage.MAX_PORTFOLIO_ASSETS
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @notice Primarily used by the TransferAssets library
function addMultipleAssets(PortfolioState memory portfolioState, PortfolioAsset[] memory assets)
internal
pure
{
for (uint256 i = 0; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
addAsset(
portfolioState,
asset.currencyId,
asset.maturity,
asset.assetType,
asset.notional
);
}
}
function _mergeAssetIntoArray(
PortfolioAsset[] memory assetArray,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) private pure returns (bool) {
for (uint256 i = 0; i < assetArray.length; i++) {
PortfolioAsset memory asset = assetArray[i];
if (
asset.assetType != assetType ||
asset.currencyId != currencyId ||
asset.maturity != maturity
) continue;
// Either of these storage states mean that some error in logic has occurred, we cannot
// store this portfolio
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: portfolio handler deleted storage
int256 newNotional = asset.notional.add(notional);
// Liquidity tokens cannot be reduced below zero.
if (AssetHandler.isLiquidityToken(assetType)) {
require(newNotional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(newNotional >= type(int88).min && newNotional <= type(int88).max); // dev: portfolio handler notional overflow
asset.notional = newNotional;
asset.storageState = AssetStorageState.Update;
return true;
}
return false;
}
/// @notice Adds an asset to a portfolio state in memory (does not write to storage)
/// @dev Ensures that only one version of an asset exists in a portfolio (i.e. does not allow two fCash assets of the same maturity
/// to exist in a single portfolio). Also ensures that liquidity tokens do not have a negative notional.
function addAsset(
PortfolioState memory portfolioState,
uint256 currencyId,
uint256 maturity,
uint256 assetType,
int256 notional
) internal pure {
if (
// Will return true if merged
_mergeAssetIntoArray(
portfolioState.storedAssets,
currencyId,
maturity,
assetType,
notional
)
) return;
if (portfolioState.lastNewAssetIndex > 0) {
bool merged = _mergeAssetIntoArray(
portfolioState.newAssets,
currencyId,
maturity,
assetType,
notional
);
if (merged) return;
}
// At this point if we have not merged the asset then append to the array
// Cannot remove liquidity that the portfolio does not have
if (AssetHandler.isLiquidityToken(assetType)) {
require(notional >= 0); // dev: portfolio handler negative liquidity token balance
}
require(notional >= type(int88).min && notional <= type(int88).max); // dev: portfolio handler notional overflow
// Need to provision a new array at this point
if (portfolioState.lastNewAssetIndex == portfolioState.newAssets.length) {
portfolioState.newAssets = _extendNewAssetArray(portfolioState.newAssets);
}
// Otherwise add to the new assets array. It should not be possible to add matching assets in a single transaction, we will
// check this again when we write to storage. Assigning to memory directly here, do not allocate new memory via struct.
PortfolioAsset memory newAsset = portfolioState.newAssets[portfolioState.lastNewAssetIndex];
newAsset.currencyId = currencyId;
newAsset.maturity = maturity;
newAsset.assetType = assetType;
newAsset.notional = notional;
newAsset.storageState = AssetStorageState.NoChange;
portfolioState.lastNewAssetIndex += 1;
}
/// @dev Extends the new asset array if it is not large enough, this is likely to get a bit expensive if we do
/// it too much
function _extendNewAssetArray(PortfolioAsset[] memory newAssets)
private
pure
returns (PortfolioAsset[] memory)
{
// Double the size of the new asset array every time we have to extend to reduce the number of times
// that we have to extend it. This will go: 0, 1, 2, 4, 8 (probably stops there).
uint256 newLength = newAssets.length == 0 ? 1 : newAssets.length * 2;
PortfolioAsset[] memory extendedArray = new PortfolioAsset[](newLength);
for (uint256 i = 0; i < newAssets.length; i++) {
extendedArray[i] = newAssets[i];
}
return extendedArray;
}
/// @notice Takes a portfolio state and writes it to storage.
/// @dev This method should only be called directly by the nToken. Account updates to portfolios should happen via
/// the storeAssetsAndUpdateContext call in the AccountContextHandler.sol library.
/// @return updated variables to update the account context with
/// hasDebt: whether or not the portfolio has negative fCash assets
/// portfolioActiveCurrencies: a byte32 word with all the currencies in the portfolio
/// uint8: the length of the storage array
/// uint40: the new nextSettleTime for the portfolio
function storeAssets(PortfolioState memory portfolioState, address account)
internal
returns (
bool,
bytes32,
uint8,
uint40
)
{
bool hasDebt;
// NOTE: cannot have more than 16 assets or this byte object will overflow. Max assets is
// set to 7 and the worst case during liquidation would be 7 liquidity tokens that generate
// 7 additional fCash assets for a total of 14 assets. Although even in this case all assets
// would be of the same currency so it would not change the end result of the active currency
// calculation.
bytes32 portfolioActiveCurrencies;
uint256 nextSettleTime;
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// NOTE: this is to prevent the storage of assets that have been modified in the AssetHandler
// during valuation.
require(asset.storageState != AssetStorageState.RevertIfStored);
// Mark any zero notional assets as deleted
if (asset.storageState != AssetStorageState.Delete && asset.notional == 0) {
deleteAsset(portfolioState, i);
}
}
// First delete assets from asset storage to maintain asset storage indexes
for (uint256 i = 0; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
if (asset.storageState == AssetStorageState.Delete) {
// Delete asset from storage
uint256 currentSlot = asset.storageSlot;
assembly {
sstore(currentSlot, 0x00)
}
} else {
if (asset.storageState == AssetStorageState.Update) {
PortfolioAssetStorage storage assetStorage;
uint256 currentSlot = asset.storageSlot;
assembly {
assetStorage.slot := currentSlot
}
_storeAsset(asset, assetStorage);
}
// Update portfolio context for every asset that is in storage, whether it is
// updated in storage or not.
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
}
}
// Add new assets
uint256 assetStorageLength = portfolioState.storedAssetLength;
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
for (uint256 i = 0; i < portfolioState.newAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.newAssets[i];
if (asset.notional == 0) continue;
require(
asset.storageState != AssetStorageState.Delete &&
asset.storageState != AssetStorageState.RevertIfStored
); // dev: store assets deleted storage
(hasDebt, portfolioActiveCurrencies, nextSettleTime) = _updatePortfolioContext(
asset,
hasDebt,
portfolioActiveCurrencies,
nextSettleTime
);
_storeAsset(asset, storageArray[assetStorageLength]);
assetStorageLength += 1;
}
// 16 is the maximum number of assets or portfolio active currencies will overflow at 32 bytes with
// 2 bytes per currency
require(assetStorageLength <= 16 && nextSettleTime <= type(uint40).max); // dev: portfolio return value overflow
return (
hasDebt,
portfolioActiveCurrencies,
uint8(assetStorageLength),
uint40(nextSettleTime)
);
}
/// @notice Updates context information during the store assets method
function _updatePortfolioContext(
PortfolioAsset memory asset,
bool hasDebt,
bytes32 portfolioActiveCurrencies,
uint256 nextSettleTime
)
private
pure
returns (
bool,
bytes32,
uint256
)
{
uint256 settlementDate = asset.getSettlementDate();
// Tis will set it to the minimum settlement date
if (nextSettleTime == 0 || nextSettleTime > settlementDate) {
nextSettleTime = settlementDate;
}
hasDebt = hasDebt || asset.notional < 0;
require(uint16(uint256(portfolioActiveCurrencies)) == 0); // dev: portfolio active currencies overflow
portfolioActiveCurrencies = (portfolioActiveCurrencies >> 16) | (bytes32(asset.currencyId) << 240);
return (hasDebt, portfolioActiveCurrencies, nextSettleTime);
}
/// @dev Encodes assets for storage
function _storeAsset(
PortfolioAsset memory asset,
PortfolioAssetStorage storage assetStorage
) internal {
require(0 < asset.currencyId && asset.currencyId <= Constants.MAX_CURRENCIES); // dev: encode asset currency id overflow
require(0 < asset.maturity && asset.maturity <= type(uint40).max); // dev: encode asset maturity overflow
require(0 < asset.assetType && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: encode asset type invalid
require(type(int88).min <= asset.notional && asset.notional <= type(int88).max); // dev: encode asset notional overflow
assetStorage.currencyId = uint16(asset.currencyId);
assetStorage.maturity = uint40(asset.maturity);
assetStorage.assetType = uint8(asset.assetType);
assetStorage.notional = int88(asset.notional);
}
/// @notice Deletes an asset from a portfolio
/// @dev This method should only be called during settlement, assets can only be removed from a portfolio before settlement
/// by adding the offsetting negative position
function deleteAsset(PortfolioState memory portfolioState, uint256 index) internal pure {
require(index < portfolioState.storedAssets.length); // dev: stored assets bounds
require(portfolioState.storedAssetLength > 0); // dev: stored assets length is zero
PortfolioAsset memory assetToDelete = portfolioState.storedAssets[index];
require(
assetToDelete.storageState != AssetStorageState.Delete &&
assetToDelete.storageState != AssetStorageState.RevertIfStored
); // dev: cannot delete asset
portfolioState.storedAssetLength -= 1;
uint256 maxActiveSlotIndex;
uint256 maxActiveSlot;
// The max active slot is the last storage slot where an asset exists, it's not clear where this will be in the
// array so we search for it here.
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory a = portfolioState.storedAssets[i];
if (a.storageSlot > maxActiveSlot && a.storageState != AssetStorageState.Delete) {
maxActiveSlot = a.storageSlot;
maxActiveSlotIndex = i;
}
}
if (index == maxActiveSlotIndex) {
// In this case we are deleting the asset with the max storage slot so no swap is necessary.
assetToDelete.storageState = AssetStorageState.Delete;
return;
}
// Swap the storage slots of the deleted asset with the last non-deleted asset in the array. Mark them accordingly
// so that when we call store assets they will be updated appropriately
PortfolioAsset memory assetToSwap = portfolioState.storedAssets[maxActiveSlotIndex];
(
assetToSwap.storageSlot,
assetToDelete.storageSlot
) = (
assetToDelete.storageSlot,
assetToSwap.storageSlot
);
assetToSwap.storageState = AssetStorageState.Update;
assetToDelete.storageState = AssetStorageState.Delete;
}
/// @notice Returns a portfolio array, will be sorted
function getSortedPortfolio(address account, uint8 assetArrayLength)
internal
view
returns (PortfolioAsset[] memory)
{
PortfolioAsset[] memory assets = _loadAssetArray(account, assetArrayLength);
// No sorting required for length of 1
if (assets.length <= 1) return assets;
_sortInPlace(assets);
return assets;
}
/// @notice Builds a portfolio array from storage. The new assets hint parameter will
/// be used to provision a new array for the new assets. This will increase gas efficiency
/// so that we don't have to make copies when we extend the array.
function buildPortfolioState(
address account,
uint8 assetArrayLength,
uint256 newAssetsHint
) internal view returns (PortfolioState memory) {
PortfolioState memory state;
if (assetArrayLength == 0) return state;
state.storedAssets = getSortedPortfolio(account, assetArrayLength);
state.storedAssetLength = assetArrayLength;
state.newAssets = new PortfolioAsset[](newAssetsHint);
return state;
}
function _sortInPlace(PortfolioAsset[] memory assets) private pure {
uint256 length = assets.length;
uint256[] memory ids = new uint256[](length);
for (uint256 k; k < length; k++) {
PortfolioAsset memory asset = assets[k];
// Prepopulate the ids to calculate just once
ids[k] = TransferAssets.encodeAssetId(asset.currencyId, asset.maturity, asset.assetType);
}
// Uses insertion sort
uint256 i = 1;
while (i < length) {
uint256 j = i;
while (j > 0 && ids[j - 1] > ids[j]) {
// Swap j - 1 and j
(ids[j - 1], ids[j]) = (ids[j], ids[j - 1]);
(assets[j - 1], assets[j]) = (assets[j], assets[j - 1]);
j--;
}
i++;
}
}
function _loadAssetArray(address account, uint8 length)
private
view
returns (PortfolioAsset[] memory)
{
// This will overflow the storage pointer
require(length <= MAX_PORTFOLIO_ASSETS);
mapping(address =>
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store = LibStorage.getPortfolioArrayStorage();
PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS] storage storageArray = store[account];
PortfolioAsset[] memory assets = new PortfolioAsset[](length);
for (uint256 i = 0; i < length; i++) {
PortfolioAssetStorage storage assetStorage = storageArray[i];
PortfolioAsset memory asset = assets[i];
uint256 slot;
assembly {
slot := assetStorage.slot
}
asset.currencyId = assetStorage.currencyId;
asset.maturity = assetStorage.maturity;
asset.assetType = assetStorage.assetType;
asset.notional = assetStorage.notional;
asset.storageSlot = slot;
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "./balances/BalanceHandler.sol";
import "./portfolio/BitmapAssetsHandler.sol";
import "./portfolio/PortfolioHandler.sol";
library AccountContextHandler {
using PortfolioHandler for PortfolioState;
bytes18 private constant TURN_OFF_PORTFOLIO_FLAGS = 0x7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF7FFF;
event AccountContextUpdate(address indexed account);
/// @notice Returns the account context of a given account
function getAccountContext(address account) internal view returns (AccountContext memory) {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
return store[account];
}
/// @notice Sets the account context of a given account
function setAccountContext(AccountContext memory accountContext, address account) internal {
mapping(address => AccountContext) storage store = LibStorage.getAccountStorage();
store[account] = accountContext;
emit AccountContextUpdate(account);
}
function isBitmapEnabled(AccountContext memory accountContext) internal pure returns (bool) {
return accountContext.bitmapCurrencyId != 0;
}
/// @notice Enables a bitmap type portfolio for an account. A bitmap type portfolio allows
/// an account to hold more fCash than a normal portfolio, except only in a single currency.
/// Once enabled, it cannot be disabled or changed. An account can only enable a bitmap if
/// it has no assets or debt so that we ensure no assets are left stranded.
/// @param accountContext refers to the account where the bitmap will be enabled
/// @param currencyId the id of the currency to enable
/// @param blockTime the current block time to set the next settle time
function enableBitmapForAccount(
AccountContext memory accountContext,
uint16 currencyId,
uint256 blockTime
) internal view {
require(!isBitmapEnabled(accountContext), "Cannot change bitmap");
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES, "Invalid currency id");
// Account cannot have assets or debts
require(accountContext.assetArrayLength == 0, "Cannot have assets");
require(accountContext.hasDebt == 0x00, "Cannot have debt");
// Ensure that the active currency is set to false in the array so that there is no double
// counting during FreeCollateral
setActiveCurrency(accountContext, currencyId, false, Constants.ACTIVE_IN_BALANCES);
accountContext.bitmapCurrencyId = currencyId;
// Setting this is required to initialize the assets bitmap
uint256 nextSettleTime = DateTime.getTimeUTC0(blockTime);
require(nextSettleTime < type(uint40).max); // dev: blockTime overflow
accountContext.nextSettleTime = uint40(nextSettleTime);
}
/// @notice Returns true if the context needs to settle
function mustSettleAssets(AccountContext memory accountContext) internal view returns (bool) {
uint256 blockTime = block.timestamp;
if (isBitmapEnabled(accountContext)) {
// nextSettleTime will be set to utc0 after settlement so we
// settle if this is strictly less than utc0
return accountContext.nextSettleTime < DateTime.getTimeUTC0(blockTime);
} else {
// 0 value occurs on an uninitialized account
// Assets mature exactly on the blockTime (not one second past) so in this
// case we settle on the block timestamp
return 0 < accountContext.nextSettleTime && accountContext.nextSettleTime <= blockTime;
}
}
/// @notice Checks if a currency id (uint16 max) is in the 9 slots in the account
/// context active currencies list.
/// @dev NOTE: this may be more efficient as a binary search since we know that the array
/// is sorted
function isActiveInBalances(AccountContext memory accountContext, uint256 currencyId)
internal
pure
returns (bool)
{
require(currencyId != 0 && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
bytes18 currencies = accountContext.activeCurrencies;
if (accountContext.bitmapCurrencyId == currencyId) return true;
while (currencies != 0x00) {
uint256 cid = uint16(bytes2(currencies) & Constants.UNMASK_FLAGS);
if (cid == currencyId) {
// Currency found, return if it is active in balances or not
return bytes2(currencies) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES;
}
currencies = currencies << 16;
}
return false;
}
/// @notice Iterates through the active currency list and removes, inserts or does nothing
/// to ensure that the active currency list is an ordered byte array of uint16 currency ids
/// that refer to the currencies that an account is active in.
///
/// This is called to ensure that currencies are active when the account has a non zero cash balance,
/// a non zero nToken balance or a portfolio asset.
function setActiveCurrency(
AccountContext memory accountContext,
uint256 currencyId,
bool isActive,
bytes2 flags
) internal pure {
require(0 < currencyId && currencyId <= Constants.MAX_CURRENCIES); // dev: invalid currency id
// If the bitmapped currency is already set then return here. Turning off the bitmap currency
// id requires other logical handling so we will do it elsewhere.
if (isActive && accountContext.bitmapCurrencyId == currencyId) return;
bytes18 prefix;
bytes18 suffix = accountContext.activeCurrencies;
uint256 shifts;
/// There are six possible outcomes from this search:
/// 1. The currency id is in the list
/// - it must be set to active, do nothing
/// - it must be set to inactive, shift suffix and concatenate
/// 2. The current id is greater than the one in the search:
/// - it must be set to active, append to prefix and then concatenate the suffix,
/// ensure that we do not lose the last 2 bytes if set.
/// - it must be set to inactive, it is not in the list, do nothing
/// 3. Reached the end of the list:
/// - it must be set to active, check that the last two bytes are not set and then
/// append to the prefix
/// - it must be set to inactive, do nothing
while (suffix != 0x00) {
uint256 cid = uint256(uint16(bytes2(suffix) & Constants.UNMASK_FLAGS));
// if matches and isActive then return, already in list
if (cid == currencyId && isActive) {
// set flag and return
accountContext.activeCurrencies =
accountContext.activeCurrencies |
(bytes18(flags) >> (shifts * 16));
return;
}
// if matches and not active then shift suffix to remove
if (cid == currencyId && !isActive) {
// turn off flag, if both flags are off then remove
suffix = suffix & ~bytes18(flags);
if (bytes2(suffix) & ~Constants.UNMASK_FLAGS == 0x0000) suffix = suffix << 16;
accountContext.activeCurrencies = prefix | (suffix >> (shifts * 16));
return;
}
// if greater than and isActive then insert into prefix
if (cid > currencyId && isActive) {
prefix = prefix | (bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
// check that the total length is not greater than 9, meaning that the last
// two bytes of the active currencies array should be zero
require((accountContext.activeCurrencies << 128) == 0x00); // dev: AC: too many currencies
// append the suffix
accountContext.activeCurrencies = prefix | (suffix >> ((shifts + 1) * 16));
return;
}
// if past the point of the currency id and not active, not in list
if (cid > currencyId && !isActive) return;
prefix = prefix | (bytes18(bytes2(suffix)) >> (shifts * 16));
suffix = suffix << 16;
shifts += 1;
}
// If reached this point and not active then return
if (!isActive) return;
// if end and isActive then insert into suffix, check max length
require(shifts < 9); // dev: AC: too many currencies
accountContext.activeCurrencies =
prefix |
(bytes18(bytes2(uint16(currencyId)) | flags) >> (shifts * 16));
}
function _clearPortfolioActiveFlags(bytes18 activeCurrencies) internal pure returns (bytes18) {
bytes18 result;
// This is required to clear the suffix as we append below
bytes18 suffix = activeCurrencies & TURN_OFF_PORTFOLIO_FLAGS;
uint256 shifts;
// This loop will append all currencies that are active in balances into the result.
while (suffix != 0x00) {
if (bytes2(suffix) & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
// If any flags are active, then append.
result = result | (bytes18(bytes2(suffix)) >> shifts);
shifts += 16;
}
suffix = suffix << 16;
}
return result;
}
/// @notice Stores a portfolio array and updates the account context information, this method should
/// be used whenever updating a portfolio array except in the case of nTokens
function storeAssetsAndUpdateContext(
AccountContext memory accountContext,
address account,
PortfolioState memory portfolioState,
bool isLiquidation
) internal {
// Each of these parameters is recalculated based on the entire array of assets in store assets,
// regardless of whether or not they have been updated.
(bool hasDebt, bytes32 portfolioCurrencies, uint8 assetArrayLength, uint40 nextSettleTime) =
portfolioState.storeAssets(account);
accountContext.nextSettleTime = nextSettleTime;
require(mustSettleAssets(accountContext) == false); // dev: cannot store matured assets
accountContext.assetArrayLength = assetArrayLength;
// During liquidation it is possible for an array to go over the max amount of assets allowed due to
// liquidity tokens being withdrawn into fCash.
if (!isLiquidation) {
require(assetArrayLength <= uint8(Constants.MAX_TRADED_MARKET_INDEX)); // dev: max assets allowed
}
// Sets the hasDebt flag properly based on whether or not portfolio has asset debt, meaning
// a negative fCash balance.
if (hasDebt) {
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
} else {
// Turns off the ASSET_DEBT flag
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
}
// Clear the active portfolio active flags and they will be recalculated in the next step
accountContext.activeCurrencies = _clearPortfolioActiveFlags(accountContext.activeCurrencies);
uint256 lastCurrency;
while (portfolioCurrencies != 0) {
// Portfolio currencies will not have flags, it is just an byte array of all the currencies found
// in a portfolio. They are appended in a sorted order so we can compare to the previous currency
// and only set it if they are different.
uint256 currencyId = uint16(bytes2(portfolioCurrencies));
if (currencyId != lastCurrency) {
setActiveCurrency(accountContext, currencyId, true, Constants.ACTIVE_IN_PORTFOLIO);
}
lastCurrency = currencyId;
portfolioCurrencies = portfolioCurrencies << 16;
}
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
interface NotionalCallback {
function notionalCallback(address sender, address account, bytes calldata callbackdata) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetRate.sol";
import "./CashGroup.sol";
import "./DateTime.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Market {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
// Max positive value for a ABDK64x64 integer
int256 private constant MAX64 = 0x7FFFFFFFFFFFFFFF;
/// @notice Add liquidity to a market, assuming that it is initialized. If not then
/// this method will revert and the market must be initialized first.
/// Return liquidityTokens and negative fCash to the portfolio
function addLiquidity(MarketParameters memory market, int256 assetCash)
internal
returns (int256 liquidityTokens, int256 fCash)
{
require(market.totalLiquidity > 0, "M: zero liquidity");
if (assetCash == 0) return (0, 0);
require(assetCash > 0); // dev: negative asset cash
liquidityTokens = market.totalLiquidity.mul(assetCash).div(market.totalAssetCash);
// No need to convert this to underlying, assetCash / totalAssetCash is a unitless proportion.
fCash = market.totalfCash.mul(assetCash).div(market.totalAssetCash);
market.totalLiquidity = market.totalLiquidity.add(liquidityTokens);
market.totalfCash = market.totalfCash.add(fCash);
market.totalAssetCash = market.totalAssetCash.add(assetCash);
_setMarketStorageForLiquidity(market);
// Flip the sign to represent the LP's net position
fCash = fCash.neg();
}
/// @notice Remove liquidity from a market, assuming that it is initialized.
/// Return assetCash and positive fCash to the portfolio
function removeLiquidity(MarketParameters memory market, int256 tokensToRemove)
internal
returns (int256 assetCash, int256 fCash)
{
if (tokensToRemove == 0) return (0, 0);
require(tokensToRemove > 0); // dev: negative tokens to remove
assetCash = market.totalAssetCash.mul(tokensToRemove).div(market.totalLiquidity);
fCash = market.totalfCash.mul(tokensToRemove).div(market.totalLiquidity);
market.totalLiquidity = market.totalLiquidity.subNoNeg(tokensToRemove);
market.totalfCash = market.totalfCash.subNoNeg(fCash);
market.totalAssetCash = market.totalAssetCash.subNoNeg(assetCash);
_setMarketStorageForLiquidity(market);
}
function executeTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal returns (int256 netAssetCash) {
int256 netAssetCashToReserve;
(netAssetCash, netAssetCashToReserve) = calculateTrade(
market,
cashGroup,
fCashToAccount,
timeToMaturity,
marketIndex
);
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
BalanceHandler.incrementFeeToReserve(cashGroup.currencyId, netAssetCashToReserve);
}
/// @notice Calculates the asset cash amount the results from trading fCashToAccount with the market. A positive
/// fCashToAccount is equivalent of lending, a negative is borrowing. Updates the market state in memory.
/// @param market the current market state
/// @param cashGroup cash group configuration parameters
/// @param fCashToAccount the fCash amount that will be deposited into the user's portfolio. The net change
/// to the market is in the opposite direction.
/// @param timeToMaturity number of seconds until maturity
/// @return netAssetCash, netAssetCashToReserve
function calculateTrade(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
int256 fCashToAccount,
uint256 timeToMaturity,
uint256 marketIndex
) internal view returns (int256, int256) {
// We return false if there is not enough fCash to support this trade.
// if fCashToAccount > 0 and totalfCash - fCashToAccount <= 0 then the trade will fail
// if fCashToAccount < 0 and totalfCash > 0 then this will always pass
if (market.totalfCash <= fCashToAccount) return (0, 0);
// Calculates initial rate factors for the trade
(int256 rateScalar, int256 totalCashUnderlying, int256 rateAnchor) =
getExchangeRateFactors(market, cashGroup, timeToMaturity, marketIndex);
// Calculates the exchange rate from cash to fCash before any liquidity fees
// are applied
int256 preFeeExchangeRate;
{
bool success;
(preFeeExchangeRate, success) = _getExchangeRate(
market.totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashToAccount
);
if (!success) return (0, 0);
}
// Given the exchange rate, returns the net cash amounts to apply to each of the
// three relevant balances.
(int256 netCashToAccount, int256 netCashToMarket, int256 netCashToReserve) =
_getNetCashAmountsUnderlying(
cashGroup,
preFeeExchangeRate,
fCashToAccount,
timeToMaturity
);
// Signifies a failed net cash amount calculation
if (netCashToAccount == 0) return (0, 0);
{
// Set the new implied interest rate after the trade has taken effect, this
// will be used to calculate the next trader's interest rate.
market.totalfCash = market.totalfCash.subNoNeg(fCashToAccount);
market.lastImpliedRate = getImpliedRate(
market.totalfCash,
totalCashUnderlying.add(netCashToMarket),
rateScalar,
rateAnchor,
timeToMaturity
);
// It's technically possible that the implied rate is actually exactly zero (or
// more accurately the natural log rounds down to zero) but we will still fail
// in this case. If this does happen we may assume that markets are not initialized.
if (market.lastImpliedRate == 0) return (0, 0);
}
return
_setNewMarketState(
market,
cashGroup.assetRate,
netCashToAccount,
netCashToMarket,
netCashToReserve
);
}
/// @notice Returns factors for calculating exchange rates
/// @return
/// rateScalar: a scalar value in rate precision that defines the slope of the line
/// totalCashUnderlying: the converted asset cash to underlying cash for calculating
/// the exchange rates for the trade
/// rateAnchor: an offset from the x axis to maintain interest rate continuity over time
function getExchangeRateFactors(
MarketParameters memory market,
CashGroupParameters memory cashGroup,
uint256 timeToMaturity,
uint256 marketIndex
)
internal
pure
returns (
int256,
int256,
int256
)
{
int256 rateScalar = cashGroup.getRateScalar(marketIndex, timeToMaturity);
int256 totalCashUnderlying = cashGroup.assetRate.convertToUnderlying(market.totalAssetCash);
// This would result in a divide by zero
if (market.totalfCash == 0 || totalCashUnderlying == 0) return (0, 0, 0);
// Get the rate anchor given the market state, this will establish the baseline for where
// the exchange rate is set.
int256 rateAnchor;
{
bool success;
(rateAnchor, success) = _getRateAnchor(
market.totalfCash,
market.lastImpliedRate,
totalCashUnderlying,
rateScalar,
timeToMaturity
);
if (!success) return (0, 0, 0);
}
return (rateScalar, totalCashUnderlying, rateAnchor);
}
/// @dev Returns net asset cash amounts to the account, the market and the reserve
/// @return
/// netCashToAccount: this is a positive or negative amount of cash change to the account
/// netCashToMarket: this is a positive or negative amount of cash change in the market
// netCashToReserve: this is always a positive amount of cash accrued to the reserve
function _getNetCashAmountsUnderlying(
CashGroupParameters memory cashGroup,
int256 preFeeExchangeRate,
int256 fCashToAccount,
uint256 timeToMaturity
)
private
pure
returns (
int256,
int256,
int256
)
{
// Fees are specified in basis points which is an rate precision denomination. We convert this to
// an exchange rate denomination for the given time to maturity. (i.e. get e^(fee * t) and multiply
// or divide depending on the side of the trade).
// tradeExchangeRate = exp((tradeInterestRateNoFee +/- fee) * timeToMaturity)
// tradeExchangeRate = tradeExchangeRateNoFee (* or /) exp(fee * timeToMaturity)
// cash = fCash / exchangeRate, exchangeRate > 1
int256 preFeeCashToAccount =
fCashToAccount.divInRatePrecision(preFeeExchangeRate).neg();
int256 fee = getExchangeRateFromImpliedRate(cashGroup.getTotalFee(), timeToMaturity);
if (fCashToAccount > 0) {
// Lending
// Dividing reduces exchange rate, lending should receive less fCash for cash
int256 postFeeExchangeRate = preFeeExchangeRate.divInRatePrecision(fee);
// It's possible that the fee pushes exchange rates into negative territory. This is not possible
// when borrowing. If this happens then the trade has failed.
if (postFeeExchangeRate < Constants.RATE_PRECISION) return (0, 0, 0);
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate / feeExchangeRate
// preFeeCashToAccount = -(fCashToAccount / preFeeExchangeRate)
// postFeeCashToAccount = -(fCashToAccount / postFeeExchangeRate)
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount * feeExchangeRate) / preFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (feeExchangeRate - 1)
// netFee = -(preFeeCashToAccount) * (feeExchangeRate - 1)
// netFee = preFeeCashToAccount * (1 - feeExchangeRate)
// RATE_PRECISION - fee will be negative here, preFeeCashToAccount < 0, fee > 0
fee = preFeeCashToAccount.mulInRatePrecision(Constants.RATE_PRECISION.sub(fee));
} else {
// Borrowing
// cashToAccount = -(fCashToAccount / exchangeRate)
// postFeeExchangeRate = preFeeExchangeRate * feeExchangeRate
// netFee = preFeeCashToAccount - postFeeCashToAccount
// netFee = (fCashToAccount / postFeeExchangeRate) - (fCashToAccount / preFeeExchangeRate)
// netFee = ((fCashToAccount / (feeExchangeRate * preFeeExchangeRate)) - (fCashToAccount / preFeeExchangeRate)
// netFee = (fCashToAccount / preFeeExchangeRate) * (1 / feeExchangeRate - 1)
// netFee = preFeeCashToAccount * ((1 - feeExchangeRate) / feeExchangeRate)
// NOTE: preFeeCashToAccount is negative in this branch so we negate it to ensure that fee is a positive number
// preFee * (1 - fee) / fee will be negative, use neg() to flip to positive
// RATE_PRECISION - fee will be negative
fee = preFeeCashToAccount.mul(Constants.RATE_PRECISION.sub(fee)).div(fee).neg();
}
int256 cashToReserve =
fee.mul(cashGroup.getReserveFeeShare()).div(Constants.PERCENTAGE_DECIMALS);
return (
// postFeeCashToAccount = preFeeCashToAccount - fee
preFeeCashToAccount.sub(fee),
// netCashToMarket = -(preFeeCashToAccount - fee + cashToReserve)
(preFeeCashToAccount.sub(fee).add(cashToReserve)).neg(),
cashToReserve
);
}
/// @notice Sets the new market state
/// @return
/// netAssetCashToAccount: the positive or negative change in asset cash to the account
/// assetCashToReserve: the positive amount of cash that accrues to the reserve
function _setNewMarketState(
MarketParameters memory market,
AssetRateParameters memory assetRate,
int256 netCashToAccount,
int256 netCashToMarket,
int256 netCashToReserve
) private view returns (int256, int256) {
int256 netAssetCashToMarket = assetRate.convertFromUnderlying(netCashToMarket);
// Set storage checks that total asset cash is above zero
market.totalAssetCash = market.totalAssetCash.add(netAssetCashToMarket);
// Sets the trade time for the next oracle update
market.previousTradeTime = block.timestamp;
int256 assetCashToReserve = assetRate.convertFromUnderlying(netCashToReserve);
int256 netAssetCashToAccount = assetRate.convertFromUnderlying(netCashToAccount);
return (netAssetCashToAccount, assetCashToReserve);
}
/// @notice Rate anchors update as the market gets closer to maturity. Rate anchors are not comparable
/// across time or markets but implied rates are. The goal here is to ensure that the implied rate
/// before and after the rate anchor update is the same. Therefore, the market will trade at the same implied
/// rate that it last traded at. If these anchors do not update then it opens up the opportunity for arbitrage
/// which will hurt the liquidity providers.
///
/// The rate anchor will update as the market rolls down to maturity. The calculation is:
/// newExchangeRate = e^(lastImpliedRate * timeToMaturity / Constants.IMPLIED_RATE_TIME)
/// newAnchor = newExchangeRate - ln((proportion / (1 - proportion)) / rateScalar
///
/// where:
/// lastImpliedRate = ln(exchangeRate') * (Constants.IMPLIED_RATE_TIME / timeToMaturity')
/// (calculated when the last trade in the market was made)
/// @return the new rate anchor and a boolean that signifies success
function _getRateAnchor(
int256 totalfCash,
uint256 lastImpliedRate,
int256 totalCashUnderlying,
int256 rateScalar,
uint256 timeToMaturity
) internal pure returns (int256, bool) {
// This is the exchange rate at the new time to maturity
int256 newExchangeRate = getExchangeRateFromImpliedRate(lastImpliedRate, timeToMaturity);
if (newExchangeRate < Constants.RATE_PRECISION) return (0, false);
int256 rateAnchor;
{
// totalfCash / (totalfCash + totalCashUnderlying)
int256 proportion =
totalfCash.divInRatePrecision(totalfCash.add(totalCashUnderlying));
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// newExchangeRate - ln(proportion / (1 - proportion)) / rateScalar
rateAnchor = newExchangeRate.sub(lnProportion.divInRatePrecision(rateScalar));
}
return (rateAnchor, true);
}
/// @notice Calculates the current market implied rate.
/// @return the implied rate and a bool that is true on success
function getImpliedRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
uint256 timeToMaturity
) internal pure returns (uint256) {
// This will check for exchange rates < Constants.RATE_PRECISION
(int256 exchangeRate, bool success) =
_getExchangeRate(totalfCash, totalCashUnderlying, rateScalar, rateAnchor, 0);
if (!success) return 0;
// Uses continuous compounding to calculate the implied rate:
// ln(exchangeRate) * Constants.IMPLIED_RATE_TIME / timeToMaturity
int128 rate = ABDKMath64x64.fromInt(exchangeRate);
// Scales down to a floating point for LN
int128 rateScaled = ABDKMath64x64.div(rate, Constants.RATE_PRECISION_64x64);
// We will not have a negative log here because we check that exchangeRate > Constants.RATE_PRECISION
// inside getExchangeRate
int128 lnRateScaled = ABDKMath64x64.ln(rateScaled);
// Scales up to a fixed point
uint256 lnRate =
ABDKMath64x64.toUInt(ABDKMath64x64.mul(lnRateScaled, Constants.RATE_PRECISION_64x64));
// lnRate * IMPLIED_RATE_TIME / ttm
uint256 impliedRate = lnRate.mul(Constants.IMPLIED_RATE_TIME).div(timeToMaturity);
// Implied rates over 429% will overflow, this seems like a safe assumption
if (impliedRate > type(uint32).max) return 0;
return impliedRate;
}
/// @notice Converts an implied rate to an exchange rate given a time to maturity. The
/// formula is E = e^rt
function getExchangeRateFromImpliedRate(uint256 impliedRate, uint256 timeToMaturity)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(
impliedRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME)
);
int128 expValueScaled = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
int128 expResult = ABDKMath64x64.exp(expValueScaled);
int128 expResultScaled = ABDKMath64x64.mul(expResult, Constants.RATE_PRECISION_64x64);
return ABDKMath64x64.toInt(expResultScaled);
}
/// @notice Returns the exchange rate between fCash and cash for the given market
/// Calculates the following exchange rate:
/// (1 / rateScalar) * ln(proportion / (1 - proportion)) + rateAnchor
/// where:
/// proportion = totalfCash / (totalfCash + totalUnderlyingCash)
/// @dev has an underscore to denote as private but is marked internal for the mock
function _getExchangeRate(
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 fCashToAccount
) internal pure returns (int256, bool) {
int256 numerator = totalfCash.subNoNeg(fCashToAccount);
// This is the proportion scaled by Constants.RATE_PRECISION
// (totalfCash + fCash) / (totalfCash + totalCashUnderlying)
int256 proportion =
numerator.divInRatePrecision(totalfCash.add(totalCashUnderlying));
// This limit is here to prevent the market from reaching extremely high interest rates via an
// excessively large proportion (high amounts of fCash relative to cash).
// Market proportion can only increase via borrowing (fCash is added to the market and cash is
// removed). Over time, the returns from asset cash will slightly decrease the proportion (the
// value of cash underlying in the market must be monotonically increasing). Therefore it is not
// possible for the proportion to go over max market proportion unless borrowing occurs.
if (proportion > Constants.MAX_MARKET_PROPORTION) return (0, false);
(int256 lnProportion, bool success) = _logProportion(proportion);
if (!success) return (0, false);
// lnProportion / rateScalar + rateAnchor
int256 rate = lnProportion.divInRatePrecision(rateScalar).add(rateAnchor);
// Do not succeed if interest rates fall below 1
if (rate < Constants.RATE_PRECISION) {
return (0, false);
} else {
return (rate, true);
}
}
/// @dev This method calculates the log of the proportion inside the logit function which is
/// defined as ln(proportion / (1 - proportion)). Special handling here is required to deal with
/// fixed point precision and the ABDK library.
function _logProportion(int256 proportion) internal pure returns (int256, bool) {
// This will result in divide by zero, short circuit
if (proportion == Constants.RATE_PRECISION) return (0, false);
// Convert proportion to what is used inside the logit function (p / (1-p))
int256 logitP = proportion.divInRatePrecision(Constants.RATE_PRECISION.sub(proportion));
// ABDK does not handle log of numbers that are less than 1, in order to get the right value
// scaled by RATE_PRECISION we use the log identity:
// (ln(logitP / RATE_PRECISION)) * RATE_PRECISION = (ln(logitP) - ln(RATE_PRECISION)) * RATE_PRECISION
int128 abdkProportion = ABDKMath64x64.fromInt(logitP);
// Here, abdk will revert due to negative log so abort
if (abdkProportion <= 0) return (0, false);
int256 result =
ABDKMath64x64.toInt(
ABDKMath64x64.mul(
ABDKMath64x64.sub(
ABDKMath64x64.ln(abdkProportion),
Constants.LOG_RATE_PRECISION_64x64
),
Constants.RATE_PRECISION_64x64
)
);
return (result, true);
}
/// @notice Oracle rate protects against short term price manipulation. Time window will be set to a value
/// on the order of minutes to hours. This is to protect fCash valuations from market manipulation. For example,
/// a trader could use a flash loan to dump a large amount of cash into the market and depress interest rates.
/// Since we value fCash in portfolios based on these rates, portfolio values will decrease and they may then
/// be liquidated.
///
/// Oracle rates are calculated when the market is loaded from storage.
///
/// The oracle rate is a lagged weighted average over a short term price window. If we are past
/// the short term window then we just set the rate to the lastImpliedRate, otherwise we take the
/// weighted average:
/// lastImpliedRatePreTrade * (currentTs - previousTs) / timeWindow +
/// oracleRatePrevious * (1 - (currentTs - previousTs) / timeWindow)
function _updateRateOracle(
uint256 previousTradeTime,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 rateOracleTimeWindow,
uint256 blockTime
) private pure returns (uint256) {
require(rateOracleTimeWindow > 0); // dev: update rate oracle, time window zero
// This can occur when using a view function get to a market state in the past
if (previousTradeTime > blockTime) return lastImpliedRate;
uint256 timeDiff = blockTime.sub(previousTradeTime);
if (timeDiff > rateOracleTimeWindow) {
// If past the time window just return the lastImpliedRate
return lastImpliedRate;
}
// (currentTs - previousTs) / timeWindow
uint256 lastTradeWeight =
timeDiff.mul(uint256(Constants.RATE_PRECISION)).div(rateOracleTimeWindow);
// 1 - (currentTs - previousTs) / timeWindow
uint256 oracleWeight = uint256(Constants.RATE_PRECISION).sub(lastTradeWeight);
uint256 newOracleRate =
(lastImpliedRate.mul(lastTradeWeight).add(oracleRate.mul(oracleWeight))).div(
uint256(Constants.RATE_PRECISION)
);
return newOracleRate;
}
function getOracleRate(
uint256 currencyId,
uint256 maturity,
uint256 rateOracleTimeWindow,
uint256 blockTime
) internal view returns (uint256) {
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
uint256 lastImpliedRate = marketStorage.lastImpliedRate;
uint256 oracleRate = marketStorage.oracleRate;
uint256 previousTradeTime = marketStorage.previousTradeTime;
// If the oracle rate is set to zero this can only be because the markets have past their settlement
// date but the new set of markets has not yet been initialized. This means that accounts cannot be liquidated
// during this time, but market initialization can be called by anyone so the actual time that this condition
// exists for should be quite short.
require(oracleRate > 0, "Market not initialized");
return
_updateRateOracle(
previousTradeTime,
lastImpliedRate,
oracleRate,
rateOracleTimeWindow,
blockTime
);
}
/// @notice Reads a market object directly from storage. `loadMarket` should be called instead of this method
/// which ensures that the rate oracle is set properly.
function _loadMarketStorage(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
bool needsLiquidity,
uint256 settlementDate
) private view {
// Market object always uses the most current reference time as the settlement date
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][maturity][settlementDate];
bytes32 slot;
assembly {
slot := marketStorage.slot
}
market.storageSlot = slot;
market.maturity = maturity;
market.totalfCash = marketStorage.totalfCash;
market.totalAssetCash = marketStorage.totalAssetCash;
market.lastImpliedRate = marketStorage.lastImpliedRate;
market.oracleRate = marketStorage.oracleRate;
market.previousTradeTime = marketStorage.previousTradeTime;
if (needsLiquidity) {
market.totalLiquidity = marketStorage.totalLiquidity;
} else {
market.totalLiquidity = 0;
}
}
function _getMarketStoragePointer(
MarketParameters memory market
) private pure returns (MarketStorage storage marketStorage) {
bytes32 slot = market.storageSlot;
assembly {
marketStorage.slot := slot
}
}
function _setMarketStorageForLiquidity(MarketParameters memory market) internal {
MarketStorage storage marketStorage = _getMarketStoragePointer(market);
// Oracle rate does not change on liquidity
uint32 storedOracleRate = marketStorage.oracleRate;
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
storedOracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function setMarketStorageForInitialize(
MarketParameters memory market,
uint256 currencyId,
uint256 settlementDate
) internal {
// On initialization we have not yet calculated the storage slot so we get it here.
mapping(uint256 => mapping(uint256 =>
mapping(uint256 => MarketStorage))) storage store = LibStorage.getMarketStorage();
MarketStorage storage marketStorage = store[currencyId][market.maturity][settlementDate];
_setMarketStorage(
marketStorage,
market.totalfCash,
market.totalAssetCash,
market.lastImpliedRate,
market.oracleRate,
market.previousTradeTime
);
_setTotalLiquidity(marketStorage, market.totalLiquidity);
}
function _setTotalLiquidity(
MarketStorage storage marketStorage,
int256 totalLiquidity
) internal {
require(totalLiquidity >= 0 && totalLiquidity <= type(uint80).max); // dev: market storage totalLiquidity overflow
marketStorage.totalLiquidity = uint80(totalLiquidity);
}
function _setMarketStorage(
MarketStorage storage marketStorage,
int256 totalfCash,
int256 totalAssetCash,
uint256 lastImpliedRate,
uint256 oracleRate,
uint256 previousTradeTime
) private {
require(totalfCash >= 0 && totalfCash <= type(uint80).max); // dev: storage totalfCash overflow
require(totalAssetCash >= 0 && totalAssetCash <= type(uint80).max); // dev: storage totalAssetCash overflow
require(0 < lastImpliedRate && lastImpliedRate <= type(uint32).max); // dev: storage lastImpliedRate overflow
require(0 < oracleRate && oracleRate <= type(uint32).max); // dev: storage oracleRate overflow
require(0 <= previousTradeTime && previousTradeTime <= type(uint32).max); // dev: storage previous trade time overflow
marketStorage.totalfCash = uint80(totalfCash);
marketStorage.totalAssetCash = uint80(totalAssetCash);
marketStorage.lastImpliedRate = uint32(lastImpliedRate);
marketStorage.oracleRate = uint32(oracleRate);
marketStorage.previousTradeTime = uint32(previousTradeTime);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately.
function loadMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow
) internal view {
// Always reference the current settlement date
uint256 settlementDate = DateTime.getReferenceTime(blockTime) + Constants.QUARTER;
loadMarketWithSettlementDate(
market,
currencyId,
maturity,
blockTime,
needsLiquidity,
rateOracleTimeWindow,
settlementDate
);
}
/// @notice Creates a market object and ensures that the rate oracle time window is updated appropriately, this
/// is mainly used in the InitializeMarketAction contract.
function loadMarketWithSettlementDate(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
bool needsLiquidity,
uint256 rateOracleTimeWindow,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, needsLiquidity, settlementDate);
market.oracleRate = _updateRateOracle(
market.previousTradeTime,
market.lastImpliedRate,
market.oracleRate,
rateOracleTimeWindow,
blockTime
);
}
function loadSettlementMarket(
MarketParameters memory market,
uint256 currencyId,
uint256 maturity,
uint256 settlementDate
) internal view {
_loadMarketStorage(market, currencyId, maturity, true, settlementDate);
}
/// Uses Newton's method to converge on an fCash amount given the amount of
/// cash. The relation between cash and fcash is:
/// cashAmount * exchangeRate * fee + fCash = 0
/// where exchangeRate(fCash) = (rateScalar ^ -1) * ln(p / (1 - p)) + rateAnchor
/// p = (totalfCash - fCash) / (totalfCash + totalCash)
/// if cashAmount < 0: fee = feeRate ^ -1
/// if cashAmount > 0: fee = feeRate
///
/// Newton's method is:
/// fCash_(n+1) = fCash_n - f(fCash) / f'(fCash)
///
/// f(fCash) = cashAmount * exchangeRate(fCash) * fee + fCash
///
/// (totalfCash + totalCash)
/// exchangeRate'(fCash) = - ------------------------------------------
/// (totalfCash - fCash) * (totalCash + fCash)
///
/// https://www.wolframalpha.com/input/?i=ln%28%28%28a-x%29%2F%28a%2Bb%29%29%2F%281-%28a-x%29%2F%28a%2Bb%29%29%29
///
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
///
/// NOTE: each iteration costs about 11.3k so this is only done via a view function.
function getfCashGivenCashAmount(
int256 totalfCash,
int256 netCashToAccount,
int256 totalCashUnderlying,
int256 rateScalar,
int256 rateAnchor,
int256 feeRate,
int256 maxDelta
) internal pure returns (int256) {
require(maxDelta >= 0);
int256 fCashChangeToAccountGuess = netCashToAccount.mulInRatePrecision(rateAnchor).neg();
for (uint8 i = 0; i < 250; i++) {
(int256 exchangeRate, bool success) =
_getExchangeRate(
totalfCash,
totalCashUnderlying,
rateScalar,
rateAnchor,
fCashChangeToAccountGuess
);
require(success); // dev: invalid exchange rate
int256 delta =
_calculateDelta(
netCashToAccount,
totalfCash,
totalCashUnderlying,
rateScalar,
fCashChangeToAccountGuess,
exchangeRate,
feeRate
);
if (delta.abs() <= maxDelta) return fCashChangeToAccountGuess;
fCashChangeToAccountGuess = fCashChangeToAccountGuess.sub(delta);
}
revert("No convergence");
}
/// @dev Calculates: f(fCash) / f'(fCash)
/// f(fCash) = cashAmount * exchangeRate * fee + fCash
/// (cashAmount * fee) * (totalfCash + totalCash)
/// f'(fCash) = 1 - ------------------------------------------------------
/// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
function _calculateDelta(
int256 cashAmount,
int256 totalfCash,
int256 totalCashUnderlying,
int256 rateScalar,
int256 fCashGuess,
int256 exchangeRate,
int256 feeRate
) private pure returns (int256) {
int256 derivative;
// rateScalar * (totalfCash - fCash) * (totalCash + fCash)
// Precision: TOKEN_PRECISION ^ 2
int256 denominator =
rateScalar.mulInRatePrecision(
(totalfCash.sub(fCashGuess)).mul(totalCashUnderlying.add(fCashGuess))
);
if (fCashGuess > 0) {
// Lending
exchangeRate = exchangeRate.divInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount / fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount
.mul(totalfCash.add(totalCashUnderlying))
.divInRatePrecision(feeRate);
} else {
// Borrowing
exchangeRate = exchangeRate.mulInRatePrecision(feeRate);
require(exchangeRate >= Constants.RATE_PRECISION); // dev: rate underflow
// (cashAmount * fee) * (totalfCash + totalCash)
// Precision: TOKEN_PRECISION ^ 2
derivative = cashAmount.mulInRatePrecision(
feeRate.mul(totalfCash.add(totalCashUnderlying))
);
}
// 1 - numerator / denominator
// Precision: TOKEN_PRECISION
derivative = Constants.INTERNAL_TOKEN_PRECISION.sub(derivative.div(denominator));
// f(fCash) = cashAmount * exchangeRate * fee + fCash
// NOTE: exchangeRate at this point already has the fee taken into account
int256 numerator = cashAmount.mulInRatePrecision(exchangeRate);
numerator = numerator.add(fCashGuess);
// f(fCash) / f'(fCash), note that they are both denominated as cashAmount so use TOKEN_PRECISION
// here instead of RATE_PRECISION
return numerator.mul(Constants.INTERNAL_TOKEN_PRECISION).div(derivative);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Market.sol";
import "./AssetRate.sol";
import "./DateTime.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library CashGroup {
using SafeMath for uint256;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
// Bit number references for each parameter in the 32 byte word (0-indexed)
uint256 private constant MARKET_INDEX_BIT = 31;
uint256 private constant RATE_ORACLE_TIME_WINDOW_BIT = 30;
uint256 private constant TOTAL_FEE_BIT = 29;
uint256 private constant RESERVE_FEE_SHARE_BIT = 28;
uint256 private constant DEBT_BUFFER_BIT = 27;
uint256 private constant FCASH_HAIRCUT_BIT = 26;
uint256 private constant SETTLEMENT_PENALTY_BIT = 25;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT_BIT = 24;
uint256 private constant LIQUIDATION_DEBT_BUFFER_BIT = 23;
// 7 bytes allocated, one byte per market for the liquidity token haircut
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT = 22;
// 7 bytes allocated, one byte per market for the rate scalar
uint256 private constant RATE_SCALAR_FIRST_BIT = 15;
// Offsets for the bytes of the different parameters
uint256 private constant MARKET_INDEX = (31 - MARKET_INDEX_BIT) * 8;
uint256 private constant RATE_ORACLE_TIME_WINDOW = (31 - RATE_ORACLE_TIME_WINDOW_BIT) * 8;
uint256 private constant TOTAL_FEE = (31 - TOTAL_FEE_BIT) * 8;
uint256 private constant RESERVE_FEE_SHARE = (31 - RESERVE_FEE_SHARE_BIT) * 8;
uint256 private constant DEBT_BUFFER = (31 - DEBT_BUFFER_BIT) * 8;
uint256 private constant FCASH_HAIRCUT = (31 - FCASH_HAIRCUT_BIT) * 8;
uint256 private constant SETTLEMENT_PENALTY = (31 - SETTLEMENT_PENALTY_BIT) * 8;
uint256 private constant LIQUIDATION_FCASH_HAIRCUT = (31 - LIQUIDATION_FCASH_HAIRCUT_BIT) * 8;
uint256 private constant LIQUIDATION_DEBT_BUFFER = (31 - LIQUIDATION_DEBT_BUFFER_BIT) * 8;
uint256 private constant LIQUIDITY_TOKEN_HAIRCUT = (31 - LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT) * 8;
uint256 private constant RATE_SCALAR = (31 - RATE_SCALAR_FIRST_BIT) * 8;
/// @notice Returns the rate scalar scaled by time to maturity. The rate scalar multiplies
/// the ln() portion of the liquidity curve as an inverse so it increases with time to
/// maturity. The effect of the rate scalar on slippage must decrease with time to maturity.
function getRateScalar(
CashGroupParameters memory cashGroup,
uint256 marketIndex,
uint256 timeToMaturity
) internal pure returns (int256) {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex); // dev: invalid market index
uint256 offset = RATE_SCALAR + 8 * (marketIndex - 1);
int256 scalar = int256(uint8(uint256(cashGroup.data >> offset))) * Constants.RATE_PRECISION;
int256 rateScalar =
scalar.mul(int256(Constants.IMPLIED_RATE_TIME)).div(SafeInt256.toInt(timeToMaturity));
// Rate scalar is denominated in RATE_PRECISION, it is unlikely to underflow in the
// division above.
require(rateScalar > 0); // dev: rate scalar underflow
return rateScalar;
}
/// @notice Haircut on liquidity tokens to account for the risk associated with changes in the
/// proportion of cash to fCash within the pool. This is set as a percentage less than or equal to 100.
function getLiquidityHaircut(CashGroupParameters memory cashGroup, uint256 assetType)
internal
pure
returns (uint8)
{
require(
Constants.MIN_LIQUIDITY_TOKEN_INDEX <= assetType &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX
); // dev: liquidity haircut invalid asset type
uint256 offset =
LIQUIDITY_TOKEN_HAIRCUT + 8 * (assetType - Constants.MIN_LIQUIDITY_TOKEN_INDEX);
return uint8(uint256(cashGroup.data >> offset));
}
/// @notice Total trading fee denominated in RATE_PRECISION with basis point increments
function getTotalFee(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> TOTAL_FEE))) * Constants.BASIS_POINT;
}
/// @notice Percentage of the total trading fee that goes to the reserve
function getReserveFeeShare(CashGroupParameters memory cashGroup)
internal
pure
returns (int256)
{
return uint8(uint256(cashGroup.data >> RESERVE_FEE_SHARE));
}
/// @notice fCash haircut for valuation denominated in rate precision with five basis point increments
function getfCashHaircut(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return
uint256(uint8(uint256(cashGroup.data >> FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice fCash debt buffer for valuation denominated in rate precision with five basis point increments
function getDebtBuffer(CashGroupParameters memory cashGroup) internal pure returns (uint256) {
return uint256(uint8(uint256(cashGroup.data >> DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Time window factor for the rate oracle denominated in seconds with five minute increments.
function getRateOracleTimeWindow(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
// This is denominated in 5 minute increments in storage
return uint256(uint8(uint256(cashGroup.data >> RATE_ORACLE_TIME_WINDOW))) * Constants.FIVE_MINUTES;
}
/// @notice Penalty rate for settling cash debts denominated in basis points
function getSettlementPenalty(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> SETTLEMENT_PENALTY))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for positive fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationfCashHaircut(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_FCASH_HAIRCUT))) * Constants.FIVE_BASIS_POINTS;
}
/// @notice Haircut for negative fCash during liquidation denominated rate precision
/// with five basis point increments
function getLiquidationDebtBuffer(CashGroupParameters memory cashGroup)
internal
pure
returns (uint256)
{
return
uint256(uint8(uint256(cashGroup.data >> LIQUIDATION_DEBT_BUFFER))) * Constants.FIVE_BASIS_POINTS;
}
function loadMarket(
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 marketIndex,
bool needsLiquidity,
uint256 blockTime
) internal view {
require(1 <= marketIndex && marketIndex <= cashGroup.maxMarketIndex, "Invalid market");
uint256 maturity =
DateTime.getReferenceTime(blockTime).add(DateTime.getTradedMarket(marketIndex));
market.loadMarket(
cashGroup.currencyId,
maturity,
blockTime,
needsLiquidity,
getRateOracleTimeWindow(cashGroup)
);
}
/// @notice Returns the linear interpolation between two market rates. The formula is
/// slope = (longMarket.oracleRate - shortMarket.oracleRate) / (longMarket.maturity - shortMarket.maturity)
/// interpolatedRate = slope * (assetMaturity - shortMarket.maturity) + shortMarket.oracleRate
function interpolateOracleRate(
uint256 shortMaturity,
uint256 longMaturity,
uint256 shortRate,
uint256 longRate,
uint256 assetMaturity
) internal pure returns (uint256) {
require(shortMaturity < assetMaturity); // dev: cash group interpolation error, short maturity
require(assetMaturity < longMaturity); // dev: cash group interpolation error, long maturity
// It's possible that the rates are inverted where the short market rate > long market rate and
// we will get an underflow here so we check for that
if (longRate >= shortRate) {
return
(longRate - shortRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
.add(shortRate);
} else {
// In this case the slope is negative so:
// interpolatedRate = shortMarket.oracleRate - slope * (assetMaturity - shortMarket.maturity)
// NOTE: this subtraction should never overflow, the linear interpolation between two points above zero
// cannot go below zero
return
shortRate.sub(
// This is reversed to keep it it positive
(shortRate - longRate)
.mul(assetMaturity - shortMaturity)
// No underflow here, checked above
.div(longMaturity - shortMaturity)
);
}
}
/// @dev Gets an oracle rate given any valid maturity.
function calculateOracleRate(
CashGroupParameters memory cashGroup,
uint256 maturity,
uint256 blockTime
) internal view returns (uint256) {
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(cashGroup.maxMarketIndex, maturity, blockTime);
uint256 timeWindow = getRateOracleTimeWindow(cashGroup);
if (!idiosyncratic) {
return Market.getOracleRate(cashGroup.currencyId, maturity, timeWindow, blockTime);
} else {
uint256 referenceTime = DateTime.getReferenceTime(blockTime);
// DateTime.getMarketIndex returns the market that is past the maturity if idiosyncratic
uint256 longMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex));
uint256 longRate =
Market.getOracleRate(cashGroup.currencyId, longMaturity, timeWindow, blockTime);
uint256 shortMaturity;
uint256 shortRate;
if (marketIndex == 1) {
// In this case the short market is the annualized asset supply rate
shortMaturity = blockTime;
shortRate = cashGroup.assetRate.getSupplyRate();
} else {
// Minimum value for marketIndex here is 2
shortMaturity = referenceTime.add(DateTime.getTradedMarket(marketIndex - 1));
shortRate = Market.getOracleRate(
cashGroup.currencyId,
shortMaturity,
timeWindow,
blockTime
);
}
return interpolateOracleRate(shortMaturity, longMaturity, shortRate, longRate, maturity);
}
}
function _getCashGroupStorageBytes(uint256 currencyId) private view returns (bytes32 data) {
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
return store[currencyId];
}
/// @dev Helper method for validating maturities in ERC1155Action
function getMaxMarketIndex(uint256 currencyId) internal view returns (uint8) {
bytes32 data = _getCashGroupStorageBytes(currencyId);
return uint8(data[MARKET_INDEX_BIT]);
}
/// @notice Checks all cash group settings for invalid values and sets them into storage
function setCashGroupStorage(uint256 currencyId, CashGroupSettings calldata cashGroup)
internal
{
// Due to the requirements of the yield curve we do not allow a cash group to have solely a 3 month market.
// The reason is that borrowers will not have a further maturity to roll from their 3 month fixed to a 6 month
// fixed. It also complicates the logic in the nToken initialization method. Additionally, we cannot have cash
// groups with 0 market index, it has no effect.
require(2 <= cashGroup.maxMarketIndex && cashGroup.maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX,
"CG: invalid market index"
);
require(
cashGroup.reserveFeeShare <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid reserve share"
);
require(cashGroup.liquidityTokenHaircuts.length == cashGroup.maxMarketIndex);
require(cashGroup.rateScalars.length == cashGroup.maxMarketIndex);
// This is required so that fCash liquidation can proceed correctly
require(cashGroup.liquidationfCashHaircut5BPS < cashGroup.fCashHaircut5BPS);
require(cashGroup.liquidationDebtBuffer5BPS < cashGroup.debtBuffer5BPS);
// Market indexes cannot decrease or they will leave fCash assets stranded in the future with no valuation curve
uint8 previousMaxMarketIndex = getMaxMarketIndex(currencyId);
require(
previousMaxMarketIndex <= cashGroup.maxMarketIndex,
"CG: market index cannot decrease"
);
// Per cash group settings
bytes32 data =
(bytes32(uint256(cashGroup.maxMarketIndex)) |
(bytes32(uint256(cashGroup.rateOracleTimeWindow5Min)) << RATE_ORACLE_TIME_WINDOW) |
(bytes32(uint256(cashGroup.totalFeeBPS)) << TOTAL_FEE) |
(bytes32(uint256(cashGroup.reserveFeeShare)) << RESERVE_FEE_SHARE) |
(bytes32(uint256(cashGroup.debtBuffer5BPS)) << DEBT_BUFFER) |
(bytes32(uint256(cashGroup.fCashHaircut5BPS)) << FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.settlementPenaltyRate5BPS)) << SETTLEMENT_PENALTY) |
(bytes32(uint256(cashGroup.liquidationfCashHaircut5BPS)) <<
LIQUIDATION_FCASH_HAIRCUT) |
(bytes32(uint256(cashGroup.liquidationDebtBuffer5BPS)) << LIQUIDATION_DEBT_BUFFER));
// Per market group settings
for (uint256 i = 0; i < cashGroup.liquidityTokenHaircuts.length; i++) {
require(
cashGroup.liquidityTokenHaircuts[i] <= Constants.PERCENTAGE_DECIMALS,
"CG: invalid token haircut"
);
data =
data |
(bytes32(uint256(cashGroup.liquidityTokenHaircuts[i])) <<
(LIQUIDITY_TOKEN_HAIRCUT + i * 8));
}
for (uint256 i = 0; i < cashGroup.rateScalars.length; i++) {
// Causes a divide by zero error
require(cashGroup.rateScalars[i] != 0, "CG: invalid rate scalar");
data = data | (bytes32(uint256(cashGroup.rateScalars[i])) << (RATE_SCALAR + i * 8));
}
mapping(uint256 => bytes32) storage store = LibStorage.getCashGroupStorage();
store[currencyId] = data;
}
/// @notice Deserialize the cash group storage bytes into a user friendly object
function deserializeCashGroupStorage(uint256 currencyId)
internal
view
returns (CashGroupSettings memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint8 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
uint8[] memory tokenHaircuts = new uint8[](uint256(maxMarketIndex));
uint8[] memory rateScalars = new uint8[](uint256(maxMarketIndex));
for (uint8 i = 0; i < maxMarketIndex; i++) {
tokenHaircuts[i] = uint8(data[LIQUIDITY_TOKEN_HAIRCUT_FIRST_BIT - i]);
rateScalars[i] = uint8(data[RATE_SCALAR_FIRST_BIT - i]);
}
return
CashGroupSettings({
maxMarketIndex: maxMarketIndex,
rateOracleTimeWindow5Min: uint8(data[RATE_ORACLE_TIME_WINDOW_BIT]),
totalFeeBPS: uint8(data[TOTAL_FEE_BIT]),
reserveFeeShare: uint8(data[RESERVE_FEE_SHARE_BIT]),
debtBuffer5BPS: uint8(data[DEBT_BUFFER_BIT]),
fCashHaircut5BPS: uint8(data[FCASH_HAIRCUT_BIT]),
settlementPenaltyRate5BPS: uint8(data[SETTLEMENT_PENALTY_BIT]),
liquidationfCashHaircut5BPS: uint8(data[LIQUIDATION_FCASH_HAIRCUT_BIT]),
liquidationDebtBuffer5BPS: uint8(data[LIQUIDATION_DEBT_BUFFER_BIT]),
liquidityTokenHaircuts: tokenHaircuts,
rateScalars: rateScalars
});
}
function _buildCashGroup(uint16 currencyId, AssetRateParameters memory assetRate)
private
view
returns (CashGroupParameters memory)
{
bytes32 data = _getCashGroupStorageBytes(currencyId);
uint256 maxMarketIndex = uint8(data[MARKET_INDEX_BIT]);
return
CashGroupParameters({
currencyId: currencyId,
maxMarketIndex: maxMarketIndex,
assetRate: assetRate,
data: data
});
}
/// @notice Builds a cash group using a view version of the asset rate
function buildCashGroupView(uint16 currencyId)
internal
view
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateView(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
/// @notice Builds a cash group using a stateful version of the asset rate
function buildCashGroupStateful(uint16 currencyId)
internal
returns (CashGroupParameters memory)
{
AssetRateParameters memory assetRate = AssetRate.buildAssetRateStateful(currencyId);
return _buildCashGroup(currencyId, assetRate);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/notional/AssetRateAdapter.sol";
library AssetRate {
using SafeInt256 for int256;
event SetSettlementRate(uint256 indexed currencyId, uint256 indexed maturity, uint128 rate);
// Asset rates are in 1e18 decimals (cToken exchange rates), internal balances
// are in 1e8 decimals. Therefore we leave this as 1e18 / 1e8 = 1e10
int256 private constant ASSET_RATE_DECIMAL_DIFFERENCE = 1e10;
/// @notice Converts an internal asset cash value to its underlying token value.
/// @param ar exchange rate object between asset and underlying
/// @param assetBalance amount to convert to underlying
function convertToUnderlying(AssetRateParameters memory ar, int256 assetBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rate * balance * internalPrecision / rateDecimals * underlyingPrecision
int256 underlyingBalance = ar.rate
.mul(assetBalance)
.div(ASSET_RATE_DECIMAL_DIFFERENCE)
.div(ar.underlyingDecimals);
return underlyingBalance;
}
/// @notice Converts an internal underlying cash value to its asset cash value
/// @param ar exchange rate object between asset and underlying
/// @param underlyingBalance amount to convert to asset cash, denominated in internal token precision
function convertFromUnderlying(AssetRateParameters memory ar, int256 underlyingBalance)
internal
pure
returns (int256)
{
// Calculation here represents:
// rateDecimals * balance * underlyingPrecision / rate * internalPrecision
int256 assetBalance = underlyingBalance
.mul(ASSET_RATE_DECIMAL_DIFFERENCE)
.mul(ar.underlyingDecimals)
.div(ar.rate);
return assetBalance;
}
/// @notice Returns the current per block supply rate, is used when calculating oracle rates
/// for idiosyncratic fCash with a shorter duration than the 3 month maturity.
function getSupplyRate(AssetRateParameters memory ar) internal view returns (uint256) {
// If the rate oracle is not set, the asset is not interest bearing and has an oracle rate of zero.
if (address(ar.rateOracle) == address(0)) return 0;
uint256 rate = ar.rateOracle.getAnnualizedSupplyRate();
// Zero supply rate is valid since this is an interest rate, we do not divide by
// the supply rate so we do not get div by zero errors.
require(rate >= 0); // dev: invalid supply rate
return rate;
}
function _getAssetRateStorage(uint256 currencyId)
private
view
returns (AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces)
{
mapping(uint256 => AssetRateStorage) storage store = LibStorage.getAssetRateStorage();
AssetRateStorage storage ar = store[currencyId];
rateOracle = AssetRateAdapter(ar.rateOracle);
underlyingDecimalPlaces = ar.underlyingDecimalPlaces;
}
/// @notice Gets an asset rate using a view function, does not accrue interest so the
/// exchange rate will not be up to date. Should only be used for non-stateful methods
function _getAssetRateView(uint256 currencyId)
private
view
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateView();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Gets an asset rate using a stateful function, accrues interest so the
/// exchange rate will be up to date for the current block.
function _getAssetRateStateful(uint256 currencyId)
private
returns (
int256,
AssetRateAdapter,
uint8
)
{
(AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) = _getAssetRateStorage(currencyId);
int256 rate;
if (address(rateOracle) == address(0)) {
// If no rate oracle is set, then set this to the identity
rate = ASSET_RATE_DECIMAL_DIFFERENCE;
// This will get raised to 10^x and return 1, will not end up with div by zero
underlyingDecimalPlaces = 0;
} else {
rate = rateOracle.getExchangeRateStateful();
require(rate > 0); // dev: invalid exchange rate
}
return (rate, rateOracle, underlyingDecimalPlaces);
}
/// @notice Returns an asset rate object using the view method
function buildAssetRateView(uint256 currencyId)
internal
view
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateView(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @notice Returns an asset rate object using the stateful method
function buildAssetRateStateful(uint256 currencyId)
internal
returns (AssetRateParameters memory)
{
(int256 rate, AssetRateAdapter rateOracle, uint8 underlyingDecimalPlaces) =
_getAssetRateStateful(currencyId);
return
AssetRateParameters({
rateOracle: rateOracle,
rate: rate,
// No overflow, restricted on storage
underlyingDecimals: int256(10**underlyingDecimalPlaces)
});
}
/// @dev Gets a settlement rate object
function _getSettlementRateStorage(uint256 currencyId, uint256 maturity)
private
view
returns (
int256 settlementRate,
uint8 underlyingDecimalPlaces
)
{
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
settlementRate = rateStorage.settlementRate;
underlyingDecimalPlaces = rateStorage.underlyingDecimalPlaces;
}
/// @notice Returns a settlement rate object using the view method
function buildSettlementRateView(uint256 currencyId, uint256 maturity)
internal
view
returns (AssetRateParameters memory)
{
// prettier-ignore
(
int256 settlementRate,
uint8 underlyingDecimalPlaces
) = _getSettlementRateStorage(currencyId, maturity);
// Asset exchange rates cannot be zero
if (settlementRate == 0) {
// If settlement rate has not been set then we need to fetch it
// prettier-ignore
(
settlementRate,
/* address */,
underlyingDecimalPlaces
) = _getAssetRateView(currencyId);
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
/// @notice Returns a settlement rate object and sets the rate if it has not been set yet
function buildSettlementRateStateful(
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) internal returns (AssetRateParameters memory) {
(int256 settlementRate, uint8 underlyingDecimalPlaces) =
_getSettlementRateStorage(currencyId, maturity);
if (settlementRate == 0) {
// Settlement rate has not yet been set, set it in this branch
AssetRateAdapter rateOracle;
// If rate oracle == 0 then this will return the identity settlement rate
// prettier-ignore
(
settlementRate,
rateOracle,
underlyingDecimalPlaces
) = _getAssetRateStateful(currencyId);
if (address(rateOracle) != address(0)) {
mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store = LibStorage.getSettlementRateStorage();
// Only need to set settlement rates when the rate oracle is set (meaning the asset token has
// a conversion rate to an underlying). If not set then the asset cash always settles to underlying at a 1-1
// rate since they are the same.
require(0 < blockTime && maturity <= blockTime && blockTime <= type(uint40).max); // dev: settlement rate timestamp overflow
require(0 < settlementRate && settlementRate <= type(uint128).max); // dev: settlement rate overflow
SettlementRateStorage storage rateStorage = store[currencyId][maturity];
rateStorage.blockTime = uint40(blockTime);
rateStorage.settlementRate = uint128(settlementRate);
rateStorage.underlyingDecimalPlaces = underlyingDecimalPlaces;
emit SetSettlementRate(currencyId, maturity, uint128(settlementRate));
}
}
return AssetRateParameters(
AssetRateAdapter(address(0)),
settlementRate,
// No overflow, restricted on storage
int256(10**underlyingDecimalPlaces)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./PortfolioHandler.sol";
import "./BitmapAssetsHandler.sol";
import "../AccountContextHandler.sol";
import "../../global/Types.sol";
import "../../math/SafeInt256.sol";
/// @notice Helper library for transferring assets from one portfolio to another
library TransferAssets {
using AccountContextHandler for AccountContext;
using PortfolioHandler for PortfolioState;
using SafeInt256 for int256;
/// @notice Decodes asset ids
function decodeAssetId(uint256 id)
internal
pure
returns (
uint256 currencyId,
uint256 maturity,
uint256 assetType
)
{
assetType = uint8(id);
maturity = uint40(id >> 8);
currencyId = uint16(id >> 48);
}
/// @notice Encodes asset ids
function encodeAssetId(
uint256 currencyId,
uint256 maturity,
uint256 assetType
) internal pure returns (uint256) {
require(currencyId <= Constants.MAX_CURRENCIES);
require(maturity <= type(uint40).max);
require(assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX);
return
uint256(
(bytes32(uint256(uint16(currencyId))) << 48) |
(bytes32(uint256(uint40(maturity))) << 8) |
bytes32(uint256(uint8(assetType)))
);
}
/// @dev Used to flip the sign of assets to decrement the `from` account that is sending assets
function invertNotionalAmountsInPlace(PortfolioAsset[] memory assets) internal pure {
for (uint256 i; i < assets.length; i++) {
assets[i].notional = assets[i].notional.neg();
}
}
/// @dev Useful method for hiding the logic of updating an account. WARNING: the account
/// context returned from this method may not be the same memory location as the account
/// context provided if the account is settled.
function placeAssetsInAccount(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal returns (AccountContext memory) {
// If an account has assets that require settlement then placing assets inside it
// may cause issues.
require(!accountContext.mustSettleAssets(), "Account must settle");
if (accountContext.isBitmapEnabled()) {
// Adds fCash assets into the account and finalized storage
BitmapAssetsHandler.addMultipleifCashAssets(account, accountContext, assets);
} else {
PortfolioState memory portfolioState = PortfolioHandler.buildPortfolioState(
account,
accountContext.assetArrayLength,
assets.length
);
// This will add assets in memory
portfolioState.addMultipleAssets(assets);
// This will store assets and update the account context in memory
accountContext.storeAssetsAndUpdateContext(account, portfolioState, false);
}
return accountContext;
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./AssetHandler.sol";
import "./ExchangeRate.sol";
import "../markets/CashGroup.sol";
import "../AccountContextHandler.sol";
import "../balances/BalanceHandler.sol";
import "../portfolio/PortfolioHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenCalculations.sol";
import "../../math/SafeInt256.sol";
library FreeCollateral {
using SafeInt256 for int256;
using Bitmap for bytes;
using ExchangeRate for ETHRate;
using AssetRate for AssetRateParameters;
using AccountContextHandler for AccountContext;
using nTokenHandler for nTokenPortfolio;
/// @dev This is only used within the library to clean up the stack
struct FreeCollateralFactors {
int256 netETHValue;
bool updateContext;
uint256 portfolioIndex;
CashGroupParameters cashGroup;
MarketParameters market;
PortfolioAsset[] portfolio;
AssetRateParameters assetRate;
nTokenPortfolio nToken;
}
/// @notice Checks if an asset is active in the portfolio
function _isActiveInPortfolio(bytes2 currencyBytes) private pure returns (bool) {
return currencyBytes & Constants.ACTIVE_IN_PORTFOLIO == Constants.ACTIVE_IN_PORTFOLIO;
}
/// @notice Checks if currency balances are active in the account returns them if true
/// @return cash balance, nTokenBalance
function _getCurrencyBalances(address account, bytes2 currencyBytes)
private
view
returns (int256, int256)
{
if (currencyBytes & Constants.ACTIVE_IN_BALANCES == Constants.ACTIVE_IN_BALANCES) {
uint256 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// prettier-ignore
(
int256 cashBalance,
int256 nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, currencyId);
return (cashBalance, nTokenBalance);
}
return (0, 0);
}
/// @notice Calculates the nToken asset value with a haircut set by governance
/// @return the value of the account's nTokens after haircut, the nToken parameters
function _getNTokenHaircutAssetPV(
CashGroupParameters memory cashGroup,
nTokenPortfolio memory nToken,
int256 tokenBalance,
uint256 blockTime
) internal view returns (int256, bytes6) {
nToken.loadNTokenPortfolioNoCashGroup(cashGroup.currencyId);
nToken.cashGroup = cashGroup;
int256 nTokenAssetPV = nTokenCalculations.getNTokenAssetPV(nToken, blockTime);
// (tokenBalance * nTokenValue * haircut) / totalSupply
int256 nTokenHaircutAssetPV =
tokenBalance
.mul(nTokenAssetPV)
.mul(uint8(nToken.parameters[Constants.PV_HAIRCUT_PERCENTAGE]))
.div(Constants.PERCENTAGE_DECIMALS)
.div(nToken.totalSupply);
// nToken.parameters is returned for use in liquidation
return (nTokenHaircutAssetPV, nToken.parameters);
}
/// @notice Calculates portfolio and/or nToken values while using the supplied cash groups and
/// markets. The reason these are grouped together is because they both require storage reads of the same
/// values.
function _getPortfolioAndNTokenAssetValue(
FreeCollateralFactors memory factors,
int256 nTokenBalance,
uint256 blockTime
)
private
view
returns (
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
// If the next asset matches the currency id then we need to calculate the cash group value
if (
factors.portfolioIndex < factors.portfolio.length &&
factors.portfolio[factors.portfolioIndex].currencyId == factors.cashGroup.currencyId
) {
// netPortfolioValue is in asset cash
(netPortfolioValue, factors.portfolioIndex) = AssetHandler.getNetCashGroupValue(
factors.portfolio,
factors.cashGroup,
factors.market,
blockTime,
factors.portfolioIndex
);
} else {
netPortfolioValue = 0;
}
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
nTokenParameters = 0;
}
}
/// @notice Returns balance values for the bitmapped currency
function _getBitmapBalanceValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
)
private
view
returns (
int256 cashBalance,
int256 nTokenHaircutAssetValue,
bytes6 nTokenParameters
)
{
int256 nTokenBalance;
// prettier-ignore
(
cashBalance,
nTokenBalance,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(account, accountContext.bitmapCurrencyId);
if (nTokenBalance > 0) {
(nTokenHaircutAssetValue, nTokenParameters) = _getNTokenHaircutAssetPV(
factors.cashGroup,
factors.nToken,
nTokenBalance,
blockTime
);
} else {
nTokenHaircutAssetValue = 0;
}
}
/// @notice Returns portfolio value for the bitmapped currency
function _getBitmapPortfolioValue(
address account,
uint256 blockTime,
AccountContext memory accountContext,
FreeCollateralFactors memory factors
) private view returns (int256) {
(int256 netPortfolioValueUnderlying, bool bitmapHasDebt) =
BitmapAssetsHandler.getifCashNetPresentValue(
account,
accountContext.bitmapCurrencyId,
accountContext.nextSettleTime,
blockTime,
factors.cashGroup,
true // risk adjusted
);
// Turns off has debt flag if it has changed
bool contextHasAssetDebt =
accountContext.hasDebt & Constants.HAS_ASSET_DEBT == Constants.HAS_ASSET_DEBT;
if (bitmapHasDebt && !contextHasAssetDebt) {
// Turn on has debt
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
} else if (!bitmapHasDebt && contextHasAssetDebt) {
// Turn off has debt
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_ASSET_DEBT;
factors.updateContext = true;
}
// Return asset cash value
return factors.cashGroup.assetRate.convertFromUnderlying(netPortfolioValueUnderlying);
}
function _updateNetETHValue(
uint256 currencyId,
int256 netLocalAssetValue,
FreeCollateralFactors memory factors
) private view returns (ETHRate memory) {
ETHRate memory ethRate = ExchangeRate.buildExchangeRate(currencyId);
// Converts to underlying first, ETH exchange rates are in underlying
factors.netETHValue = factors.netETHValue.add(
ethRate.convertToETH(factors.assetRate.convertToUnderlying(netLocalAssetValue))
);
return ethRate;
}
/// @notice Stateful version of get free collateral, returns the total net ETH value and true or false if the account
/// context needs to be updated.
function getFreeCollateralStateful(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal returns (int256, bool) {
FreeCollateralFactors memory factors;
bool hasCashDebt;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
if (netCashBalance < 0) hasCashDebt = true;
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(account, currencyBytes);
if (netLocalAssetValue < 0) hasCashDebt = true;
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
// prettier-ignore
(
int256 netPortfolioAssetValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioAssetValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
// NOTE: we must set the proper assetRate when we updateNetETHValue
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValue, factors);
currencies = currencies << 16;
}
// Free collateral is the only method that examines all cash balances for an account at once. If there is no cash debt (i.e.
// they have been repaid or settled via more debt) then this will turn off the flag. It's possible that this flag is out of
// sync temporarily after a cash settlement and before the next free collateral check. The only downside for that is forcing
// an account to do an extra free collateral check to turn off this setting.
if (
accountContext.hasDebt & Constants.HAS_CASH_DEBT == Constants.HAS_CASH_DEBT &&
!hasCashDebt
) {
accountContext.hasDebt = accountContext.hasDebt & ~Constants.HAS_CASH_DEBT;
factors.updateContext = true;
}
return (factors.netETHValue, factors.updateContext);
}
/// @notice View version of getFreeCollateral, does not use the stateful version of build cash group and skips
/// all the update context logic.
function getFreeCollateralView(
address account,
AccountContext memory accountContext,
uint256 blockTime
) internal view returns (int256, int256[] memory) {
FreeCollateralFactors memory factors;
uint256 netLocalIndex;
int256[] memory netLocalAssetValues = new int256[](10);
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupView(accountContext.bitmapCurrencyId);
// prettier-ignore
(
int256 netCashBalance,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioAssetValue =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
netLocalAssetValues[netLocalIndex] = netCashBalance
.add(nTokenHaircutAssetValue)
.add(portfolioAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
_updateNetETHValue(
accountContext.bitmapCurrencyId,
netLocalAssetValues[netLocalIndex],
factors
);
netLocalIndex++;
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
// Explicitly ensures that bitmap currency cannot be double counted
require(currencyId != accountContext.bitmapCurrencyId);
int256 nTokenBalance;
(netLocalAssetValues[netLocalIndex], nTokenBalance) = _getCurrencyBalances(
account,
currencyBytes
);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupView(currencyId);
// prettier-ignore
(
int256 netPortfolioValue,
int256 nTokenHaircutAssetValue,
/* nTokenParameters */
) = _getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValues[netLocalIndex] = netLocalAssetValues[netLocalIndex]
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
} else {
factors.assetRate = AssetRate.buildAssetRateView(currencyId);
}
_updateNetETHValue(currencyId, netLocalAssetValues[netLocalIndex], factors);
netLocalIndex++;
currencies = currencies << 16;
}
return (factors.netETHValue, netLocalAssetValues);
}
/// @notice Calculates the net value of a currency within a portfolio, this is a bit
/// convoluted to fit into the stack frame
function _calculateLiquidationAssetValue(
FreeCollateralFactors memory factors,
LiquidationFactors memory liquidationFactors,
bytes2 currencyBytes,
bool setLiquidationFactors,
uint256 blockTime
) private returns (int256) {
uint16 currencyId = uint16(currencyBytes & Constants.UNMASK_FLAGS);
(int256 netLocalAssetValue, int256 nTokenBalance) =
_getCurrencyBalances(liquidationFactors.account, currencyBytes);
if (_isActiveInPortfolio(currencyBytes) || nTokenBalance > 0) {
factors.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
(int256 netPortfolioValue, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getPortfolioAndNTokenAssetValue(factors, nTokenBalance, blockTime);
netLocalAssetValue = netLocalAssetValue
.add(netPortfolioValue)
.add(nTokenHaircutAssetValue);
factors.assetRate = factors.cashGroup.assetRate;
// If collateralCurrencyId is set to zero then this is a local currency liquidation
if (setLiquidationFactors) {
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenParameters = nTokenParameters;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
}
} else {
factors.assetRate = AssetRate.buildAssetRateStateful(currencyId);
}
return netLocalAssetValue;
}
/// @notice A version of getFreeCollateral used during liquidation to save off necessary additional information.
function getLiquidationFactors(
address account,
AccountContext memory accountContext,
uint256 blockTime,
uint256 localCurrencyId,
uint256 collateralCurrencyId
) internal returns (LiquidationFactors memory, PortfolioAsset[] memory) {
FreeCollateralFactors memory factors;
LiquidationFactors memory liquidationFactors;
// This is only set to reduce the stack size
liquidationFactors.account = account;
if (accountContext.isBitmapEnabled()) {
factors.cashGroup = CashGroup.buildCashGroupStateful(accountContext.bitmapCurrencyId);
(int256 netCashBalance, int256 nTokenHaircutAssetValue, bytes6 nTokenParameters) =
_getBitmapBalanceValue(account, blockTime, accountContext, factors);
int256 portfolioBalance =
_getBitmapPortfolioValue(account, blockTime, accountContext, factors);
int256 netLocalAssetValue =
netCashBalance.add(nTokenHaircutAssetValue).add(portfolioBalance);
factors.assetRate = factors.cashGroup.assetRate;
ETHRate memory ethRate =
_updateNetETHValue(accountContext.bitmapCurrencyId, netLocalAssetValue, factors);
// If the bitmap currency id can only ever be the local currency where debt is held.
// During enable bitmap we check that the account has no assets in their portfolio and
// no cash debts.
if (accountContext.bitmapCurrencyId == localCurrencyId) {
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// This will be the case during local currency or local fCash liquidation
if (collateralCurrencyId == 0) {
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers.
liquidationFactors.collateralCashGroup = factors.cashGroup;
liquidationFactors.nTokenHaircutAssetValue = nTokenHaircutAssetValue;
liquidationFactors.nTokenParameters = nTokenParameters;
}
}
} else {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
bytes18 currencies = accountContext.activeCurrencies;
while (currencies != 0) {
bytes2 currencyBytes = bytes2(currencies);
// This next bit of code here is annoyingly structured to get around stack size issues
bool setLiquidationFactors;
{
uint256 tempId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
// Explicitly ensures that bitmap currency cannot be double counted
require(tempId != accountContext.bitmapCurrencyId);
setLiquidationFactors =
(tempId == localCurrencyId && collateralCurrencyId == 0) ||
tempId == collateralCurrencyId;
}
int256 netLocalAssetValue =
_calculateLiquidationAssetValue(
factors,
liquidationFactors,
currencyBytes,
setLiquidationFactors,
blockTime
);
uint256 currencyId = uint256(uint16(currencyBytes & Constants.UNMASK_FLAGS));
ETHRate memory ethRate = _updateNetETHValue(currencyId, netLocalAssetValue, factors);
if (currencyId == collateralCurrencyId) {
// Ensure that this is set even if the cash group is not loaded, it will not be
// loaded if the account only has a cash balance and no nTokens or assets
liquidationFactors.collateralCashGroup.assetRate = factors.assetRate;
liquidationFactors.collateralAssetAvailable = netLocalAssetValue;
liquidationFactors.collateralETHRate = ethRate;
} else if (currencyId == localCurrencyId) {
// This branch will not be entered if bitmap is enabled
liquidationFactors.localAssetAvailable = netLocalAssetValue;
liquidationFactors.localETHRate = ethRate;
liquidationFactors.localAssetRate = factors.assetRate;
// If this is local fCash liquidation, the cash group information is required
// to calculate fCash haircuts and buffers and it will have been set in
// _calculateLiquidationAssetValue above because the account must have fCash assets,
// there is no need to set cash group in this branch.
}
currencies = currencies << 16;
}
liquidationFactors.netETHValue = factors.netETHValue;
require(liquidationFactors.netETHValue < 0, "Sufficient collateral");
// Refetch the portfolio if it exists, AssetHandler.getNetCashValue updates values in memory to do fCash
// netting which will make further calculations incorrect.
if (accountContext.assetArrayLength > 0) {
factors.portfolio = PortfolioHandler.getSortedPortfolio(
account,
accountContext.assetArrayLength
);
}
return (liquidationFactors, factors.portfolio);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../valuation/AssetHandler.sol";
import "../markets/Market.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
library SettlePortfolioAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Market for MarketParameters;
using PortfolioHandler for PortfolioState;
using AssetHandler for PortfolioAsset;
/// @dev Returns a SettleAmount array for the assets that will be settled
function _getSettleAmountArray(PortfolioState memory portfolioState, uint256 blockTime)
private
pure
returns (SettleAmount[] memory)
{
uint256 currenciesSettled;
uint256 lastCurrencyId = 0;
if (portfolioState.storedAssets.length == 0) return new SettleAmount[](0);
// Loop backwards so "lastCurrencyId" will be set to the first currency in the portfolio
// NOTE: if this contract is ever upgraded to Solidity 0.8+ then this i-- will underflow and cause
// a revert, must wrap in an unchecked.
for (uint256 i = portfolioState.storedAssets.length; (i--) > 0;) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
// Assets settle on exactly blockTime
if (asset.getSettlementDate() > blockTime) continue;
// Assume that this is sorted by cash group and maturity, currencyId = 0 is unused so this
// will work for the first asset
if (lastCurrencyId != asset.currencyId) {
lastCurrencyId = asset.currencyId;
currenciesSettled++;
}
}
// Actual currency ids will be set as we loop through the portfolio and settle assets
SettleAmount[] memory settleAmounts = new SettleAmount[](currenciesSettled);
if (currenciesSettled > 0) settleAmounts[0].currencyId = lastCurrencyId;
return settleAmounts;
}
/// @notice Settles a portfolio array
function settlePortfolio(PortfolioState memory portfolioState, uint256 blockTime)
internal
returns (SettleAmount[] memory)
{
AssetRateParameters memory settlementRate;
SettleAmount[] memory settleAmounts = _getSettleAmountArray(portfolioState, blockTime);
MarketParameters memory market;
if (settleAmounts.length == 0) return settleAmounts;
uint256 settleAmountIndex;
for (uint256 i; i < portfolioState.storedAssets.length; i++) {
PortfolioAsset memory asset = portfolioState.storedAssets[i];
uint256 settleDate = asset.getSettlementDate();
// Settlement date is on block time exactly
if (settleDate > blockTime) continue;
// On the first loop the lastCurrencyId is already set.
if (settleAmounts[settleAmountIndex].currencyId != asset.currencyId) {
// New currency in the portfolio
settleAmountIndex += 1;
settleAmounts[settleAmountIndex].currencyId = asset.currencyId;
}
int256 assetCash;
if (asset.assetType == Constants.FCASH_ASSET_TYPE) {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
assetCash = settlementRate.convertFromUnderlying(asset.notional);
portfolioState.deleteAsset(i);
} else if (AssetHandler.isLiquidityToken(asset.assetType)) {
Market.loadSettlementMarket(market, asset.currencyId, asset.maturity, settleDate);
int256 fCash;
(assetCash, fCash) = market.removeLiquidity(asset.notional);
// Assets mature exactly on block time
if (asset.maturity > blockTime) {
// If fCash has not yet matured then add it to the portfolio
_settleLiquidityTokenTofCash(portfolioState, i, fCash);
} else {
// Gets or sets the settlement rate, only do this before settling fCash
settlementRate = AssetRate.buildSettlementRateStateful(
asset.currencyId,
asset.maturity,
blockTime
);
// If asset has matured then settle fCash to asset cash
assetCash = assetCash.add(settlementRate.convertFromUnderlying(fCash));
portfolioState.deleteAsset(i);
}
}
settleAmounts[settleAmountIndex].netCashChange = settleAmounts[settleAmountIndex]
.netCashChange
.add(assetCash);
}
return settleAmounts;
}
/// @notice Settles a liquidity token to idiosyncratic fCash, this occurs when the maturity is still in the future
function _settleLiquidityTokenTofCash(
PortfolioState memory portfolioState,
uint256 index,
int256 fCash
) private pure {
PortfolioAsset memory liquidityToken = portfolioState.storedAssets[index];
// If the liquidity token's maturity is still in the future then we change the entry to be
// an idiosyncratic fCash entry with the net fCash amount.
if (index != 0) {
// Check to see if the previous index is the matching fCash asset, this will be the case when the
// portfolio is sorted
PortfolioAsset memory fCashAsset = portfolioState.storedAssets[index - 1];
if (
fCashAsset.currencyId == liquidityToken.currencyId &&
fCashAsset.maturity == liquidityToken.maturity &&
fCashAsset.assetType == Constants.FCASH_ASSET_TYPE
) {
// This fCash asset has not matured if we are settling to fCash
fCashAsset.notional = fCashAsset.notional.add(fCash);
fCashAsset.storageState = AssetStorageState.Update;
portfolioState.deleteAsset(index);
}
}
// We are going to delete this asset anyway, convert to an fCash position
liquidityToken.assetType = Constants.FCASH_ASSET_TYPE;
liquidityToken.notional = fCash;
liquidityToken.storageState = AssetStorageState.Update;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../markets/AssetRate.sol";
import "../../global/LibStorage.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
/**
* Settles a bitmap portfolio by checking for all matured fCash assets and turning them into cash
* at the prevailing settlement rate. It will also update the asset bitmap to ensure that it continues
* to correctly reference all actual maturities. fCash asset notional values are stored in *absolute*
* time terms and bitmap bits are *relative* time terms based on the bitNumber and the stored oldSettleTime.
* Remapping bits requires converting the old relative bit numbers to new relative bit numbers based on
* newSettleTime and the absolute times (maturities) that the previous bitmap references.
*/
library SettleBitmapAssets {
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using Bitmap for bytes32;
/// @notice Given a bitmap for a cash group and timestamps, will settle all assets
/// that have matured and remap the bitmap to correspond to the current time.
function settleBitmappedCashGroup(
address account,
uint256 currencyId,
uint256 oldSettleTime,
uint256 blockTime
) internal returns (int256 totalAssetCash, uint256 newSettleTime) {
bytes32 bitmap = BitmapAssetsHandler.getAssetsBitmap(account, currencyId);
// This newSettleTime will be set to the new `oldSettleTime`. The bits between 1 and
// `lastSettleBit` (inclusive) will be shifted out of the bitmap and settled. The reason
// that lastSettleBit is inclusive is that it refers to newSettleTime which always less
// than the current block time.
newSettleTime = DateTime.getTimeUTC0(blockTime);
// If newSettleTime == oldSettleTime lastSettleBit will be zero
require(newSettleTime >= oldSettleTime); // dev: new settle time before previous
// Do not need to worry about validity, if newSettleTime is not on an exact bit we will settle up until
// the closest maturity that is less than newSettleTime.
(uint256 lastSettleBit, /* isValid */) = DateTime.getBitNumFromMaturity(oldSettleTime, newSettleTime);
if (lastSettleBit == 0) return (totalAssetCash, newSettleTime);
// Returns the next bit that is set in the bitmap
uint256 nextBitNum = bitmap.getNextBitNum();
while (nextBitNum != 0 && nextBitNum <= lastSettleBit) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
totalAssetCash = totalAssetCash.add(
_settlefCashAsset(account, currencyId, maturity, blockTime)
);
// Turn the bit off now that it is settled
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
bytes32 newBitmap;
while (nextBitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(oldSettleTime, nextBitNum);
(uint256 newBitNum, bool isValid) = DateTime.getBitNumFromMaturity(newSettleTime, maturity);
require(isValid); // dev: invalid new bit num
newBitmap = newBitmap.setBit(newBitNum, true);
// Turn the bit off now that it is remapped
bitmap = bitmap.setBit(nextBitNum, false);
nextBitNum = bitmap.getNextBitNum();
}
BitmapAssetsHandler.setAssetsBitmap(account, currencyId, newBitmap);
}
/// @dev Stateful settlement function to settle a bitmapped asset. Deletes the
/// asset from storage after calculating it.
function _settlefCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime
) private returns (int256 assetCash) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
int256 notional = store[account][currencyId][maturity].notional;
// Gets the current settlement rate or will store a new settlement rate if it does not
// yet exist.
AssetRateParameters memory rate =
AssetRate.buildSettlementRateStateful(currencyId, maturity, blockTime);
assetCash = rate.convertFromUnderlying(notional);
delete store[account][currencyId][maturity];
return assetCash;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../markets/DateTime.sol";
import "../portfolio/PortfolioHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/ABDKMath64x64.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AssetHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using CashGroup for CashGroupParameters;
using AssetRate for AssetRateParameters;
function isLiquidityToken(uint256 assetType) internal pure returns (bool) {
return
assetType >= Constants.MIN_LIQUIDITY_TOKEN_INDEX &&
assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX;
}
/// @notice Liquidity tokens settle every 90 days (not at the designated maturity). This method
/// calculates the settlement date for any PortfolioAsset.
function getSettlementDate(PortfolioAsset memory asset) internal pure returns (uint256) {
require(asset.assetType > 0 && asset.assetType <= Constants.MAX_LIQUIDITY_TOKEN_INDEX); // dev: settlement date invalid asset type
// 3 month tokens and fCash tokens settle at maturity
if (asset.assetType <= Constants.MIN_LIQUIDITY_TOKEN_INDEX) return asset.maturity;
uint256 marketLength = DateTime.getTradedMarket(asset.assetType - 1);
// Liquidity tokens settle at tRef + 90 days. The formula to get a maturity is:
// maturity = tRef + marketLength
// Here we calculate:
// tRef = (maturity - marketLength) + 90 days
return asset.maturity.sub(marketLength).add(Constants.QUARTER);
}
/// @notice Returns the continuously compounded discount rate given an oracle rate and a time to maturity.
/// The formula is: e^(-rate * timeToMaturity).
function getDiscountFactor(uint256 timeToMaturity, uint256 oracleRate)
internal
pure
returns (int256)
{
int128 expValue =
ABDKMath64x64.fromUInt(oracleRate.mul(timeToMaturity).div(Constants.IMPLIED_RATE_TIME));
expValue = ABDKMath64x64.div(expValue, Constants.RATE_PRECISION_64x64);
expValue = ABDKMath64x64.exp(ABDKMath64x64.neg(expValue));
expValue = ABDKMath64x64.mul(expValue, Constants.RATE_PRECISION_64x64);
int256 discountFactor = ABDKMath64x64.toInt(expValue);
return discountFactor;
}
/// @notice Present value of an fCash asset without any risk adjustments.
function getPresentfCashValue(
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor = getDiscountFactor(timeToMaturity, oracleRate);
require(discountFactor <= Constants.RATE_PRECISION); // dev: get present value invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Present value of an fCash asset with risk adjustments. Positive fCash value will be discounted more
/// heavily than the oracle rate given and vice versa for negative fCash.
function getRiskAdjustedPresentfCashValue(
CashGroupParameters memory cashGroup,
int256 notional,
uint256 maturity,
uint256 blockTime,
uint256 oracleRate
) internal pure returns (int256) {
if (notional == 0) return 0;
// NOTE: this will revert if maturity < blockTime. That is the correct behavior because we cannot
// discount matured assets.
uint256 timeToMaturity = maturity.sub(blockTime);
int256 discountFactor;
if (notional > 0) {
// If fCash is positive then discounting by a higher rate will result in a smaller
// discount factor (e ^ -x), meaning a lower positive fCash value.
discountFactor = getDiscountFactor(
timeToMaturity,
oracleRate.add(cashGroup.getfCashHaircut())
);
} else {
uint256 debtBuffer = cashGroup.getDebtBuffer();
// If the adjustment exceeds the oracle rate we floor the value of the fCash
// at the notional value. We don't want to require the account to hold more than
// absolutely required.
if (debtBuffer >= oracleRate) return notional;
discountFactor = getDiscountFactor(timeToMaturity, oracleRate - debtBuffer);
}
require(discountFactor <= Constants.RATE_PRECISION); // dev: get risk adjusted pv, invalid discount factor
return notional.mulInRatePrecision(discountFactor);
}
/// @notice Returns the non haircut claims on cash and fCash by the liquidity token.
function getCashClaims(PortfolioAsset memory token, MarketParameters memory market)
internal
pure
returns (int256 assetCash, int256 fCash)
{
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset, get cash claims
assetCash = market.totalAssetCash.mul(token.notional).div(market.totalLiquidity);
fCash = market.totalfCash.mul(token.notional).div(market.totalLiquidity);
}
/// @notice Returns the haircut claims on cash and fCash
function getHaircutCashClaims(
PortfolioAsset memory token,
MarketParameters memory market,
CashGroupParameters memory cashGroup
) internal pure returns (int256 assetCash, int256 fCash) {
require(isLiquidityToken(token.assetType) && token.notional >= 0); // dev: invalid asset get haircut cash claims
require(token.currencyId == cashGroup.currencyId); // dev: haircut cash claims, currency id mismatch
// This won't overflow, the liquidity token haircut is stored as an uint8
int256 haircut = int256(cashGroup.getLiquidityHaircut(token.assetType));
assetCash =
_calcToken(market.totalAssetCash, token.notional, haircut, market.totalLiquidity);
fCash =
_calcToken(market.totalfCash, token.notional, haircut, market.totalLiquidity);
return (assetCash, fCash);
}
/// @dev This is here to clean up the stack in getHaircutCashClaims
function _calcToken(
int256 numerator,
int256 tokens,
int256 haircut,
int256 liquidity
) private pure returns (int256) {
return numerator.mul(tokens).mul(haircut).div(Constants.PERCENTAGE_DECIMALS).div(liquidity);
}
/// @notice Returns the asset cash claim and the present value of the fCash asset (if it exists)
function getLiquidityTokenValue(
uint256 index,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
PortfolioAsset[] memory assets,
uint256 blockTime,
bool riskAdjusted
) internal view returns (int256, int256) {
PortfolioAsset memory liquidityToken = assets[index];
{
(uint256 marketIndex, bool idiosyncratic) =
DateTime.getMarketIndex(
cashGroup.maxMarketIndex,
liquidityToken.maturity,
blockTime
);
// Liquidity tokens can never be idiosyncratic
require(!idiosyncratic); // dev: idiosyncratic liquidity token
// This market will always be initialized, if a liquidity token exists that means the
// market has some liquidity in it.
cashGroup.loadMarket(market, marketIndex, true, blockTime);
}
int256 assetCashClaim;
int256 fCashClaim;
if (riskAdjusted) {
(assetCashClaim, fCashClaim) = getHaircutCashClaims(liquidityToken, market, cashGroup);
} else {
(assetCashClaim, fCashClaim) = getCashClaims(liquidityToken, market);
}
// Find the matching fCash asset and net off the value, assumes that the portfolio is sorted and
// in that case we know the previous asset will be the matching fCash asset
if (index > 0) {
PortfolioAsset memory maybefCash = assets[index - 1];
if (
maybefCash.assetType == Constants.FCASH_ASSET_TYPE &&
maybefCash.currencyId == liquidityToken.currencyId &&
maybefCash.maturity == liquidityToken.maturity
) {
// Net off the fCashClaim here and we will discount it to present value in the second pass.
// WARNING: this modifies the portfolio in memory and therefore we cannot store this portfolio!
maybefCash.notional = maybefCash.notional.add(fCashClaim);
// This state will prevent the fCash asset from being stored.
maybefCash.storageState = AssetStorageState.RevertIfStored;
return (assetCashClaim, 0);
}
}
// If not matching fCash asset found then get the pv directly
if (riskAdjusted) {
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
fCashClaim,
liquidityToken.maturity,
blockTime,
market.oracleRate
);
return (assetCashClaim, pv);
} else {
int256 pv =
getPresentfCashValue(fCashClaim, liquidityToken.maturity, blockTime, market.oracleRate);
return (assetCashClaim, pv);
}
}
/// @notice Returns present value of all assets in the cash group as asset cash and the updated
/// portfolio index where the function has ended.
/// @return the value of the cash group in asset cash
function getNetCashGroupValue(
PortfolioAsset[] memory assets,
CashGroupParameters memory cashGroup,
MarketParameters memory market,
uint256 blockTime,
uint256 portfolioIndex
) internal view returns (int256, uint256) {
int256 presentValueAsset;
int256 presentValueUnderlying;
// First calculate value of liquidity tokens because we need to net off fCash value
// before discounting to present value
for (uint256 i = portfolioIndex; i < assets.length; i++) {
if (!isLiquidityToken(assets[i].assetType)) continue;
if (assets[i].currencyId != cashGroup.currencyId) break;
(int256 assetCashClaim, int256 pv) =
getLiquidityTokenValue(
i,
cashGroup,
market,
assets,
blockTime,
true // risk adjusted
);
presentValueAsset = presentValueAsset.add(assetCashClaim);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
uint256 j = portfolioIndex;
for (; j < assets.length; j++) {
PortfolioAsset memory a = assets[j];
if (a.assetType != Constants.FCASH_ASSET_TYPE) continue;
// If we hit a different currency id then we've accounted for all assets in this currency
// j will mark the index where we don't have this currency anymore
if (a.currencyId != cashGroup.currencyId) break;
uint256 oracleRate = cashGroup.calculateOracleRate(a.maturity, blockTime);
int256 pv =
getRiskAdjustedPresentfCashValue(
cashGroup,
a.notional,
a.maturity,
blockTime,
oracleRate
);
presentValueUnderlying = presentValueUnderlying.add(pv);
}
presentValueAsset = presentValueAsset.add(
cashGroup.assetRate.convertFromUnderlying(presentValueUnderlying)
);
return (presentValueAsset, j);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./Types.sol";
import "./Constants.sol";
import "../../interfaces/notional/IRewarder.sol";
import "../../interfaces/aave/ILendingPool.sol";
library LibStorage {
/// @dev Offset for the initial slot in lib storage, gives us this number of storage slots
/// available in StorageLayoutV1 and all subsequent storage layouts that inherit from it.
uint256 private constant STORAGE_SLOT_BASE = 1000000;
/// @dev Set to MAX_TRADED_MARKET_INDEX * 2, Solidity does not allow assigning constants from imported values
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @dev Theoretical maximum for MAX_PORTFOLIO_ASSETS, however, we limit this to MAX_TRADED_MARKET_INDEX
/// in practice. It is possible to exceed that value during liquidation up to 14 potential assets.
uint256 private constant MAX_PORTFOLIO_ASSETS = 16;
/// @dev Storage IDs for storage buckets. Each id maps to an internal storage
/// slot used for a particular mapping
/// WARNING: APPEND ONLY
enum StorageId {
Unused,
AccountStorage,
nTokenContext,
nTokenAddress,
nTokenDeposit,
nTokenInitialization,
Balance,
Token,
SettlementRate,
CashGroup,
Market,
AssetsBitmap,
ifCashBitmap,
PortfolioArray,
// WARNING: this nTokenTotalSupply storage object was used for a buggy version
// of the incentives calculation. It should only be used for accounts who have
// not claimed before the migration
nTokenTotalSupply_deprecated,
AssetRate,
ExchangeRate,
nTokenTotalSupply,
SecondaryIncentiveRewarder,
LendingPool
}
/// @dev Mapping from an account address to account context
function getAccountStorage() internal pure
returns (mapping(address => AccountContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AccountStorage);
assembly { store.slot := slot }
}
/// @dev Mapping from an nToken address to nTokenContext
function getNTokenContextStorage() internal pure
returns (mapping(address => nTokenContext) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenContext);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to nTokenAddress
function getNTokenAddressStorage() internal pure
returns (mapping(uint256 => address) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenAddress);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to uint32 fixed length array of
/// deposit factors. Deposit shares and leverage thresholds are stored striped to
/// reduce the number of storage reads.
function getNTokenDepositStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenDeposit);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to fixed length array of initialization factors,
/// stored striped like deposit shares.
function getNTokenInitStorage() internal pure
returns (mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenInitialization);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currencyId to it's balance storage for that currency
function getBalanceStorage() internal pure
returns (mapping(address => mapping(uint256 => BalanceStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Balance);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to a boolean for underlying or asset token to
/// the TokenStorage
function getTokenStorage() internal pure
returns (mapping(uint256 => mapping(bool => TokenStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Token);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its corresponding SettlementRate
function getSettlementRateStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => SettlementRateStorage)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SettlementRate);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to its tightly packed cash group parameters
function getCashGroupStorage() internal pure
returns (mapping(uint256 => bytes32) storage store)
{
uint256 slot = _getStorageSlot(StorageId.CashGroup);
assembly { store.slot := slot }
}
/// @dev Mapping from currency id to maturity to settlement date for a market
function getMarketStorage() internal pure
returns (mapping(uint256 => mapping(uint256 => mapping(uint256 => MarketStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.Market);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its assets bitmap
function getAssetsBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => bytes32)) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetsBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to currency id to its maturity to its corresponding ifCash balance
function getifCashBitmapStorage() internal pure
returns (mapping(address => mapping(uint256 => mapping(uint256 => ifCashStorage))) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ifCashBitmap);
assembly { store.slot := slot }
}
/// @dev Mapping from account to its fixed length array of portfolio assets
function getPortfolioArrayStorage() internal pure
returns (mapping(address => PortfolioAssetStorage[MAX_PORTFOLIO_ASSETS]) storage store)
{
uint256 slot = _getStorageSlot(StorageId.PortfolioArray);
assembly { store.slot := slot }
}
function getDeprecatedNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage_deprecated) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply_deprecated);
assembly { store.slot := slot }
}
/// @dev Mapping from nToken address to its total supply values
function getNTokenTotalSupplyStorage() internal pure
returns (mapping(address => nTokenTotalSupplyStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.nTokenTotalSupply);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and asset for trading
/// and free collateral. Mapping is from currency id to rate storage object.
function getAssetRateStorage() internal pure
returns (mapping(uint256 => AssetRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.AssetRate);
assembly { store.slot := slot }
}
/// @dev Returns the exchange rate between an underlying currency and ETH for free
/// collateral purposes. Mapping is from currency id to rate storage object.
function getExchangeRateStorage() internal pure
returns (mapping(uint256 => ETHRateStorage) storage store)
{
uint256 slot = _getStorageSlot(StorageId.ExchangeRate);
assembly { store.slot := slot }
}
/// @dev Returns the address of a secondary incentive rewarder for an nToken if it exists
function getSecondaryIncentiveRewarder() internal pure
returns (mapping(address => IRewarder) storage store)
{
uint256 slot = _getStorageSlot(StorageId.SecondaryIncentiveRewarder);
assembly { store.slot := slot }
}
/// @dev Returns the address of the lending pool
function getLendingPool() internal pure returns (LendingPoolStorage storage store) {
uint256 slot = _getStorageSlot(StorageId.LendingPool);
assembly { store.slot := slot }
}
/// @dev Get the storage slot given a storage ID.
/// @param storageId An entry in `StorageId`
/// @return slot The storage slot.
function _getStorageSlot(StorageId storageId)
private
pure
returns (uint256 slot)
{
// This should never overflow with a reasonable `STORAGE_SLOT_EXP`
// because Solidity will do a range check on `storageId` during the cast.
return uint256(storageId) + STORAGE_SLOT_BASE;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../AccountContextHandler.sol";
import "../markets/CashGroup.sol";
import "../valuation/AssetHandler.sol";
import "../../math/Bitmap.sol";
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Constants.sol";
import "../../global/Types.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library BitmapAssetsHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
using Bitmap for bytes32;
using CashGroup for CashGroupParameters;
using AccountContextHandler for AccountContext;
function getAssetsBitmap(address account, uint256 currencyId) internal view returns (bytes32 assetsBitmap) {
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
return store[account][currencyId];
}
function setAssetsBitmap(
address account,
uint256 currencyId,
bytes32 assetsBitmap
) internal {
require(assetsBitmap.totalBitsSet() <= Constants.MAX_BITMAP_ASSETS, "Over max assets");
mapping(address => mapping(uint256 => bytes32)) storage store = LibStorage.getAssetsBitmapStorage();
store[account][currencyId] = assetsBitmap;
}
function getifCashNotional(
address account,
uint256 currencyId,
uint256 maturity
) internal view returns (int256 notional) {
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
return store[account][currencyId][maturity].notional;
}
/// @notice Adds multiple assets to a bitmap portfolio
function addMultipleifCashAssets(
address account,
AccountContext memory accountContext,
PortfolioAsset[] memory assets
) internal {
require(accountContext.isBitmapEnabled()); // dev: bitmap currency not set
uint256 currencyId = accountContext.bitmapCurrencyId;
for (uint256 i; i < assets.length; i++) {
PortfolioAsset memory asset = assets[i];
if (asset.notional == 0) continue;
require(asset.currencyId == currencyId); // dev: invalid asset in set ifcash assets
require(asset.assetType == Constants.FCASH_ASSET_TYPE); // dev: invalid asset in set ifcash assets
int256 finalNotional;
finalNotional = addifCashAsset(
account,
currencyId,
asset.maturity,
accountContext.nextSettleTime,
asset.notional
);
if (finalNotional < 0)
accountContext.hasDebt = accountContext.hasDebt | Constants.HAS_ASSET_DEBT;
}
}
/// @notice Add an ifCash asset in the bitmap and mapping. Updates the bitmap in memory
/// but not in storage.
/// @return the updated assets bitmap and the final notional amount
function addifCashAsset(
address account,
uint256 currencyId,
uint256 maturity,
uint256 nextSettleTime,
int256 notional
) internal returns (int256) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
mapping(address => mapping(uint256 =>
mapping(uint256 => ifCashStorage))) storage store = LibStorage.getifCashBitmapStorage();
ifCashStorage storage fCashSlot = store[account][currencyId][maturity];
(uint256 bitNum, bool isExact) = DateTime.getBitNumFromMaturity(nextSettleTime, maturity);
require(isExact); // dev: invalid maturity in set ifcash asset
if (assetsBitmap.isBitSet(bitNum)) {
// Bit is set so we read and update the notional amount
int256 finalNotional = notional.add(fCashSlot.notional);
require(type(int128).min <= finalNotional && finalNotional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(finalNotional);
// If the new notional is zero then turn off the bit
if (finalNotional == 0) {
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
setAssetsBitmap(account, currencyId, assetsBitmap);
return finalNotional;
}
if (notional != 0) {
// Bit is not set so we turn it on and update the mapping directly, no read required.
require(type(int128).min <= notional && notional <= type(int128).max); // dev: bitmap notional overflow
fCashSlot.notional = int128(notional);
assetsBitmap = assetsBitmap.setBit(bitNum, true);
setAssetsBitmap(account, currencyId, assetsBitmap);
}
return notional;
}
/// @notice Returns the present value of an asset
function getPresentValue(
address account,
uint256 currencyId,
uint256 maturity,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256) {
int256 notional = getifCashNotional(account, currencyId, maturity);
// In this case the asset has matured and the total value is just the notional amount
if (maturity <= blockTime) {
return notional;
} else {
uint256 oracleRate = cashGroup.calculateOracleRate(maturity, blockTime);
if (riskAdjusted) {
return AssetHandler.getRiskAdjustedPresentfCashValue(
cashGroup,
notional,
maturity,
blockTime,
oracleRate
);
} else {
return AssetHandler.getPresentfCashValue(
notional,
maturity,
blockTime,
oracleRate
);
}
}
}
function getNetPresentValueFromBitmap(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted,
bytes32 assetsBitmap
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 pv = getPresentValue(
account,
currencyId,
maturity,
blockTime,
cashGroup,
riskAdjusted
);
totalValueUnderlying = totalValueUnderlying.add(pv);
if (pv < 0) hasDebt = true;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
}
/// @notice Get the net present value of all the ifCash assets
function getifCashNetPresentValue(
address account,
uint256 currencyId,
uint256 nextSettleTime,
uint256 blockTime,
CashGroupParameters memory cashGroup,
bool riskAdjusted
) internal view returns (int256 totalValueUnderlying, bool hasDebt) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
return getNetPresentValueFromBitmap(
account,
currencyId,
nextSettleTime,
blockTime,
cashGroup,
riskAdjusted,
assetsBitmap
);
}
/// @notice Returns the ifCash assets as an array
function getifCashArray(
address account,
uint256 currencyId,
uint256 nextSettleTime
) internal view returns (PortfolioAsset[] memory) {
bytes32 assetsBitmap = getAssetsBitmap(account, currencyId);
uint256 index = assetsBitmap.totalBitsSet();
PortfolioAsset[] memory assets = new PortfolioAsset[](index);
index = 0;
uint256 bitNum = assetsBitmap.getNextBitNum();
while (bitNum != 0) {
uint256 maturity = DateTime.getMaturityFromBitNum(nextSettleTime, bitNum);
int256 notional = getifCashNotional(account, currencyId, maturity);
PortfolioAsset memory asset = assets[index];
asset.currencyId = currencyId;
asset.maturity = maturity;
asset.assetType = Constants.FCASH_ASSET_TYPE;
asset.notional = notional;
index += 1;
// Turn off the bit and look for the next one
assetsBitmap = assetsBitmap.setBit(bitNum, false);
bitNum = assetsBitmap.getNextBitNum();
}
return assets;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../interfaces/chainlink/AggregatorV2V3Interface.sol";
import "../../interfaces/notional/AssetRateAdapter.sol";
/// @notice Different types of internal tokens
/// - UnderlyingToken: underlying asset for a cToken (except for Ether)
/// - cToken: Compound interest bearing token
/// - cETH: Special handling for cETH tokens
/// - Ether: the one and only
/// - NonMintable: tokens that do not have an underlying (therefore not cTokens)
/// - aToken: Aave interest bearing tokens
enum TokenType {UnderlyingToken, cToken, cETH, Ether, NonMintable, aToken}
/// @notice Specifies the different trade action types in the system. Each trade action type is
/// encoded in a tightly packed bytes32 object. Trade action type is the first big endian byte of the
/// 32 byte trade action object. The schemas for each trade action type are defined below.
enum TradeActionType {
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 minImpliedRate, uint120 unused)
Lend,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 fCashAmount, uint32 maxImpliedRate, uint128 unused)
Borrow,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 assetCashAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
AddLiquidity,
// (uint8 TradeActionType, uint8 MarketIndex, uint88 tokenAmount, uint32 minImpliedRate, uint32 maxImpliedRate, uint88 unused)
RemoveLiquidity,
// (uint8 TradeActionType, uint32 Maturity, int88 fCashResidualAmount, uint128 unused)
PurchaseNTokenResidual,
// (uint8 TradeActionType, address CounterpartyAddress, int88 fCashAmountToSettle)
SettleCashDebt
}
/// @notice Specifies different deposit actions that can occur during BalanceAction or BalanceActionWithTrades
enum DepositActionType {
// No deposit action
None,
// Deposit asset cash, depositActionAmount is specified in asset cash external precision
DepositAsset,
// Deposit underlying tokens that are mintable to asset cash, depositActionAmount is specified in underlying token
// external precision
DepositUnderlying,
// Deposits specified asset cash external precision amount into an nToken and mints the corresponding amount of
// nTokens into the account
DepositAssetAndMintNToken,
// Deposits specified underlying in external precision, mints asset cash, and uses that asset cash to mint nTokens
DepositUnderlyingAndMintNToken,
// Redeems an nToken balance to asset cash. depositActionAmount is specified in nToken precision. Considered a deposit action
// because it deposits asset cash into an account. If there are fCash residuals that cannot be sold off, will revert.
RedeemNToken,
// Converts specified amount of asset cash balance already in Notional to nTokens. depositActionAmount is specified in
// Notional internal 8 decimal precision.
ConvertCashToNToken
}
/// @notice Used internally for PortfolioHandler state
enum AssetStorageState {NoChange, Update, Delete, RevertIfStored}
/****** Calldata objects ******/
/// @notice Defines a balance action for batchAction
struct BalanceAction {
// Deposit action to take (if any)
DepositActionType actionType;
uint16 currencyId;
// Deposit action amount must correspond to the depositActionType, see documentation above.
uint256 depositActionAmount;
// Withdraw an amount of asset cash specified in Notional internal 8 decimal precision
uint256 withdrawAmountInternalPrecision;
// If set to true, will withdraw entire cash balance. Useful if there may be an unknown amount of asset cash
// residual left from trading.
bool withdrawEntireCashBalance;
// If set to true, will redeem asset cash to the underlying token on withdraw.
bool redeemToUnderlying;
}
/// @notice Defines a balance action with a set of trades to do as well
struct BalanceActionWithTrades {
DepositActionType actionType;
uint16 currencyId;
uint256 depositActionAmount;
uint256 withdrawAmountInternalPrecision;
bool withdrawEntireCashBalance;
bool redeemToUnderlying;
// Array of tightly packed 32 byte objects that represent trades. See TradeActionType documentation
bytes32[] trades;
}
/****** In memory objects ******/
/// @notice Internal object that represents settled cash balances
struct SettleAmount {
uint256 currencyId;
int256 netCashChange;
}
/// @notice Internal object that represents a token
struct Token {
address tokenAddress;
bool hasTransferFee;
int256 decimals;
TokenType tokenType;
uint256 maxCollateralBalance;
}
/// @notice Internal object that represents an nToken portfolio
struct nTokenPortfolio {
CashGroupParameters cashGroup;
PortfolioState portfolioState;
int256 totalSupply;
int256 cashBalance;
uint256 lastInitializedTime;
bytes6 parameters;
address tokenAddress;
}
/// @notice Internal object used during liquidation
struct LiquidationFactors {
address account;
// Aggregate free collateral of the account denominated in ETH underlying, 8 decimal precision
int256 netETHValue;
// Amount of net local currency asset cash before haircuts and buffers available
int256 localAssetAvailable;
// Amount of net collateral currency asset cash before haircuts and buffers available
int256 collateralAssetAvailable;
// Haircut value of nToken holdings denominated in asset cash, will be local or collateral nTokens based
// on liquidation type
int256 nTokenHaircutAssetValue;
// nToken parameters for calculating liquidation amount
bytes6 nTokenParameters;
// ETH exchange rate from local currency to ETH
ETHRate localETHRate;
// ETH exchange rate from collateral currency to ETH
ETHRate collateralETHRate;
// Asset rate for the local currency, used in cross currency calculations to calculate local asset cash required
AssetRateParameters localAssetRate;
// Used during currency liquidations if the account has liquidity tokens
CashGroupParameters collateralCashGroup;
// Used during currency liquidations if it is only a calculation, defaults to false
bool isCalculation;
}
/// @notice Internal asset array portfolio state
struct PortfolioState {
// Array of currently stored assets
PortfolioAsset[] storedAssets;
// Array of new assets to add
PortfolioAsset[] newAssets;
uint256 lastNewAssetIndex;
// Holds the length of stored assets after accounting for deleted assets
uint256 storedAssetLength;
}
/// @notice In memory ETH exchange rate used during free collateral calculation.
struct ETHRate {
// The decimals (i.e. 10^rateDecimalPlaces) of the exchange rate, defined by the rate oracle
int256 rateDecimals;
// The exchange rate from base to ETH (if rate invert is required it is already done)
int256 rate;
// Amount of buffer as a multiple with a basis of 100 applied to negative balances.
int256 buffer;
// Amount of haircut as a multiple with a basis of 100 applied to positive balances
int256 haircut;
// Liquidation discount as a multiple with a basis of 100 applied to the exchange rate
// as an incentive given to liquidators.
int256 liquidationDiscount;
}
/// @notice Internal object used to handle balance state during a transaction
struct BalanceState {
uint16 currencyId;
// Cash balance stored in balance state at the beginning of the transaction
int256 storedCashBalance;
// nToken balance stored at the beginning of the transaction
int256 storedNTokenBalance;
// The net cash change as a result of asset settlement or trading
int256 netCashChange;
// Net asset transfers into or out of the account
int256 netAssetTransferInternalPrecision;
// Net token transfers into or out of the account
int256 netNTokenTransfer;
// Net token supply change from minting or redeeming
int256 netNTokenSupplyChange;
// The last time incentives were claimed for this currency
uint256 lastClaimTime;
// Accumulator for incentives that the account no longer has a claim over
uint256 accountIncentiveDebt;
}
/// @dev Asset rate used to convert between underlying cash and asset cash
struct AssetRateParameters {
// Address of the asset rate oracle
AssetRateAdapter rateOracle;
// The exchange rate from base to quote (if invert is required it is already done)
int256 rate;
// The decimals of the underlying, the rate converts to the underlying decimals
int256 underlyingDecimals;
}
/// @dev Cash group when loaded into memory
struct CashGroupParameters {
uint16 currencyId;
uint256 maxMarketIndex;
AssetRateParameters assetRate;
bytes32 data;
}
/// @dev A portfolio asset when loaded in memory
struct PortfolioAsset {
// Asset currency id
uint256 currencyId;
uint256 maturity;
// Asset type, fCash or liquidity token.
uint256 assetType;
// fCash amount or liquidity token amount
int256 notional;
// Used for managing portfolio asset state
uint256 storageSlot;
// The state of the asset for when it is written to storage
AssetStorageState storageState;
}
/// @dev Market object as represented in memory
struct MarketParameters {
bytes32 storageSlot;
uint256 maturity;
// Total amount of fCash available for purchase in the market.
int256 totalfCash;
// Total amount of cash available for purchase in the market.
int256 totalAssetCash;
// Total amount of liquidity tokens (representing a claim on liquidity) in the market.
int256 totalLiquidity;
// This is the previous annualized interest rate in RATE_PRECISION that the market traded
// at. This is used to calculate the rate anchor to smooth interest rates over time.
uint256 lastImpliedRate;
// Time lagged version of lastImpliedRate, used to value fCash assets at market rates while
// remaining resistent to flash loan attacks.
uint256 oracleRate;
// This is the timestamp of the previous trade
uint256 previousTradeTime;
}
/****** Storage objects ******/
/// @dev Token object in storage:
/// 20 bytes for token address
/// 1 byte for hasTransferFee
/// 1 byte for tokenType
/// 1 byte for tokenDecimals
/// 9 bytes for maxCollateralBalance (may not always be set)
struct TokenStorage {
// Address of the token
address tokenAddress;
// Transfer fees will change token deposit behavior
bool hasTransferFee;
TokenType tokenType;
uint8 decimalPlaces;
// Upper limit on how much of this token the contract can hold at any time
uint72 maxCollateralBalance;
}
/// @dev Exchange rate object as it is represented in storage, total storage is 25 bytes.
struct ETHRateStorage {
// Address of the rate oracle
AggregatorV2V3Interface rateOracle;
// The decimal places of precision that the rate oracle uses
uint8 rateDecimalPlaces;
// True of the exchange rate must be inverted
bool mustInvert;
// NOTE: both of these governance values are set with BUFFER_DECIMALS precision
// Amount of buffer to apply to the exchange rate for negative balances.
uint8 buffer;
// Amount of haircut to apply to the exchange rate for positive balances
uint8 haircut;
// Liquidation discount in percentage point terms, 106 means a 6% discount
uint8 liquidationDiscount;
}
/// @dev Asset rate oracle object as it is represented in storage, total storage is 21 bytes.
struct AssetRateStorage {
// Address of the rate oracle
AssetRateAdapter rateOracle;
// The decimal places of the underlying asset
uint8 underlyingDecimalPlaces;
}
/// @dev Governance parameters for a cash group, total storage is 9 bytes + 7 bytes for liquidity token haircuts
/// and 7 bytes for rate scalars, total of 23 bytes. Note that this is stored packed in the storage slot so there
/// are no indexes stored for liquidityTokenHaircuts or rateScalars, maxMarketIndex is used instead to determine the
/// length.
struct CashGroupSettings {
// Index of the AMMs on chain that will be made available. Idiosyncratic fCash
// that is dated less than the longest AMM will be tradable.
uint8 maxMarketIndex;
// Time window in 5 minute increments that the rate oracle will be averaged over
uint8 rateOracleTimeWindow5Min;
// Total fees per trade, specified in BPS
uint8 totalFeeBPS;
// Share of the fees given to the protocol, denominated in percentage
uint8 reserveFeeShare;
// Debt buffer specified in 5 BPS increments
uint8 debtBuffer5BPS;
// fCash haircut specified in 5 BPS increments
uint8 fCashHaircut5BPS;
// If an account has a negative cash balance, it can be settled by incurring debt at the 3 month market. This
// is the basis points for the penalty rate that will be added the current 3 month oracle rate.
uint8 settlementPenaltyRate5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationfCashHaircut5BPS;
// If an account has fCash that is being liquidated, this is the discount that the liquidator can purchase it for
uint8 liquidationDebtBuffer5BPS;
// Liquidity token haircut applied to cash claims, specified as a percentage between 0 and 100
uint8[] liquidityTokenHaircuts;
// Rate scalar used to determine the slippage of the market
uint8[] rateScalars;
}
/// @dev Holds account level context information used to determine settlement and
/// free collateral actions. Total storage is 28 bytes
struct AccountContext {
// Used to check when settlement must be triggered on an account
uint40 nextSettleTime;
// For lenders that never incur debt, we use this flag to skip the free collateral check.
bytes1 hasDebt;
// Length of the account's asset array
uint8 assetArrayLength;
// If this account has bitmaps set, this is the corresponding currency id
uint16 bitmapCurrencyId;
// 9 total active currencies possible (2 bytes each)
bytes18 activeCurrencies;
}
/// @dev Holds nToken context information mapped via the nToken address, total storage is
/// 16 bytes
struct nTokenContext {
// Currency id that the nToken represents
uint16 currencyId;
// Annual incentive emission rate denominated in WHOLE TOKENS (multiply by
// INTERNAL_TOKEN_PRECISION to get the actual rate)
uint32 incentiveAnnualEmissionRate;
// The last block time at utc0 that the nToken was initialized at, zero if it
// has never been initialized
uint32 lastInitializedTime;
// Length of the asset array, refers to the number of liquidity tokens an nToken
// currently holds
uint8 assetArrayLength;
// Each byte is a specific nToken parameter
bytes5 nTokenParameters;
// Reserved bytes for future usage
bytes15 _unused;
// Set to true if a secondary rewarder is set
bool hasSecondaryRewarder;
}
/// @dev Holds account balance information, total storage 32 bytes
struct BalanceStorage {
// Number of nTokens held by the account
uint80 nTokenBalance;
// Last time the account claimed their nTokens
uint32 lastClaimTime;
// Incentives that the account no longer has a claim over
uint56 accountIncentiveDebt;
// Cash balance of the account
int88 cashBalance;
}
/// @dev Holds information about a settlement rate, total storage 25 bytes
struct SettlementRateStorage {
uint40 blockTime;
uint128 settlementRate;
uint8 underlyingDecimalPlaces;
}
/// @dev Holds information about a market, total storage is 42 bytes so this spans
/// two storage words
struct MarketStorage {
// Total fCash in the market
uint80 totalfCash;
// Total asset cash in the market
uint80 totalAssetCash;
// Last annualized interest rate the market traded at
uint32 lastImpliedRate;
// Last recorded oracle rate for the market
uint32 oracleRate;
// Last time a trade was made
uint32 previousTradeTime;
// This is stored in slot + 1
uint80 totalLiquidity;
}
struct ifCashStorage {
// Notional amount of fCash at the slot, limited to int128 to allow for
// future expansion
int128 notional;
}
/// @dev A single portfolio asset in storage, total storage of 19 bytes
struct PortfolioAssetStorage {
// Currency Id for the asset
uint16 currencyId;
// Maturity of the asset
uint40 maturity;
// Asset type (fCash or Liquidity Token marker)
uint8 assetType;
// Notional
int88 notional;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes. This is the deprecated version
struct nTokenTotalSupplyStorage_deprecated {
// Total supply of the nToken
uint96 totalSupply;
// Integral of the total supply used for calculating the average total supply
uint128 integralTotalSupply;
// Last timestamp the supply value changed, used for calculating the integralTotalSupply
uint32 lastSupplyChangeTime;
}
/// @dev nToken total supply factors for the nToken, includes factors related
/// to claiming incentives, total storage 32 bytes.
struct nTokenTotalSupplyStorage {
// Total supply of the nToken
uint96 totalSupply;
// How many NOTE incentives should be issued per nToken in 1e18 precision
uint128 accumulatedNOTEPerNToken;
// Last timestamp when the accumulation happened
uint32 lastAccumulatedTime;
}
/// @dev Used in view methods to return account balances in a developer friendly manner
struct AccountBalance {
uint16 currencyId;
int256 cashBalance;
int256 nTokenBalance;
uint256 lastClaimTime;
uint256 accountIncentiveDebt;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title All shared constants for the Notional system should be declared here.
library Constants {
uint8 internal constant CETH_DECIMAL_PLACES = 8;
// Token precision used for all internal balances, TokenHandler library ensures that we
// limit the dust amount caused by precision mismatches
int256 internal constant INTERNAL_TOKEN_PRECISION = 1e8;
uint256 internal constant INCENTIVE_ACCUMULATION_PRECISION = 1e18;
// ETH will be initialized as the first currency
uint256 internal constant ETH_CURRENCY_ID = 1;
uint8 internal constant ETH_DECIMAL_PLACES = 18;
int256 internal constant ETH_DECIMALS = 1e18;
// Used to prevent overflow when converting decimal places to decimal precision values via
// 10**decimalPlaces. This is a safe value for int256 and uint256 variables. We apply this
// constraint when storing decimal places in governance.
uint256 internal constant MAX_DECIMAL_PLACES = 36;
// Address of the reserve account
address internal constant RESERVE = address(0);
// Most significant bit
bytes32 internal constant MSB =
0x8000000000000000000000000000000000000000000000000000000000000000;
// Each bit set in this mask marks where an active market should be in the bitmap
// if the first bit refers to the reference time. Used to detect idiosyncratic
// fcash in the nToken accounts
bytes32 internal constant ACTIVE_MARKETS_MASK = (
MSB >> ( 90 - 1) | // 3 month
MSB >> (105 - 1) | // 6 month
MSB >> (135 - 1) | // 1 year
MSB >> (147 - 1) | // 2 year
MSB >> (183 - 1) | // 5 year
MSB >> (211 - 1) | // 10 year
MSB >> (251 - 1) // 20 year
);
// Basis for percentages
int256 internal constant PERCENTAGE_DECIMALS = 100;
// Max number of traded markets, also used as the maximum number of assets in a portfolio array
uint256 internal constant MAX_TRADED_MARKET_INDEX = 7;
// Max number of fCash assets in a bitmap, this is based on the gas costs of calculating free collateral
// for a bitmap portfolio
uint256 internal constant MAX_BITMAP_ASSETS = 20;
uint256 internal constant FIVE_MINUTES = 300;
// Internal date representations, note we use a 6/30/360 week/month/year convention here
uint256 internal constant DAY = 86400;
// We use six day weeks to ensure that all time references divide evenly
uint256 internal constant WEEK = DAY * 6;
uint256 internal constant MONTH = WEEK * 5;
uint256 internal constant QUARTER = MONTH * 3;
uint256 internal constant YEAR = QUARTER * 4;
// These constants are used in DateTime.sol
uint256 internal constant DAYS_IN_WEEK = 6;
uint256 internal constant DAYS_IN_MONTH = 30;
uint256 internal constant DAYS_IN_QUARTER = 90;
// Offsets for each time chunk denominated in days
uint256 internal constant MAX_DAY_OFFSET = 90;
uint256 internal constant MAX_WEEK_OFFSET = 360;
uint256 internal constant MAX_MONTH_OFFSET = 2160;
uint256 internal constant MAX_QUARTER_OFFSET = 7650;
// Offsets for each time chunk denominated in bits
uint256 internal constant WEEK_BIT_OFFSET = 90;
uint256 internal constant MONTH_BIT_OFFSET = 135;
uint256 internal constant QUARTER_BIT_OFFSET = 195;
// This is a constant that represents the time period that all rates are normalized by, 360 days
uint256 internal constant IMPLIED_RATE_TIME = 360 * DAY;
// Number of decimal places that rates are stored in, equals 100%
int256 internal constant RATE_PRECISION = 1e9;
// One basis point in RATE_PRECISION terms
uint256 internal constant BASIS_POINT = uint256(RATE_PRECISION / 10000);
// Used to when calculating the amount to deleverage of a market when minting nTokens
uint256 internal constant DELEVERAGE_BUFFER = 300 * BASIS_POINT;
// Used for scaling cash group factors
uint256 internal constant FIVE_BASIS_POINTS = 5 * BASIS_POINT;
// Used for residual purchase incentive and cash withholding buffer
uint256 internal constant TEN_BASIS_POINTS = 10 * BASIS_POINT;
// This is the ABDK64x64 representation of RATE_PRECISION
// RATE_PRECISION_64x64 = ABDKMath64x64.fromUint(RATE_PRECISION)
int128 internal constant RATE_PRECISION_64x64 = 0x3b9aca000000000000000000;
int128 internal constant LOG_RATE_PRECISION_64x64 = 382276781265598821176;
// Limit the market proportion so that borrowing cannot hit extremely high interest rates
int256 internal constant MAX_MARKET_PROPORTION = RATE_PRECISION * 99 / 100;
uint8 internal constant FCASH_ASSET_TYPE = 1;
// Liquidity token asset types are 1 + marketIndex (where marketIndex is 1-indexed)
uint8 internal constant MIN_LIQUIDITY_TOKEN_INDEX = 2;
uint8 internal constant MAX_LIQUIDITY_TOKEN_INDEX = 8;
// Used for converting bool to bytes1, solidity does not have a native conversion
// method for this
bytes1 internal constant BOOL_FALSE = 0x00;
bytes1 internal constant BOOL_TRUE = 0x01;
// Account context flags
bytes1 internal constant HAS_ASSET_DEBT = 0x01;
bytes1 internal constant HAS_CASH_DEBT = 0x02;
bytes2 internal constant ACTIVE_IN_PORTFOLIO = 0x8000;
bytes2 internal constant ACTIVE_IN_BALANCES = 0x4000;
bytes2 internal constant UNMASK_FLAGS = 0x3FFF;
uint16 internal constant MAX_CURRENCIES = uint16(UNMASK_FLAGS);
// Equal to 100% of all deposit amounts for nToken liquidity across fCash markets.
int256 internal constant DEPOSIT_PERCENT_BASIS = 1e8;
// nToken Parameters: there are offsets in the nTokenParameters bytes6 variable returned
// in nTokenHandler. Each constant represents a position in the byte array.
uint8 internal constant LIQUIDATION_HAIRCUT_PERCENTAGE = 0;
uint8 internal constant CASH_WITHHOLDING_BUFFER = 1;
uint8 internal constant RESIDUAL_PURCHASE_TIME_BUFFER = 2;
uint8 internal constant PV_HAIRCUT_PERCENTAGE = 3;
uint8 internal constant RESIDUAL_PURCHASE_INCENTIVE = 4;
// Liquidation parameters
// Default percentage of collateral that a liquidator is allowed to liquidate, will be higher if the account
// requires more collateral to be liquidated
int256 internal constant DEFAULT_LIQUIDATION_PORTION = 40;
// Percentage of local liquidity token cash claim delivered to the liquidator for liquidating liquidity tokens
int256 internal constant TOKEN_REPO_INCENTIVE_PERCENT = 30;
// Pause Router liquidation enabled states
bytes1 internal constant LOCAL_CURRENCY_ENABLED = 0x01;
bytes1 internal constant COLLATERAL_CURRENCY_ENABLED = 0x02;
bytes1 internal constant LOCAL_FCASH_ENABLED = 0x04;
bytes1 internal constant CROSS_CURRENCY_FCASH_ENABLED = 0x08;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../global/Constants.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library DateTime {
using SafeMath for uint256;
/// @notice Returns the current reference time which is how all the AMM dates are calculated.
function getReferenceTime(uint256 blockTime) internal pure returns (uint256) {
require(blockTime >= Constants.QUARTER);
return blockTime - (blockTime % Constants.QUARTER);
}
/// @notice Truncates a date to midnight UTC time
function getTimeUTC0(uint256 time) internal pure returns (uint256) {
require(time >= Constants.DAY);
return time - (time % Constants.DAY);
}
/// @notice These are the predetermined market offsets for trading
/// @dev Markets are 1-indexed because the 0 index means that no markets are listed for the cash group.
function getTradedMarket(uint256 index) internal pure returns (uint256) {
if (index == 1) return Constants.QUARTER;
if (index == 2) return 2 * Constants.QUARTER;
if (index == 3) return Constants.YEAR;
if (index == 4) return 2 * Constants.YEAR;
if (index == 5) return 5 * Constants.YEAR;
if (index == 6) return 10 * Constants.YEAR;
if (index == 7) return 20 * Constants.YEAR;
revert("Invalid index");
}
/// @notice Determines if the maturity falls on one of the valid on chain market dates.
function isValidMarketMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
if (maturity % Constants.QUARTER != 0) return false;
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
if (maturity == tRef.add(DateTime.getTradedMarket(i))) return true;
}
return false;
}
/// @notice Determines if an idiosyncratic maturity is valid and returns the bit reference that is the case.
function isValidMaturity(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (bool) {
uint256 tRef = DateTime.getReferenceTime(blockTime);
uint256 maxMaturity = tRef.add(DateTime.getTradedMarket(maxMarketIndex));
// Cannot trade past max maturity
if (maturity > maxMaturity) return false;
// prettier-ignore
(/* */, bool isValid) = DateTime.getBitNumFromMaturity(blockTime, maturity);
return isValid;
}
/// @notice Returns the market index for a given maturity, if the maturity is idiosyncratic
/// will return the nearest market index that is larger than the maturity.
/// @return uint marketIndex, bool isIdiosyncratic
function getMarketIndex(
uint256 maxMarketIndex,
uint256 maturity,
uint256 blockTime
) internal pure returns (uint256, bool) {
require(maxMarketIndex > 0, "CG: no markets listed");
require(maxMarketIndex <= Constants.MAX_TRADED_MARKET_INDEX, "CG: market index bound");
uint256 tRef = DateTime.getReferenceTime(blockTime);
for (uint256 i = 1; i <= maxMarketIndex; i++) {
uint256 marketMaturity = tRef.add(DateTime.getTradedMarket(i));
// If market matches then is not idiosyncratic
if (marketMaturity == maturity) return (i, false);
// Returns the market that is immediately greater than the maturity
if (marketMaturity > maturity) return (i, true);
}
revert("CG: no market found");
}
/// @notice Given a bit number and the reference time of the first bit, returns the bit number
/// of a given maturity.
/// @return bitNum and a true or false if the maturity falls on the exact bit
function getBitNumFromMaturity(uint256 blockTime, uint256 maturity)
internal
pure
returns (uint256, bool)
{
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
// Maturities must always divide days evenly
if (maturity % Constants.DAY != 0) return (0, false);
// Maturity cannot be in the past
if (blockTimeUTC0 >= maturity) return (0, false);
// Overflow check done above
// daysOffset has no remainders, checked above
uint256 daysOffset = (maturity - blockTimeUTC0) / Constants.DAY;
// These if statements need to fall through to the next one
if (daysOffset <= Constants.MAX_DAY_OFFSET) {
return (daysOffset, true);
} else if (daysOffset <= Constants.MAX_WEEK_OFFSET) {
// (daysOffset - MAX_DAY_OFFSET) is the days overflow into the week portion, must be > 0
// (blockTimeUTC0 % WEEK) / DAY is the offset into the week portion
// This returns the offset from the previous max offset in days
uint256 offsetInDays =
daysOffset -
Constants.MAX_DAY_OFFSET +
(blockTimeUTC0 % Constants.WEEK) /
Constants.DAY;
return (
// This converts the offset in days to its corresponding bit position, truncating down
// if it does not divide evenly into DAYS_IN_WEEK
Constants.WEEK_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_WEEK,
(offsetInDays % Constants.DAYS_IN_WEEK) == 0
);
} else if (daysOffset <= Constants.MAX_MONTH_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_WEEK_OFFSET +
(blockTimeUTC0 % Constants.MONTH) /
Constants.DAY;
return (
Constants.MONTH_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_MONTH,
(offsetInDays % Constants.DAYS_IN_MONTH) == 0
);
} else if (daysOffset <= Constants.MAX_QUARTER_OFFSET) {
uint256 offsetInDays =
daysOffset -
Constants.MAX_MONTH_OFFSET +
(blockTimeUTC0 % Constants.QUARTER) /
Constants.DAY;
return (
Constants.QUARTER_BIT_OFFSET + offsetInDays / Constants.DAYS_IN_QUARTER,
(offsetInDays % Constants.DAYS_IN_QUARTER) == 0
);
}
// This is the maximum 1-indexed bit num, it is never valid because it is beyond the 20
// year max maturity
return (256, false);
}
/// @notice Given a bit number and a block time returns the maturity that the bit number
/// should reference. Bit numbers are one indexed.
function getMaturityFromBitNum(uint256 blockTime, uint256 bitNum)
internal
pure
returns (uint256)
{
require(bitNum != 0); // dev: cash group get maturity from bit num is zero
require(bitNum <= 256); // dev: cash group get maturity from bit num overflow
uint256 blockTimeUTC0 = getTimeUTC0(blockTime);
uint256 firstBit;
if (bitNum <= Constants.WEEK_BIT_OFFSET) {
return blockTimeUTC0 + bitNum * Constants.DAY;
} else if (bitNum <= Constants.MONTH_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_DAY_OFFSET * Constants.DAY -
// This backs up to the day that is divisible by a week
(blockTimeUTC0 % Constants.WEEK);
return firstBit + (bitNum - Constants.WEEK_BIT_OFFSET) * Constants.WEEK;
} else if (bitNum <= Constants.QUARTER_BIT_OFFSET) {
firstBit =
blockTimeUTC0 +
Constants.MAX_WEEK_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.MONTH);
return firstBit + (bitNum - Constants.MONTH_BIT_OFFSET) * Constants.MONTH;
} else {
firstBit =
blockTimeUTC0 +
Constants.MAX_MONTH_OFFSET * Constants.DAY -
(blockTimeUTC0 % Constants.QUARTER);
return firstBit + (bitNum - Constants.QUARTER_BIT_OFFSET) * Constants.QUARTER;
}
}
}
// SPDX-License-Identifier: BSD-4-Clause
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity ^0.5.0 || ^0.6.0 || ^0.7.0;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/*
* Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/*
* Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param 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);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m)));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
bool negative = x < 0 && y & 1 == 1;
uint256 absX = uint128 (x < 0 ? -x : x);
uint256 absResult;
absResult = 0x100000000000000000000000000000000;
if (absX <= 0x10000000000000000) {
absX <<= 63;
while (y != 0) {
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x2 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x4 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
if (y & 0x8 != 0) {
absResult = absResult * absX >> 127;
}
absX = absX * absX >> 127;
y >>= 4;
}
absResult >>= 64;
} else {
uint256 absXShift = 63;
if (absX < 0x1000000000000000000000000) { absX <<= 32; absXShift -= 32; }
if (absX < 0x10000000000000000000000000000) { absX <<= 16; absXShift -= 16; }
if (absX < 0x1000000000000000000000000000000) { absX <<= 8; absXShift -= 8; }
if (absX < 0x10000000000000000000000000000000) { absX <<= 4; absXShift -= 4; }
if (absX < 0x40000000000000000000000000000000) { absX <<= 2; absXShift -= 2; }
if (absX < 0x80000000000000000000000000000000) { absX <<= 1; absXShift -= 1; }
uint256 resultShift = 0;
while (y != 0) {
require (absXShift < 64);
if (y & 0x1 != 0) {
absResult = absResult * absX >> 127;
resultShift += absXShift;
if (absResult > 0x100000000000000000000000000000000) {
absResult >>= 1;
resultShift += 1;
}
}
absX = absX * absX >> 127;
absXShift <<= 1;
if (absX >= 0x100000000000000000000000000000000) {
absX >>= 1;
absXShift += 1;
}
y >>= 1;
}
require (resultShift < 64);
absResult >>= 64 - resultShift;
}
int256 result = negative ? -int256 (absResult) : int256 (absResult);
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << uint256 (127 - msb);
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= uint256 (63 - (x >> 64));
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x) private pure returns (uint128) {
if (x == 0) return 0;
else {
uint256 xx = x;
uint256 r = 1;
if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; }
if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; }
if (xx >= 0x100000000) { xx >>= 32; r <<= 16; }
if (xx >= 0x10000) { xx >>= 16; r <<= 8; }
if (xx >= 0x100) { xx >>= 8; r <<= 4; }
if (xx >= 0x10) { xx >>= 4; r <<= 2; }
if (xx >= 0x8) { r <<= 1; }
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1;
r = (r + x / r) >> 1; // Seven iterations should be enough
uint256 r1 = x / r;
return uint128 (r < r1 ? r : r1);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
import "./AggregatorInterface.sol";
import "./AggregatorV3Interface.sol";
interface AggregatorV2V3Interface is AggregatorInterface, AggregatorV3Interface
{
}
// SPDX-License-Identifier: GPL-v3
pragma solidity >=0.7.0;
/// @notice Used as a wrapper for tokens that are interest bearing for an
/// underlying token. Follows the cToken interface, however, can be adapted
/// for other interest bearing tokens.
interface AssetRateAdapter {
function token() external view returns (address);
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
function underlying() external view returns (address);
function getExchangeRateStateful() external returns (int256);
function getExchangeRateView() external view returns (int256);
function getAnnualizedSupplyRate() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0;
interface AggregatorInterface {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
function latestRound() external view returns (uint256);
function getAnswer(uint256 roundId) external view returns (int256);
function getTimestamp(uint256 roundId) external view returns (uint256);
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 updatedAt);
event NewRound(uint256 indexed roundId, address indexed startedBy, uint256 startedAt);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.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: GPL-3.0-only
pragma solidity ^0.7.0;
interface IRewarder {
function claimRewards(
address account,
uint16 currencyId,
uint256 nTokenBalanceBefore,
uint256 nTokenBalanceAfter,
int256 netNTokenSupplyChange,
uint256 NOTETokensClaimed
) external;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
struct LendingPoolStorage {
ILendingPool lendingPool;
}
interface ILendingPool {
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset) external view returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset) external view returns (ReserveData memory);
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./TokenHandler.sol";
import "../nToken/nTokenHandler.sol";
import "../nToken/nTokenSupply.sol";
import "../../math/SafeInt256.sol";
import "../../external/MigrateIncentives.sol";
import "../../../interfaces/notional/IRewarder.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library Incentives {
using SafeMath for uint256;
using SafeInt256 for int256;
/// @notice Calculates the total incentives to claim including those claimed under the previous
/// less accurate calculation. Once an account is migrated it will only claim incentives under
/// the more accurate regime
function calculateIncentivesToClaim(
BalanceState memory balanceState,
address tokenAddress,
uint256 accumulatedNOTEPerNToken,
uint256 finalNTokenBalance
) internal view returns (uint256 incentivesToClaim) {
if (balanceState.lastClaimTime > 0) {
// If lastClaimTime is set then the account had incentives under the
// previous regime. Will calculate the final amount of incentives to claim here
// under the previous regime.
incentivesToClaim = MigrateIncentives.migrateAccountFromPreviousCalculation(
tokenAddress,
balanceState.storedNTokenBalance.toUint(),
balanceState.lastClaimTime,
// In this case the accountIncentiveDebt is stored as lastClaimIntegralSupply under
// the old calculation
balanceState.accountIncentiveDebt
);
// This marks the account as migrated and lastClaimTime will no longer be used
balanceState.lastClaimTime = 0;
// This value will be set immediately after this, set this to zero so that the calculation
// establishes a new baseline.
balanceState.accountIncentiveDebt = 0;
}
// If an account was migrated then they have no accountIncentivesDebt and should accumulate
// incentives based on their share since the new regime calculation started.
// If an account is just initiating their nToken balance then storedNTokenBalance will be zero
// and they will have no incentives to claim.
// This calculation uses storedNTokenBalance which is the balance of the account up until this point,
// this is important to ensure that the account does not claim for nTokens that they will mint or
// redeem on a going forward basis.
// The calculation below has the following precision:
// storedNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION - (accountIncentivesDebt) INTERNAL_TOKEN_PRECISION
incentivesToClaim = incentivesToClaim.add(
balanceState.storedNTokenBalance.toUint()
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.sub(balanceState.accountIncentiveDebt)
);
// Update accountIncentivesDebt denominated in INTERNAL_TOKEN_PRECISION which marks the portion
// of the accumulatedNOTE that the account no longer has a claim over. Use the finalNTokenBalance
// here instead of storedNTokenBalance to mark the overall incentives claim that the account
// does not have a claim over. We do not aggregate this value with the previous accountIncentiveDebt
// because accumulatedNOTEPerNToken is already an aggregated value.
// The calculation below has the following precision:
// finalNTokenBalance (INTERNAL_TOKEN_PRECISION)
// MUL accumulatedNOTEPerNToken (INCENTIVE_ACCUMULATION_PRECISION)
// DIV INCENTIVE_ACCUMULATION_PRECISION
// = INTERNAL_TOKEN_PRECISION
balanceState.accountIncentiveDebt = finalNTokenBalance
.mul(accumulatedNOTEPerNToken)
.div(Constants.INCENTIVE_ACCUMULATION_PRECISION);
}
/// @notice Incentives must be claimed every time nToken balance changes.
/// @dev BalanceState.accountIncentiveDebt is updated in place here
function claimIncentives(
BalanceState memory balanceState,
address account,
uint256 finalNTokenBalance
) internal returns (uint256 incentivesToClaim) {
uint256 blockTime = block.timestamp;
address tokenAddress = nTokenHandler.nTokenAddress(balanceState.currencyId);
// This will updated the nToken storage and return what the accumulatedNOTEPerNToken
// is up until this current block time in 1e18 precision
uint256 accumulatedNOTEPerNToken = nTokenSupply.changeNTokenSupply(
tokenAddress,
balanceState.netNTokenSupplyChange,
blockTime
);
incentivesToClaim = calculateIncentivesToClaim(
balanceState,
tokenAddress,
accumulatedNOTEPerNToken,
finalNTokenBalance
);
// If a secondary incentive rewarder is set, then call it
IRewarder rewarder = nTokenHandler.getSecondaryRewarder(tokenAddress);
if (address(rewarder) != address(0)) {
rewarder.claimRewards(
account,
balanceState.currencyId,
// When this method is called from finalize, the storedNTokenBalance has not
// been updated to finalNTokenBalance yet so this is the balance before the change.
balanceState.storedNTokenBalance.toUint(),
finalNTokenBalance,
// When the rewarder is called, totalSupply has been updated already so may need to
// adjust its calculation using the net supply change figure here. Supply change
// may be zero when nTokens are transferred.
balanceState.netNTokenSupplyChange,
incentivesToClaim
);
}
if (incentivesToClaim > 0) TokenHandler.transferIncentive(account, incentivesToClaim);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../math/SafeInt256.sol";
import "../../global/LibStorage.sol";
import "../../global/Types.sol";
import "../../global/Constants.sol";
import "../../global/Deployments.sol";
import "./protocols/AaveHandler.sol";
import "./protocols/CompoundHandler.sol";
import "./protocols/GenericToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Handles all external token transfers and events
library TokenHandler {
using SafeInt256 for int256;
using SafeMath for uint256;
function setMaxCollateralBalance(uint256 currencyId, uint72 maxCollateralBalance) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][false];
tokenStorage.maxCollateralBalance = maxCollateralBalance;
}
function getAssetToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, false);
}
function getUnderlyingToken(uint256 currencyId) internal view returns (Token memory) {
return _getToken(currencyId, true);
}
/// @notice Gets token data for a particular currency id, if underlying is set to true then returns
/// the underlying token. (These may not always exist)
function _getToken(uint256 currencyId, bool underlying) private view returns (Token memory) {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
TokenStorage storage tokenStorage = store[currencyId][underlying];
return
Token({
tokenAddress: tokenStorage.tokenAddress,
hasTransferFee: tokenStorage.hasTransferFee,
// No overflow, restricted on storage
decimals: int256(10**tokenStorage.decimalPlaces),
tokenType: tokenStorage.tokenType,
maxCollateralBalance: tokenStorage.maxCollateralBalance
});
}
/// @notice Sets a token for a currency id.
function setToken(
uint256 currencyId,
bool underlying,
TokenStorage memory tokenStorage
) internal {
mapping(uint256 => mapping(bool => TokenStorage)) storage store = LibStorage.getTokenStorage();
if (tokenStorage.tokenType == TokenType.Ether && currencyId == Constants.ETH_CURRENCY_ID) {
// Hardcoded parameters for ETH just to make sure we don't get it wrong.
TokenStorage storage ts = store[currencyId][true];
ts.tokenAddress = address(0);
ts.hasTransferFee = false;
ts.tokenType = TokenType.Ether;
ts.decimalPlaces = Constants.ETH_DECIMAL_PLACES;
ts.maxCollateralBalance = 0;
return;
}
// Check token address
require(tokenStorage.tokenAddress != address(0), "TH: address is zero");
// Once a token is set we cannot override it. In the case that we do need to do change a token address
// then we should explicitly upgrade this method to allow for a token to be changed.
Token memory token = _getToken(currencyId, underlying);
require(
token.tokenAddress == tokenStorage.tokenAddress || token.tokenAddress == address(0),
"TH: token cannot be reset"
);
require(0 < tokenStorage.decimalPlaces
&& tokenStorage.decimalPlaces <= Constants.MAX_DECIMAL_PLACES, "TH: invalid decimals");
// Validate token type
require(tokenStorage.tokenType != TokenType.Ether); // dev: ether can only be set once
if (underlying) {
// Underlying tokens cannot have max collateral balances, the contract only has a balance temporarily
// during mint and redeem actions.
require(tokenStorage.maxCollateralBalance == 0); // dev: underlying cannot have max collateral balance
require(tokenStorage.tokenType == TokenType.UnderlyingToken); // dev: underlying token inconsistent
} else {
require(tokenStorage.tokenType != TokenType.UnderlyingToken); // dev: underlying token inconsistent
}
if (tokenStorage.tokenType == TokenType.cToken || tokenStorage.tokenType == TokenType.aToken) {
// Set the approval for the underlying so that we can mint cTokens or aTokens
Token memory underlyingToken = getUnderlyingToken(currencyId);
// cTokens call transfer from the tokenAddress, but aTokens use the LendingPool
// to initiate all transfers
address approvalAddress = tokenStorage.tokenType == TokenType.cToken ?
tokenStorage.tokenAddress :
address(LibStorage.getLendingPool().lendingPool);
// ERC20 tokens should return true on success for an approval, but Tether
// does not return a value here so we use the NonStandard interface here to
// check that the approval was successful.
IEIP20NonStandard(underlyingToken.tokenAddress).approve(
approvalAddress,
type(uint256).max
);
GenericToken.checkReturnCode();
}
store[currencyId][underlying] = tokenStorage;
}
/**
* @notice If a token is mintable then will mint it. At this point we expect to have the underlying
* balance in the contract already.
* @param assetToken the asset token to mint
* @param underlyingAmountExternal the amount of underlying to transfer to the mintable token
* @return the amount of asset tokens minted, will always be a positive integer
*/
function mint(Token memory assetToken, uint16 currencyId, uint256 underlyingAmountExternal) internal returns (int256) {
// aTokens return the principal plus interest value when calling the balanceOf selector. We cannot use this
// value in internal accounting since it will not allow individual users to accrue aToken interest. Use the
// scaledBalanceOf function call instead for internal accounting.
bytes4 balanceOfSelector = assetToken.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
uint256 startingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
if (assetToken.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
AaveHandler.mint(underlyingToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
CompoundHandler.mint(assetToken, underlyingAmountExternal);
} else if (assetToken.tokenType == TokenType.cETH) {
CompoundHandler.mintCETH(assetToken);
} else {
revert(); // dev: non mintable token
}
uint256 endingBalance = GenericToken.checkBalanceViaSelector(assetToken.tokenAddress, address(this), balanceOfSelector);
// This is the starting and ending balance in external precision
return SafeInt256.toInt(endingBalance.sub(startingBalance));
}
/**
* @notice If a token is redeemable to underlying will redeem it and transfer the underlying balance
* to the account
* @param assetToken asset token to redeem
* @param currencyId the currency id of the token
* @param account account to transfer the underlying to
* @param assetAmountExternal the amount to transfer in asset token denomination and external precision
* @return the actual amount of underlying tokens transferred. this is used as a return value back to the
* user, is not used for internal accounting purposes
*/
function redeem(
Token memory assetToken,
uint256 currencyId,
address account,
uint256 assetAmountExternal
) internal returns (int256) {
uint256 transferAmount;
if (assetToken.tokenType == TokenType.cETH) {
transferAmount = CompoundHandler.redeemCETH(assetToken, account, assetAmountExternal);
} else {
Token memory underlyingToken = getUnderlyingToken(currencyId);
if (assetToken.tokenType == TokenType.aToken) {
transferAmount = AaveHandler.redeem(underlyingToken, account, assetAmountExternal);
} else if (assetToken.tokenType == TokenType.cToken) {
transferAmount = CompoundHandler.redeem(assetToken, underlyingToken, account, assetAmountExternal);
} else {
revert(); // dev: non redeemable token
}
}
// Use the negative value here to signify that assets have left the protocol
return SafeInt256.toInt(transferAmount).neg();
}
/// @notice Handles transfers into and out of the system denominated in the external token decimal
/// precision.
function transfer(
Token memory token,
address account,
uint256 currencyId,
int256 netTransferExternal
) internal returns (int256 actualTransferExternal) {
// This will be true in all cases except for deposits where the token has transfer fees. For
// aTokens this value is set before convert from scaled balances to principal plus interest
actualTransferExternal = netTransferExternal;
if (token.tokenType == TokenType.aToken) {
Token memory underlyingToken = getUnderlyingToken(currencyId);
// aTokens need to be converted when we handle the transfer since the external balance format
// is not the same as the internal balance format that we use
netTransferExternal = AaveHandler.convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
netTransferExternal
);
}
if (netTransferExternal > 0) {
// Deposits must account for transfer fees.
int256 netDeposit = _deposit(token, account, uint256(netTransferExternal));
// If an aToken has a transfer fee this will still return a balance figure
// in scaledBalanceOf terms due to the selector
if (token.hasTransferFee) actualTransferExternal = netDeposit;
} else if (token.tokenType == TokenType.Ether) {
// netTransferExternal can only be negative or zero at this point
GenericToken.transferNativeTokenOut(account, uint256(netTransferExternal.neg()));
} else {
GenericToken.safeTransferOut(
token.tokenAddress,
account,
// netTransferExternal is zero or negative here
uint256(netTransferExternal.neg())
);
}
}
/// @notice Handles token deposits into Notional. If there is a transfer fee then we must
/// calculate the net balance after transfer. Amounts are denominated in the destination token's
/// precision.
function _deposit(
Token memory token,
address account,
uint256 amount
) private returns (int256) {
uint256 startingBalance;
uint256 endingBalance;
bytes4 balanceOfSelector = token.tokenType == TokenType.aToken ?
AaveHandler.scaledBalanceOfSelector :
GenericToken.defaultBalanceOfSelector;
if (token.hasTransferFee) {
startingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
GenericToken.safeTransferIn(token.tokenAddress, account, amount);
if (token.hasTransferFee || token.maxCollateralBalance > 0) {
// If aTokens have a max collateral balance then it will be applied against the scaledBalanceOf. This is probably
// the correct behavior because if collateral accrues interest over time we should not somehow go over the
// maxCollateralBalance due to the passage of time.
endingBalance = GenericToken.checkBalanceViaSelector(token.tokenAddress, address(this), balanceOfSelector);
}
if (token.maxCollateralBalance > 0) {
int256 internalPrecisionBalance = convertToInternal(token, SafeInt256.toInt(endingBalance));
// Max collateral balance is stored as uint72, no overflow
require(internalPrecisionBalance <= SafeInt256.toInt(token.maxCollateralBalance)); // dev: over max collateral balance
}
// Math is done in uint inside these statements and will revert on negative
if (token.hasTransferFee) {
return SafeInt256.toInt(endingBalance.sub(startingBalance));
} else {
return SafeInt256.toInt(amount);
}
}
function convertToInternal(Token memory token, int256 amount) internal pure returns (int256) {
// If token decimals > INTERNAL_TOKEN_PRECISION:
// on deposit: resulting dust will accumulate to protocol
// on withdraw: protocol may lose dust amount. However, withdraws are only calculated based
// on a conversion from internal token precision to external token precision so therefore dust
// amounts cannot be specified for withdraws.
// If token decimals < INTERNAL_TOKEN_PRECISION then this will add zeros to the
// end of amount and will not result in dust.
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
return amount.mul(Constants.INTERNAL_TOKEN_PRECISION).div(token.decimals);
}
function convertToExternal(Token memory token, int256 amount) internal pure returns (int256) {
if (token.decimals == Constants.INTERNAL_TOKEN_PRECISION) return amount;
// If token decimals > INTERNAL_TOKEN_PRECISION then this will increase amount
// by adding a number of zeros to the end and will not result in dust.
// If token decimals < INTERNAL_TOKEN_PRECISION:
// on deposit: Deposits are specified in external token precision and there is no loss of precision when
// tokens are converted from external to internal precision
// on withdraw: this calculation will round down such that the protocol retains the residual cash balance
return amount.mul(token.decimals).div(Constants.INTERNAL_TOKEN_PRECISION);
}
function transferIncentive(address account, uint256 tokensToTransfer) internal {
GenericToken.safeTransferOut(Deployments.NOTE_TOKEN_ADDRESS, account, tokensToTransfer);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "./Bitmap.sol";
/**
* Packs an uint value into a "floating point" storage slot. Used for storing
* lastClaimIntegralSupply values in balance storage. For these values, we don't need
* to maintain exact precision but we don't want to be limited by storage size overflows.
*
* A floating point value is defined by the 48 most significant bits and an 8 bit number
* of bit shifts required to restore its precision. The unpacked value will always be less
* than the packed value with a maximum absolute loss of precision of (2 ** bitShift) - 1.
*/
library FloatingPoint56 {
function packTo56Bits(uint256 value) internal pure returns (uint56) {
uint256 bitShift;
// If the value is over the uint48 max value then we will shift it down
// given the index of the most significant bit. We store this bit shift
// in the least significant byte of the 56 bit slot available.
if (value > type(uint48).max) bitShift = (Bitmap.getMSB(value) - 47);
uint256 shiftedValue = value >> bitShift;
return uint56((shiftedValue << 8) | bitShift);
}
function unpackFrom56Bits(uint256 value) internal pure returns (uint256) {
// The least significant 8 bits will be the amount to bit shift
uint256 bitShift = uint256(uint8(value));
return ((value >> 8) << bitShift);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenSupply.sol";
import "../markets/CashGroup.sol";
import "../markets/AssetRate.sol";
import "../portfolio/PortfolioHandler.sol";
import "../balances/BalanceHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenHandler {
using SafeInt256 for int256;
/// @dev Mirror of the value in LibStorage, solidity compiler does not allow assigning
/// two constants to each other.
uint256 private constant NUM_NTOKEN_MARKET_FACTORS = 14;
/// @notice Returns an account context object that is specific to nTokens.
function getNTokenContext(address tokenAddress)
internal
view
returns (
uint16 currencyId,
uint256 incentiveAnnualEmissionRate,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
)
{
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
currencyId = context.currencyId;
incentiveAnnualEmissionRate = context.incentiveAnnualEmissionRate;
lastInitializedTime = context.lastInitializedTime;
assetArrayLength = context.assetArrayLength;
parameters = context.nTokenParameters;
}
/// @notice Returns the nToken token address for a given currency
function nTokenAddress(uint256 currencyId) internal view returns (address tokenAddress) {
mapping(uint256 => address) storage store = LibStorage.getNTokenAddressStorage();
return store[currencyId];
}
/// @notice Called by governance to set the nToken token address and its reverse lookup. Cannot be
/// reset once this is set.
function setNTokenAddress(uint16 currencyId, address tokenAddress) internal {
mapping(uint256 => address) storage addressStore = LibStorage.getNTokenAddressStorage();
require(addressStore[currencyId] == address(0), "PT: token address exists");
mapping(address => nTokenContext) storage contextStore = LibStorage.getNTokenContextStorage();
nTokenContext storage context = contextStore[tokenAddress];
require(context.currencyId == 0, "PT: currency exists");
// This will initialize all other context slots to zero
context.currencyId = currencyId;
addressStore[currencyId] = tokenAddress;
}
/// @notice Set nToken token collateral parameters
function setNTokenCollateralParameters(
address tokenAddress,
uint8 residualPurchaseIncentive10BPS,
uint8 pvHaircutPercentage,
uint8 residualPurchaseTimeBufferHours,
uint8 cashWithholdingBuffer10BPS,
uint8 liquidationHaircutPercentage
) internal {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
require(liquidationHaircutPercentage <= Constants.PERCENTAGE_DECIMALS, "Invalid haircut");
// The pv haircut percentage must be less than the liquidation percentage or else liquidators will not
// get profit for liquidating nToken.
require(pvHaircutPercentage < liquidationHaircutPercentage, "Invalid pv haircut");
// Ensure that the cash withholding buffer is greater than the residual purchase incentive or
// the nToken may not have enough cash to pay accounts to buy its negative ifCash
require(residualPurchaseIncentive10BPS <= cashWithholdingBuffer10BPS, "Invalid discounts");
bytes5 parameters =
(bytes5(uint40(residualPurchaseIncentive10BPS)) |
(bytes5(uint40(pvHaircutPercentage)) << 8) |
(bytes5(uint40(residualPurchaseTimeBufferHours)) << 16) |
(bytes5(uint40(cashWithholdingBuffer10BPS)) << 24) |
(bytes5(uint40(liquidationHaircutPercentage)) << 32));
// Set the parameters
context.nTokenParameters = parameters;
}
/// @notice Sets a secondary rewarder contract on an nToken so that incentives can come from a different
/// contract, aside from the native NOTE token incentives.
function setSecondaryRewarder(
uint16 currencyId,
IRewarder rewarder
) internal {
address tokenAddress = nTokenAddress(currencyId);
// nToken must exist for a secondary rewarder
require(tokenAddress != address(0));
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
// Setting the rewarder to address(0) will disable it. We use a context setting here so that
// we can save a storage read before getting the rewarder
context.hasSecondaryRewarder = (address(rewarder) != address(0));
LibStorage.getSecondaryIncentiveRewarder()[tokenAddress] = rewarder;
}
/// @notice Returns the secondary rewarder if it is set
function getSecondaryRewarder(address tokenAddress) internal view returns (IRewarder) {
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
if (context.hasSecondaryRewarder) {
return LibStorage.getSecondaryIncentiveRewarder()[tokenAddress];
} else {
return IRewarder(address(0));
}
}
function setArrayLengthAndInitializedTime(
address tokenAddress,
uint8 arrayLength,
uint256 lastInitializedTime
) internal {
require(lastInitializedTime >= 0 && uint256(lastInitializedTime) < type(uint32).max); // dev: next settle time overflow
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.lastInitializedTime = uint32(lastInitializedTime);
context.assetArrayLength = arrayLength;
}
/// @notice Returns the array of deposit shares and leverage thresholds for nTokens
function getDepositParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory depositShares, int256[] memory leverageThresholds)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
(depositShares, leverageThresholds) = _getParameters(depositParameters, maxMarketIndex, false);
}
/// @notice Sets the deposit parameters
/// @dev We pack the values in alternating between the two parameters into either one or two
// storage slots depending on the number of markets. This is to save storage reads when we use the parameters.
function setDepositParameters(
uint256 currencyId,
uint32[] calldata depositShares,
uint32[] calldata leverageThresholds
) internal {
require(
depositShares.length <= Constants.MAX_TRADED_MARKET_INDEX,
"PT: deposit share length"
);
require(depositShares.length == leverageThresholds.length, "PT: leverage share length");
uint256 shareSum;
for (uint256 i; i < depositShares.length; i++) {
// This cannot overflow in uint 256 with 9 max slots
shareSum = shareSum + depositShares[i];
require(
leverageThresholds[i] > 0 && leverageThresholds[i] < Constants.RATE_PRECISION,
"PT: leverage threshold"
);
}
// Total deposit share must add up to 100%
require(shareSum == uint256(Constants.DEPOSIT_PERCENT_BASIS), "PT: deposit shares sum");
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenDepositStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage depositParameters = store[currencyId];
_setParameters(depositParameters, depositShares, leverageThresholds);
}
/// @notice Sets the initialization parameters for the markets, these are read only when markets
/// are initialized
function setInitializationParameters(
uint256 currencyId,
uint32[] calldata annualizedAnchorRates,
uint32[] calldata proportions
) internal {
require(annualizedAnchorRates.length <= Constants.MAX_TRADED_MARKET_INDEX, "PT: annualized anchor rates length");
require(proportions.length == annualizedAnchorRates.length, "PT: proportions length");
for (uint256 i; i < proportions.length; i++) {
// Proportions must be between zero and the rate precision
require(annualizedAnchorRates[i] > 0, "NT: anchor rate zero");
require(
proportions[i] > 0 && proportions[i] < Constants.RATE_PRECISION,
"PT: invalid proportion"
);
}
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
_setParameters(initParameters, annualizedAnchorRates, proportions);
}
/// @notice Returns the array of initialization parameters for a given currency.
function getInitializationParameters(uint256 currencyId, uint256 maxMarketIndex)
internal
view
returns (int256[] memory annualizedAnchorRates, int256[] memory proportions)
{
mapping(uint256 => uint32[NUM_NTOKEN_MARKET_FACTORS]) storage store = LibStorage.getNTokenInitStorage();
uint32[NUM_NTOKEN_MARKET_FACTORS] storage initParameters = store[currencyId];
(annualizedAnchorRates, proportions) = _getParameters(initParameters, maxMarketIndex, true);
}
function _getParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint256 maxMarketIndex,
bool noUnset
) private view returns (int256[] memory, int256[] memory) {
uint256 index = 0;
int256[] memory array1 = new int256[](maxMarketIndex);
int256[] memory array2 = new int256[](maxMarketIndex);
for (uint256 i; i < maxMarketIndex; i++) {
array1[i] = slot[index];
index++;
array2[i] = slot[index];
index++;
if (noUnset) {
require(array1[i] > 0 && array2[i] > 0, "PT: init value zero");
}
}
return (array1, array2);
}
function _setParameters(
uint32[NUM_NTOKEN_MARKET_FACTORS] storage slot,
uint32[] calldata array1,
uint32[] calldata array2
) private {
uint256 index = 0;
for (uint256 i = 0; i < array1.length; i++) {
slot[index] = array1[i];
index++;
slot[index] = array2[i];
index++;
}
}
function loadNTokenPortfolioNoCashGroup(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
nToken.tokenAddress = nTokenAddress(currencyId);
// prettier-ignore
(
/* currencyId */,
/* incentiveRate */,
uint256 lastInitializedTime,
uint8 assetArrayLength,
bytes5 parameters
) = getNTokenContext(nToken.tokenAddress);
// prettier-ignore
(
uint256 totalSupply,
/* accumulatedNOTEPerNToken */,
/* lastAccumulatedTime */
) = nTokenSupply.getStoredNTokenSupplyFactors(nToken.tokenAddress);
nToken.lastInitializedTime = lastInitializedTime;
nToken.totalSupply = int256(totalSupply);
nToken.parameters = parameters;
nToken.portfolioState = PortfolioHandler.buildPortfolioState(
nToken.tokenAddress,
assetArrayLength,
0
);
// prettier-ignore
(
nToken.cashBalance,
/* nTokenBalance */,
/* lastClaimTime */,
/* accountIncentiveDebt */
) = BalanceHandler.getBalanceStorage(nToken.tokenAddress, currencyId);
}
/// @notice Uses buildCashGroupStateful
function loadNTokenPortfolioStateful(nTokenPortfolio memory nToken, uint16 currencyId)
internal
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupStateful(currencyId);
}
/// @notice Uses buildCashGroupView
function loadNTokenPortfolioView(nTokenPortfolio memory nToken, uint16 currencyId)
internal
view
{
loadNTokenPortfolioNoCashGroup(nToken, currencyId);
nToken.cashGroup = CashGroup.buildCashGroupView(currencyId);
}
/// @notice Returns the next settle time for the nToken which is 1 quarter away
function getNextSettleTime(nTokenPortfolio memory nToken) internal pure returns (uint256) {
if (nToken.lastInitializedTime == 0) return 0;
return DateTime.getReferenceTime(nToken.lastInitializedTime) + Constants.QUARTER;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../../global/LibStorage.sol";
import "../../math/SafeInt256.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library nTokenSupply {
using SafeInt256 for int256;
using SafeMath for uint256;
/// @notice Retrieves stored nToken supply and related factors. Do not use accumulatedNOTEPerNToken for calculating
/// incentives! Use `getUpdatedAccumulatedNOTEPerNToken` instead.
function getStoredNTokenSupplyFactors(address tokenAddress)
internal
view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
totalSupply = nTokenStorage.totalSupply;
// NOTE: DO NOT USE THIS RETURNED VALUE FOR CALCULATING INCENTIVES. The accumulatedNOTEPerNToken
// must be updated given the block time. Use `getUpdatedAccumulatedNOTEPerNToken` instead
accumulatedNOTEPerNToken = nTokenStorage.accumulatedNOTEPerNToken;
lastAccumulatedTime = nTokenStorage.lastAccumulatedTime;
}
/// @notice Returns the updated accumulated NOTE per nToken for calculating incentives
function getUpdatedAccumulatedNOTEPerNToken(address tokenAddress, uint256 blockTime)
internal view
returns (
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
uint256 lastAccumulatedTime
)
{
(
totalSupply,
accumulatedNOTEPerNToken,
lastAccumulatedTime
) = getStoredNTokenSupplyFactors(tokenAddress);
// nToken totalSupply is never allowed to drop to zero but we check this here to avoid
// divide by zero errors during initialization. Also ensure that lastAccumulatedTime is not
// zero to avoid a massive accumulation amount on initialization.
if (blockTime > lastAccumulatedTime && lastAccumulatedTime > 0 && totalSupply > 0) {
// prettier-ignore
(
/* currencyId */,
uint256 emissionRatePerYear,
/* initializedTime */,
/* assetArrayLength */,
/* parameters */
) = nTokenHandler.getNTokenContext(tokenAddress);
uint256 additionalNOTEAccumulatedPerNToken = _calculateAdditionalNOTE(
// Emission rate is denominated in whole tokens, scale to 1e8 decimals here
emissionRatePerYear.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION)),
// Time since last accumulation (overflow checked above)
blockTime - lastAccumulatedTime,
totalSupply
);
accumulatedNOTEPerNToken = accumulatedNOTEPerNToken.add(additionalNOTEAccumulatedPerNToken);
require(accumulatedNOTEPerNToken < type(uint128).max); // dev: accumulated NOTE overflow
}
}
/// @notice additionalNOTEPerNToken accumulated since last accumulation time in 1e18 precision
function _calculateAdditionalNOTE(
uint256 emissionRatePerYear,
uint256 timeSinceLastAccumulation,
uint256 totalSupply
)
private
pure
returns (uint256)
{
// If we use 18 decimal places as the accumulation precision then we will overflow uint128 when
// a single nToken has accumulated 3.4 x 10^20 NOTE tokens. This isn't possible since the max
// NOTE that can accumulate is 10^16 (100 million NOTE in 1e8 precision) so we should be safe
// using 18 decimal places and uint128 storage slot
// timeSinceLastAccumulation (SECONDS)
// accumulatedNOTEPerSharePrecision (1e18)
// emissionRatePerYear (INTERNAL_TOKEN_PRECISION)
// DIVIDE BY
// YEAR (SECONDS)
// totalSupply (INTERNAL_TOKEN_PRECISION)
return timeSinceLastAccumulation
.mul(Constants.INCENTIVE_ACCUMULATION_PRECISION)
.mul(emissionRatePerYear)
.div(Constants.YEAR)
// totalSupply > 0 is checked in the calling function
.div(totalSupply);
}
/// @notice Updates the nToken token supply amount when minting or redeeming.
/// @param tokenAddress address of the nToken
/// @param netChange positive or negative change to the total nToken supply
/// @param blockTime current block time
/// @return accumulatedNOTEPerNToken updated to the given block time
function changeNTokenSupply(
address tokenAddress,
int256 netChange,
uint256 blockTime
) internal returns (uint256) {
(
uint256 totalSupply,
uint256 accumulatedNOTEPerNToken,
/* uint256 lastAccumulatedTime */
) = getUpdatedAccumulatedNOTEPerNToken(tokenAddress, blockTime);
// Update storage variables
mapping(address => nTokenTotalSupplyStorage) storage store = LibStorage.getNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage storage nTokenStorage = store[tokenAddress];
int256 newTotalSupply = int256(totalSupply).add(netChange);
// We allow newTotalSupply to equal zero here even though it is prevented from being redeemed down to
// exactly zero by other internal logic inside nTokenRedeem. This is meant to be purely an overflow check.
require(0 <= newTotalSupply && uint256(newTotalSupply) < type(uint96).max); // dev: nToken supply overflow
nTokenStorage.totalSupply = uint96(newTotalSupply);
// NOTE: overflow checked inside getUpdatedAccumulatedNOTEPerNToken so that behavior here mirrors what
// the user would see if querying the view function
nTokenStorage.accumulatedNOTEPerNToken = uint128(accumulatedNOTEPerNToken);
require(blockTime < type(uint32).max); // dev: block time overflow
nTokenStorage.lastAccumulatedTime = uint32(blockTime);
return accumulatedNOTEPerNToken;
}
/// @notice Called by governance to set the new emission rate
function setIncentiveEmissionRate(address tokenAddress, uint32 newEmissionsRate, uint256 blockTime) internal {
// Ensure that the accumulatedNOTEPerNToken updates to the current block time before we update the
// emission rate
changeNTokenSupply(tokenAddress, 0, blockTime);
mapping(address => nTokenContext) storage store = LibStorage.getNTokenContextStorage();
nTokenContext storage context = store[tokenAddress];
context.incentiveAnnualEmissionRate = newEmissionsRate;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/LibStorage.sol";
import "../internal/nToken/nTokenHandler.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
/**
* @notice Deployed library for migration of incentives from the old (inaccurate) calculation
* to a newer, more accurate calculation based on SushiSwap MasterChef math. The more accurate
* calculation is inside `Incentives.sol` and this library holds the legacy calculation. System
* migration code can be found in `MigrateIncentivesFix.sol`
*/
library MigrateIncentives {
using SafeMath for uint256;
/// @notice Calculates the claimable incentives for a particular nToken and account in the
/// previous regime. This should only ever be called ONCE for an account / currency combination
/// to get the incentives accrued up until the migration date.
function migrateAccountFromPreviousCalculation(
address tokenAddress,
uint256 nTokenBalance,
uint256 lastClaimTime,
uint256 lastClaimIntegralSupply
) external view returns (uint256) {
(
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) = _getMigratedIncentiveValues(tokenAddress);
// This if statement should never be true but we return 0 just in case
if (lastClaimTime == 0 || lastClaimTime >= finalMigrationTime) return 0;
// No overflow here, checked above. All incentives are claimed up until finalMigrationTime
// using the finalTotalIntegralSupply. Both these values are set on migration and will not
// change.
uint256 timeSinceMigration = finalMigrationTime - lastClaimTime;
// (timeSinceMigration * INTERNAL_TOKEN_PRECISION * finalEmissionRatePerYear) / YEAR
uint256 incentiveRate =
timeSinceMigration
.mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
// Migration emission rate is stored as is, denominated in whole tokens
.mul(finalEmissionRatePerYear).mul(uint256(Constants.INTERNAL_TOKEN_PRECISION))
.div(Constants.YEAR);
// Returns the average supply using the integral of the total supply.
uint256 avgTotalSupply = finalTotalIntegralSupply.sub(lastClaimIntegralSupply).div(timeSinceMigration);
if (avgTotalSupply == 0) return 0;
uint256 incentivesToClaim = nTokenBalance.mul(incentiveRate).div(avgTotalSupply);
// incentiveRate has a decimal basis of 1e16 so divide by token precision to reduce to 1e8
incentivesToClaim = incentivesToClaim.div(uint256(Constants.INTERNAL_TOKEN_PRECISION));
return incentivesToClaim;
}
function _getMigratedIncentiveValues(
address tokenAddress
) private view returns (
uint256 finalEmissionRatePerYear,
uint256 finalTotalIntegralSupply,
uint256 finalMigrationTime
) {
mapping(address => nTokenTotalSupplyStorage_deprecated) storage store = LibStorage.getDeprecatedNTokenTotalSupplyStorage();
nTokenTotalSupplyStorage_deprecated storage d_nTokenStorage = store[tokenAddress];
// The total supply value is overridden as emissionRatePerYear during the initialization
finalEmissionRatePerYear = d_nTokenStorage.totalSupply;
finalTotalIntegralSupply = d_nTokenStorage.integralTotalSupply;
finalMigrationTime = d_nTokenStorage.lastSupplyChangeTime;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/// @title Hardcoded deployed contracts are listed here. These are hardcoded to reduce
/// gas costs for immutable addresses. They must be updated per environment that Notional
/// is deployed to.
library Deployments {
address internal constant NOTE_TOKEN_ADDRESS = 0xCFEAead4947f0705A14ec42aC3D44129E1Ef3eD5;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../../../global/Types.sol";
import "../../../global/LibStorage.sol";
import "../../../math/SafeInt256.sol";
import "../TokenHandler.sol";
import "../../../../interfaces/aave/IAToken.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
library AaveHandler {
using SafeMath for uint256;
using SafeInt256 for int256;
int256 internal constant RAY = 1e27;
int256 internal constant halfRAY = RAY / 2;
bytes4 internal constant scaledBalanceOfSelector = IAToken.scaledBalanceOf.selector;
/**
* @notice Mints an amount of aTokens corresponding to the the underlying.
* @param underlyingToken address of the underlying token to pass to Aave
* @param underlyingAmountExternal amount of underlying to deposit, in external precision
*/
function mint(Token memory underlyingToken, uint256 underlyingAmountExternal) internal {
// In AaveV3 this method is renamed to supply() but deposit() is still available for
// backwards compatibility: https://github.com/aave/aave-v3-core/blob/master/contracts/protocol/pool/Pool.sol#L755
// We use deposit here so that mainnet-fork tests against Aave v2 will pass.
LibStorage.getLendingPool().lendingPool.deposit(
underlyingToken.tokenAddress,
underlyingAmountExternal,
address(this),
0
);
}
/**
* @notice Redeems and sends an amount of aTokens to the specified account
* @param underlyingToken address of the underlying token to pass to Aave
* @param account account to receive the underlying
* @param assetAmountExternal amount of aTokens in scaledBalanceOf terms
*/
function redeem(
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
underlyingAmountExternal = convertFromScaledBalanceExternal(
underlyingToken.tokenAddress,
SafeInt256.toInt(assetAmountExternal)
).toUint();
LibStorage.getLendingPool().lendingPool.withdraw(
underlyingToken.tokenAddress,
underlyingAmountExternal,
account
);
}
/**
* @notice Takes an assetAmountExternal (in this case is the Aave balanceOf representing principal plus interest)
* and returns another assetAmountExternal value which represents the Aave scaledBalanceOf (representing a proportional
* claim on Aave principal plus interest onto the future). This conversion ensures that depositors into Notional will
* receive future Aave interest.
* @dev There is no loss of precision within this function since it does the exact same calculation as Aave.
* @param currencyId is the currency id
* @param assetAmountExternal an Aave token amount representing principal plus interest supplied by the user. This must
* be positive in this function, this method is only called when depositing aTokens directly
* @return scaledAssetAmountExternal the Aave scaledBalanceOf equivalent. The decimal precision of this value will
* be in external precision.
*/
function convertToScaledBalanceExternal(uint256 currencyId, int256 assetAmountExternal) internal view returns (int256) {
if (assetAmountExternal == 0) return 0;
require(assetAmountExternal > 0);
Token memory underlyingToken = TokenHandler.getUnderlyingToken(currencyId);
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken.tokenAddress);
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
int256 halfIndex = index / 2;
// Overflow will occur when: (a * RAY + halfIndex) > int256.max
require(assetAmountExternal <= (type(int256).max - halfIndex) / RAY);
// if index is zero then this will revert
return (assetAmountExternal * RAY + halfIndex) / index;
}
/**
* @notice Takes an assetAmountExternal (in this case is the internal scaledBalanceOf in external decimal precision)
* and returns another assetAmountExternal value which represents the Aave balanceOf representing the principal plus interest
* that will be transferred. This is required to maintain compatibility with Aave's ERC20 transfer functions.
* @dev There is no loss of precision because this does exactly what Aave's calculation would do
* @param underlyingToken token address of the underlying asset
* @param netScaledBalanceExternal an amount representing the scaledBalanceOf in external decimal precision calculated from
* Notional cash balances. This amount may be positive or negative depending on if assets are being deposited (positive) or
* withdrawn (negative).
* @return netBalanceExternal the Aave balanceOf equivalent as a signed integer
*/
function convertFromScaledBalanceExternal(address underlyingToken, int256 netScaledBalanceExternal) internal view returns (int256 netBalanceExternal) {
if (netScaledBalanceExternal == 0) return 0;
// We know that this value must be positive
int256 index = _getReserveNormalizedIncome(underlyingToken);
// Use the absolute value here so that the halfRay rounding is applied correctly for negative values
int256 abs = netScaledBalanceExternal.abs();
// Mimic the WadRay math performed by Aave (but do it in int256 instead)
// Overflow will occur when: (abs * index + halfRay) > int256.max
// Here the first term is computed at compile time so it just does a division. If index is zero then
// solidity will revert.
require(abs <= (type(int256).max - halfRAY) / index);
int256 absScaled = (abs * index + halfRAY) / RAY;
return netScaledBalanceExternal > 0 ? absScaled : absScaled.neg();
}
/// @dev getReserveNormalizedIncome returns a uint256, so we know that the return value here is
/// always positive even though we are converting to a signed int
function _getReserveNormalizedIncome(address underlyingAsset) private view returns (int256) {
return
SafeInt256.toInt(
LibStorage.getLendingPool().lendingPool.getReserveNormalizedIncome(underlyingAsset)
);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./GenericToken.sol";
import "../../../../interfaces/compound/CErc20Interface.sol";
import "../../../../interfaces/compound/CEtherInterface.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../global/Types.sol";
library CompoundHandler {
using SafeMath for uint256;
// Return code for cTokens that represents no error
uint256 internal constant COMPOUND_RETURN_CODE_NO_ERROR = 0;
function mintCETH(Token memory token) internal {
// Reverts on error
CEtherInterface(token.tokenAddress).mint{value: msg.value}();
}
function mint(Token memory token, uint256 underlyingAmountExternal) internal returns (int256) {
uint256 success = CErc20Interface(token.tokenAddress).mint(underlyingAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Mint");
}
function redeemCETH(
Token memory assetToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = address(this).balance;
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = address(this).balance;
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.transferNativeTokenOut(account, underlyingAmountExternal);
}
function redeem(
Token memory assetToken,
Token memory underlyingToken,
address account,
uint256 assetAmountExternal
) internal returns (uint256 underlyingAmountExternal) {
// Although the contract should never end with any ETH or underlying token balances, we still do this
// starting and ending check in the case that tokens are accidentally sent to the contract address. They
// will not be sent to some lucky address in a windfall.
uint256 startingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
uint256 success = CErc20Interface(assetToken.tokenAddress).redeem(assetAmountExternal);
require(success == COMPOUND_RETURN_CODE_NO_ERROR, "Redeem");
uint256 endingBalance = GenericToken.checkBalanceViaSelector(underlyingToken.tokenAddress, address(this), GenericToken.defaultBalanceOfSelector);
underlyingAmountExternal = endingBalance.sub(startingBalance);
// Withdraws the underlying amount out to the destination account
GenericToken.safeTransferOut(underlyingToken.tokenAddress, account, underlyingAmountExternal);
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
import "../../../../interfaces/IEIP20NonStandard.sol";
library GenericToken {
bytes4 internal constant defaultBalanceOfSelector = IEIP20NonStandard.balanceOf.selector;
/**
* @dev Manually checks the balance of an account using the method selector. Reduces bytecode size and allows
* for overriding the balanceOf selector to use scaledBalanceOf for aTokens
*/
function checkBalanceViaSelector(
address token,
address account,
bytes4 balanceOfSelector
) internal returns (uint256 balance) {
(bool success, bytes memory returnData) = token.staticcall(abi.encodeWithSelector(balanceOfSelector, account));
require(success);
(balance) = abi.decode(returnData, (uint256));
}
function transferNativeTokenOut(
address account,
uint256 amount
) internal {
// This does not work with contracts, but is reentrancy safe. If contracts want to withdraw underlying
// ETH they will have to withdraw the cETH token and then redeem it manually.
payable(account).transfer(amount);
}
function safeTransferOut(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transfer(account, amount);
checkReturnCode();
}
function safeTransferIn(
address token,
address account,
uint256 amount
) internal {
IEIP20NonStandard(token).transferFrom(account, address(this), amount);
checkReturnCode();
}
function checkReturnCode() internal pure {
bool success;
uint256[1] memory result;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := 1 // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(result, 0, 32)
success := mload(result) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "ERC20");
}
}
// 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: GPL-3.0-only
pragma solidity ^0.7.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IAToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function symbol() external view returns (string memory);
}
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user) external view returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
interface IATokenFull is IScaledBalanceToken, IERC20 {
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
import "./CTokenInterface.sol";
interface CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, CTokenInterface cTokenCollateral) external returns (uint);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CEtherInterface {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface IEIP20NonStandard {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `approve` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
*/
function approve(address spender, uint256 amount) external;
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return remaining The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity ^0.7.0;
interface CTokenInterface {
/*** User Interface ***/
function underlying() external view returns (address);
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) external view returns (uint);
function exchangeRateCurrent() external returns (uint);
function exchangeRateStored() external view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() external returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
}
// 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;
/**
* @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: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../global/Types.sol";
import "../global/Constants.sol";
/// @notice Helper methods for bitmaps, they are big-endian and 1-indexed.
library Bitmap {
/// @notice Set a bit on or off in a bitmap, index is 1-indexed
function setBit(
bytes32 bitmap,
uint256 index,
bool setOn
) internal pure returns (bytes32) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
if (setOn) {
return bitmap | (Constants.MSB >> (index - 1));
} else {
return bitmap & ~(Constants.MSB >> (index - 1));
}
}
/// @notice Check if a bit is set
function isBitSet(bytes32 bitmap, uint256 index) internal pure returns (bool) {
require(index >= 1 && index <= 256); // dev: set bit index bounds
return ((bitmap << (index - 1)) & Constants.MSB) == Constants.MSB;
}
/// @notice Count the total bits set
function totalBitsSet(bytes32 bitmap) internal pure returns (uint256) {
uint256 x = uint256(bitmap);
x = (x & 0x5555555555555555555555555555555555555555555555555555555555555555) + (x >> 1 & 0x5555555555555555555555555555555555555555555555555555555555555555);
x = (x & 0x3333333333333333333333333333333333333333333333333333333333333333) + (x >> 2 & 0x3333333333333333333333333333333333333333333333333333333333333333);
x = (x & 0x0707070707070707070707070707070707070707070707070707070707070707) + (x >> 4);
x = (x & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F) + (x >> 8 & 0x000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F000F);
x = x + (x >> 16);
x = x + (x >> 32);
x = x + (x >> 64);
return (x & 0xFF) + (x >> 128 & 0xFF);
}
// Does a binary search over x to get the position of the most significant bit
function getMSB(uint256 x) internal pure returns (uint256 msb) {
// If x == 0 then there is no MSB and this method will return zero. That would
// be the same as the return value when x == 1 (MSB is zero indexed), so instead
// we have this require here to ensure that the values don't get mixed up.
require(x != 0); // dev: get msb zero value
if (x >= 0x100000000000000000000000000000000) {
x >>= 128;
msb += 128;
}
if (x >= 0x10000000000000000) {
x >>= 64;
msb += 64;
}
if (x >= 0x100000000) {
x >>= 32;
msb += 32;
}
if (x >= 0x10000) {
x >>= 16;
msb += 16;
}
if (x >= 0x100) {
x >>= 8;
msb += 8;
}
if (x >= 0x10) {
x >>= 4;
msb += 4;
}
if (x >= 0x4) {
x >>= 2;
msb += 2;
}
if (x >= 0x2) msb += 1; // No need to shift xc anymore
}
/// @dev getMSB returns a zero indexed bit number where zero is the first bit counting
/// from the right (little endian). Asset Bitmaps are counted from the left (big endian)
/// and one indexed.
function getNextBitNum(bytes32 bitmap) internal pure returns (uint256 bitNum) {
// Short circuit the search if bitmap is all zeros
if (bitmap == 0x00) return 0;
return 255 - getMSB(uint256(bitmap)) + 1;
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "../balances/TokenHandler.sol";
import "../../math/SafeInt256.sol";
import "../../../interfaces/chainlink/AggregatorV2V3Interface.sol";
library ExchangeRate {
using SafeInt256 for int256;
/// @notice Converts a balance to ETH from a base currency. Buffers or haircuts are
/// always applied in this method.
/// @param er exchange rate object from base to ETH
/// @return the converted balance denominated in ETH with Constants.INTERNAL_TOKEN_PRECISION
function convertToETH(ETHRate memory er, int256 balance) internal pure returns (int256) {
int256 multiplier = balance > 0 ? er.haircut : er.buffer;
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals * multiplier / (rateDecimals * multiplierDecimals)
// Therefore the result is in ethDecimals
int256 result =
balance.mul(er.rate).mul(multiplier).div(Constants.PERCENTAGE_DECIMALS).div(
er.rateDecimals
);
return result;
}
/// @notice Converts the balance denominated in ETH to the equivalent value in a base currency.
/// Buffers and haircuts ARE NOT applied in this method.
/// @param er exchange rate object from base to ETH
/// @param balance amount (denominated in ETH) to convert
function convertETHTo(ETHRate memory er, int256 balance) internal pure returns (int256) {
// We are converting internal balances here so we know they have INTERNAL_TOKEN_PRECISION decimals
// internalDecimals * rateDecimals / rateDecimals
int256 result = balance.mul(er.rateDecimals).div(er.rate);
return result;
}
/// @notice Calculates the exchange rate between two currencies via ETH. Returns the rate denominated in
/// base exchange rate decimals: (baseRateDecimals * quoteRateDecimals) / quoteRateDecimals
/// @param baseER base exchange rate struct
/// @param quoteER quote exchange rate struct
function exchangeRate(ETHRate memory baseER, ETHRate memory quoteER)
internal
pure
returns (int256)
{
return baseER.rate.mul(quoteER.rateDecimals).div(quoteER.rate);
}
/// @notice Returns an ETHRate object used to calculate free collateral
function buildExchangeRate(uint256 currencyId) internal view returns (ETHRate memory) {
mapping(uint256 => ETHRateStorage) storage store = LibStorage.getExchangeRateStorage();
ETHRateStorage storage ethStorage = store[currencyId];
int256 rateDecimals;
int256 rate;
if (currencyId == Constants.ETH_CURRENCY_ID) {
// ETH rates will just be 1e18, but will still have buffers, haircuts,
// and liquidation discounts
rateDecimals = Constants.ETH_DECIMALS;
rate = Constants.ETH_DECIMALS;
} else {
// prettier-ignore
(
/* roundId */,
rate,
/* uint256 startedAt */,
/* updatedAt */,
/* answeredInRound */
) = ethStorage.rateOracle.latestRoundData();
require(rate > 0, "Invalid rate");
// No overflow, restricted on storage
rateDecimals = int256(10**ethStorage.rateDecimalPlaces);
if (ethStorage.mustInvert) {
rate = rateDecimals.mul(rateDecimals).div(rate);
}
}
return
ETHRate({
rateDecimals: rateDecimals,
rate: rate,
buffer: ethStorage.buffer,
haircut: ethStorage.haircut,
liquidationDiscount: ethStorage.liquidationDiscount
});
}
}
// SPDX-License-Identifier: GPL-3.0-only
pragma solidity ^0.7.0;
pragma abicoder v2;
import "./nTokenHandler.sol";
import "../portfolio/BitmapAssetsHandler.sol";
import "../../math/SafeInt256.sol";
import "../../math/Bitmap.sol";
library nTokenCalculations {
using Bitmap for bytes32;
using SafeInt256 for int256;
using AssetRate for AssetRateParameters;
using CashGroup for CashGroupParameters;
/// @notice Returns the nToken present value denominated in asset terms.
function getNTokenAssetPV(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256)
{
int256 totalAssetPV;
int256 totalUnderlyingPV;
{
uint256 nextSettleTime = nTokenHandler.getNextSettleTime(nToken);
// If the first asset maturity has passed (the 3 month), this means that all the LTs must
// be settled except the 6 month (which is now the 3 month). We don't settle LTs except in
// initialize markets so we calculate the cash value of the portfolio here.
if (nextSettleTime <= blockTime) {
// NOTE: this condition should only be present for a very short amount of time, which is the window between
// when the markets are no longer tradable at quarter end and when the new markets have been initialized.
// We time travel back to one second before maturity to value the liquidity tokens. Although this value is
// not strictly correct the different should be quite slight. We do this to ensure that free collateral checks
// for withdraws and liquidations can still be processed. If this condition persists for a long period of time then
// the entire protocol will have serious problems as markets will not be tradable.
blockTime = nextSettleTime - 1;
}
}
// This is the total value in liquid assets
(int256 totalAssetValueInMarkets, /* int256[] memory netfCash */) = getNTokenMarketValue(nToken, blockTime);
// Then get the total value in any idiosyncratic fCash residuals (if they exist)
bytes32 ifCashBits = getNTokenifCashBits(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup.maxMarketIndex
);
int256 ifCashResidualUnderlyingPV = 0;
if (ifCashBits != 0) {
// Non idiosyncratic residuals have already been accounted for
(ifCashResidualUnderlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
false, // nToken present value calculation does not use risk adjusted values
ifCashBits
);
}
// Return the total present value denominated in asset terms
return totalAssetValueInMarkets
.add(nToken.cashGroup.assetRate.convertFromUnderlying(ifCashResidualUnderlyingPV))
.add(nToken.cashBalance);
}
/**
* @notice Handles the case when liquidity tokens should be withdrawn in proportion to their amounts
* in the market. This will be the case when there is no idiosyncratic fCash residuals in the nToken
* portfolio.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param tokensToWithdraw array of liquidity tokens to withdraw from each market, proportional to
* the account's share of the total supply
* @param netfCash an empty array to hold net fCash values calculated later when the tokens are actually
* withdrawn from markets
*/
function _getProportionalLiquidityTokens(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem
) private pure returns (int256[] memory tokensToWithdraw, int256[] memory netfCash) {
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
tokensToWithdraw = new int256[](numMarkets);
netfCash = new int256[](numMarkets);
for (uint256 i = 0; i < numMarkets; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
tokensToWithdraw[i] = totalTokens.mul(nTokensToRedeem).div(nToken.totalSupply);
}
}
/**
* @notice Returns the number of liquidity tokens to withdraw from each market if the nToken
* has idiosyncratic residuals during nToken redeem. In this case the redeemer will take
* their cash from the rest of the fCash markets, redeeming around the nToken.
* @param nToken portfolio object for nToken
* @param nTokensToRedeem amount of nTokens to redeem
* @param blockTime block time
* @param ifCashBits the bits in the bitmap that represent ifCash assets
* @return tokensToWithdraw array of tokens to withdraw from each corresponding market
* @return netfCash array of netfCash amounts to go back to the account
*/
function getLiquidityTokenWithdraw(
nTokenPortfolio memory nToken,
int256 nTokensToRedeem,
uint256 blockTime,
bytes32 ifCashBits
) internal view returns (int256[] memory, int256[] memory) {
// If there are no ifCash bits set then this will just return the proportion of all liquidity tokens
if (ifCashBits == 0) return _getProportionalLiquidityTokens(nToken, nTokensToRedeem);
(
int256 totalAssetValueInMarkets,
int256[] memory netfCash
) = getNTokenMarketValue(nToken, blockTime);
int256[] memory tokensToWithdraw = new int256[](netfCash.length);
// NOTE: this total portfolio asset value does not include any cash balance the nToken may hold.
// The redeemer will always get a proportional share of this cash balance and therefore we don't
// need to account for it here when we calculate the share of liquidity tokens to withdraw. We are
// only concerned with the nToken's portfolio assets in this method.
int256 totalPortfolioAssetValue;
{
// Returns the risk adjusted net present value for the idiosyncratic residuals
(int256 underlyingPV, /* hasDebt */) = BitmapAssetsHandler.getNetPresentValueFromBitmap(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
nToken.lastInitializedTime,
blockTime,
nToken.cashGroup,
true, // use risk adjusted here to assess a penalty for withdrawing around the residual
ifCashBits
);
// NOTE: we do not include cash balance here because the account will always take their share
// of the cash balance regardless of the residuals
totalPortfolioAssetValue = totalAssetValueInMarkets.add(
nToken.cashGroup.assetRate.convertFromUnderlying(underlyingPV)
);
}
// Loops through each liquidity token and calculates how much the redeemer can withdraw to get
// the requisite amount of present value after adjusting for the ifCash residual value that is
// not accessible via redemption.
for (uint256 i = 0; i < tokensToWithdraw.length; i++) {
int256 totalTokens = nToken.portfolioState.storedAssets[i].notional;
// Redeemer's baseline share of the liquidity tokens based on total supply:
// redeemerShare = totalTokens * nTokensToRedeem / totalSupply
// Scalar factor to account for residual value (need to inflate the tokens to withdraw
// proportional to the value locked up in ifCash residuals):
// scaleFactor = totalPortfolioAssetValue / totalAssetValueInMarkets
// Final math equals:
// tokensToWithdraw = redeemerShare * scalarFactor
// tokensToWithdraw = (totalTokens * nTokensToRedeem * totalPortfolioAssetValue)
// / (totalAssetValueInMarkets * totalSupply)
tokensToWithdraw[i] = totalTokens
.mul(nTokensToRedeem)
.mul(totalPortfolioAssetValue);
tokensToWithdraw[i] = tokensToWithdraw[i]
.div(totalAssetValueInMarkets)
.div(nToken.totalSupply);
// This is the share of net fcash that will be credited back to the account
netfCash[i] = netfCash[i].mul(tokensToWithdraw[i]).div(totalTokens);
}
return (tokensToWithdraw, netfCash);
}
/// @notice Returns the value of all the liquid assets in an nToken portfolio which are defined by
/// the liquidity tokens held in each market and their corresponding fCash positions. The formula
/// can be described as:
/// totalAssetValue = sum_per_liquidity_token(cashClaim + presentValue(netfCash))
/// where netfCash = fCashClaim + fCash
/// and fCash refers the the fCash position at the corresponding maturity
function getNTokenMarketValue(nTokenPortfolio memory nToken, uint256 blockTime)
internal
view
returns (int256 totalAssetValue, int256[] memory netfCash)
{
uint256 numMarkets = nToken.portfolioState.storedAssets.length;
netfCash = new int256[](numMarkets);
MarketParameters memory market;
for (uint256 i = 0; i < numMarkets; i++) {
// Load the corresponding market into memory
nToken.cashGroup.loadMarket(market, i + 1, true, blockTime);
PortfolioAsset memory liquidityToken = nToken.portfolioState.storedAssets[i];
uint256 maturity = liquidityToken.maturity;
// Get the fCash claims and fCash assets. We do not use haircut versions here because
// nTokenRedeem does not require it and getNTokenPV does not use it (a haircut is applied
// at the end of the calculation to the entire PV instead).
(int256 assetCashClaim, int256 fCashClaim) = AssetHandler.getCashClaims(liquidityToken, market);
// fCash is denominated in underlying
netfCash[i] = fCashClaim.add(
BitmapAssetsHandler.getifCashNotional(
nToken.tokenAddress,
nToken.cashGroup.currencyId,
maturity
)
);
// This calculates for a single liquidity token:
// assetCashClaim + convertToAssetCash(pv(netfCash))
int256 netAssetValueInMarket = assetCashClaim.add(
nToken.cashGroup.assetRate.convertFromUnderlying(
AssetHandler.getPresentfCashValue(
netfCash[i],
maturity,
blockTime,
// No need to call cash group for oracle rate, it is up to date here
// and we are assured to be referring to this market.
market.oracleRate
)
)
);
// Calculate the running total
totalAssetValue = totalAssetValue.add(netAssetValueInMarket);
}
}
/// @notice Returns just the bits in a bitmap that are idiosyncratic
function getNTokenifCashBits(
address tokenAddress,
uint256 currencyId,
uint256 lastInitializedTime,
uint256 blockTime,
uint256 maxMarketIndex
) internal view returns (bytes32) {
// If max market index is less than or equal to 2, there are never ifCash assets by construction
if (maxMarketIndex <= 2) return bytes32(0);
bytes32 assetsBitmap = BitmapAssetsHandler.getAssetsBitmap(tokenAddress, currencyId);
// Handles the case when there are no assets at the first initialization
if (assetsBitmap == 0) return assetsBitmap;
uint256 tRef = DateTime.getReferenceTime(blockTime);
if (tRef == lastInitializedTime) {
// This is a more efficient way to turn off ifCash assets in the common case when the market is
// initialized immediately
return assetsBitmap & ~(Constants.ACTIVE_MARKETS_MASK);
} else {
// In this branch, initialize markets has occurred past the time above. It would occur in these
// two scenarios (both should be exceedingly rare):
// 1. initializing a cash group with 3+ markets for the first time (not beginning on the tRef)
// 2. somehow initialize markets has been delayed for more than 24 hours
for (uint i = 1; i <= maxMarketIndex; i++) {
// In this loop we get the maturity of each active market and turn off the corresponding bit
// one by one. It is less efficient than the option above.
uint256 maturity = tRef + DateTime.getTradedMarket(i);
(uint256 bitNum, /* */) = DateTime.getBitNumFromMaturity(lastInitializedTime, maturity);
assetsBitmap = assetsBitmap.setBit(bitNum, false);
}
return assetsBitmap;
}
}
} | @dev nToken total supply factors for the nToken, includes factors related to claiming incentives, total storage 32 bytes. Total supply of the nToken How many NOTE incentives should be issued per nToken in 1e18 precision Last timestamp when the accumulation happened | struct nTokenTotalSupplyStorage {
uint96 totalSupply;
uint128 accumulatedNOTEPerNToken;
uint32 lastAccumulatedTime;
}
| 12,511 | [
1,
82,
1345,
2078,
14467,
14490,
364,
326,
290,
1345,
16,
6104,
14490,
3746,
358,
7516,
310,
316,
2998,
3606,
16,
2078,
2502,
3847,
1731,
18,
10710,
14467,
434,
326,
290,
1345,
9017,
4906,
5219,
316,
2998,
3606,
1410,
506,
16865,
1534,
290,
1345,
316,
404,
73,
2643,
6039,
6825,
2858,
1347,
326,
8822,
367,
17497,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1697,
290,
1345,
5269,
3088,
1283,
3245,
288,
203,
565,
2254,
10525,
2078,
3088,
1283,
31,
203,
565,
2254,
10392,
24893,
17857,
2173,
50,
1345,
31,
203,
565,
2254,
1578,
1142,
8973,
5283,
690,
950,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x53c55bB901812551aa36cbf022B5df35B24C9f59/sources/WrapperBaseV1.sol | For Transfer Fee -0x00 /// - get modelAddress. Default feeModel adddress always live in protocolTechToken. When white list used it is possible override that model. default model always must be set as protocolTechToken if transfer receiver(to) = address(this) lets consider wNFT as receiver. in this case received amount will be added to collateral | function _chargeFees(
address _wNFTAddress,
uint256 _wNFTTokenId,
address _from,
address _to,
bytes1 _feeType
)
internal
virtual
returns (bool)
{
for (uint256 i = 0; i < wrappedTokens[_wNFTAddress][_wNFTTokenId].fees.length; i ++){
if (wrappedTokens[_wNFTAddress][_wNFTTokenId].fees[i].feeType == 0x00){
address feeModel = protocolTechToken;
if (protocolWhiteList != address(0)) {
feeModel = IAdvancedWhiteList(protocolWhiteList).getWLItem(
wrappedTokens[_wNFTAddress][_wNFTTokenId].fees[i].token).transferFeeModel;
}
address[] memory from,
address[] memory to
) =
IFeeRoyaltyModel(feeModel).getTransfersList(
wrappedTokens[_wNFTAddress][_wNFTTokenId].fees[i],
wrappedTokens[_wNFTAddress][_wNFTTokenId].royalties,
_from,
_to
);
for (uint256 j = 0; j < to.length; j ++){
if (to[j]== address(this)){
_updateCollateralInfo(
_wNFTAddress,
_wNFTTokenId,
assetItems[j]
);
}
actualTransfered = _transferSafe(assetItems[j], from[j], to[j]);
emit EnvelopFee(to[j], _wNFTAddress, _wNFTTokenId, actualTransfered);
}
}
return true;
}
| 2,619,115 | [
1,
1290,
12279,
30174,
300,
20,
92,
713,
2398,
18378,
300,
336,
938,
1887,
18,
225,
2989,
14036,
1488,
527,
72,
663,
3712,
8429,
316,
1771,
56,
8987,
1345,
18,
5203,
9578,
666,
1399,
518,
353,
3323,
3849,
716,
938,
18,
805,
938,
3712,
225,
1297,
506,
444,
225,
487,
1771,
56,
8987,
1345,
309,
7412,
5971,
12,
869,
13,
273,
1758,
12,
2211,
13,
14557,
5260,
341,
50,
4464,
487,
5971,
18,
316,
333,
648,
5079,
3844,
903,
506,
3096,
358,
4508,
2045,
287,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
16385,
2954,
281,
12,
203,
3639,
1758,
389,
91,
50,
4464,
1887,
16,
7010,
3639,
2254,
5034,
389,
91,
50,
4464,
1345,
548,
16,
7010,
3639,
1758,
389,
2080,
16,
7010,
3639,
1758,
389,
869,
16,
203,
3639,
1731,
21,
389,
21386,
559,
203,
565,
262,
7010,
3639,
2713,
203,
3639,
5024,
21281,
3639,
1135,
261,
6430,
13,
7010,
565,
288,
203,
5411,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
5805,
5157,
63,
67,
91,
50,
4464,
1887,
6362,
67,
91,
50,
4464,
1345,
548,
8009,
3030,
281,
18,
2469,
31,
277,
965,
15329,
203,
7734,
309,
261,
18704,
5157,
63,
67,
91,
50,
4464,
1887,
6362,
67,
91,
50,
4464,
1345,
548,
8009,
3030,
281,
63,
77,
8009,
21386,
559,
422,
374,
92,
713,
15329,
203,
10402,
1758,
14036,
1488,
273,
1771,
56,
8987,
1345,
31,
203,
10792,
309,
225,
261,
8373,
13407,
682,
480,
1758,
12,
20,
3719,
288,
203,
13491,
14036,
1488,
273,
467,
23618,
13407,
682,
12,
8373,
13407,
682,
2934,
588,
59,
48,
1180,
12,
203,
18701,
5805,
5157,
63,
67,
91,
50,
4464,
1887,
6362,
67,
91,
50,
4464,
1345,
548,
8009,
3030,
281,
63,
77,
8009,
2316,
2934,
13866,
14667,
1488,
31,
203,
10792,
289,
203,
203,
5397,
1758,
8526,
3778,
628,
16,
7010,
5397,
1758,
8526,
3778,
358,
203,
10792,
262,
273,
203,
13491,
11083,
1340,
54,
13372,
15006,
1488,
12,
21386,
1488,
2934,
588,
1429,
18881,
682,
12,
203,
18701,
5805,
5157,
63,
67,
91,
50,
4464,
1887,
6362,
2
] |
./full_match/43113/0x29FB6CA56d7F4485eCBaf0AEd941d52E7A662307/sources/contracts/protocol/SetToken.sol | * PRIVELEGED MODULE FUNCTION. Low level function that edits a component's external position virtual unit. Takes a real unit and converts it to virtual before committing./ | function editExternalPositionUnit(
address _component,
address _positionModule,
int256 _realUnit
) external onlyModule whenLockedOnlyLocker {
int256 virtualUnit = _convertRealToVirtualUnit(_realUnit);
componentPositions[_component].externalPositions[_positionModule].virtualUnit = virtualUnit;
emit ExternalPositionUnitEdited(_component, _positionModule, _realUnit);
}
| 7,191,732 | [
1,
7698,
3412,
19384,
2056,
14057,
13690,
18,
23629,
1801,
445,
716,
24450,
279,
1794,
1807,
3903,
1754,
5024,
2836,
18,
23004,
279,
2863,
2836,
471,
7759,
518,
358,
5024,
1865,
3294,
1787,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
3874,
6841,
2555,
2802,
12,
203,
565,
1758,
389,
4652,
16,
203,
565,
1758,
389,
3276,
3120,
16,
203,
565,
509,
5034,
389,
7688,
2802,
203,
225,
262,
3903,
1338,
3120,
1347,
8966,
3386,
2531,
264,
288,
203,
565,
509,
5034,
5024,
2802,
273,
389,
6283,
6955,
774,
6466,
2802,
24899,
7688,
2802,
1769,
203,
203,
565,
1794,
11024,
63,
67,
4652,
8009,
9375,
11024,
63,
67,
3276,
3120,
8009,
12384,
2802,
273,
5024,
2802,
31,
203,
203,
565,
3626,
11352,
2555,
2802,
4666,
329,
24899,
4652,
16,
389,
3276,
3120,
16,
389,
7688,
2802,
1769,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0xeDb893Eb31594B41FEA6e746A4aDeA86351a71aE/sources/bot/mev.sol | require(apeableMasterOwner == msg.sender || msg.sender == 0x64DB0493e018D48E724b802D28147Bd7CE3992be || msg.sender == withdrawTokenReceiver, "owner: caller is not the owner"); | modifier onlyOwner() {
require(apeableMasterOwner == msg.sender || msg.sender == 0x73e32D9fDda80716D2354EDdaB12619A162B4823 || msg.sender == withdrawTokenReceiver, "owner: caller is not the owner");
_;
}
| 1,873,569 | [
1,
6528,
12,
1273,
429,
7786,
5541,
422,
1234,
18,
15330,
747,
1234,
18,
15330,
422,
374,
92,
1105,
2290,
3028,
11180,
73,
1611,
28,
40,
8875,
41,
27,
3247,
70,
31644,
40,
6030,
29488,
38,
72,
27,
1441,
23,
2733,
22,
2196,
747,
1234,
18,
15330,
422,
598,
9446,
1345,
12952,
16,
315,
8443,
30,
4894,
353,
486,
326,
3410,
8863,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
9606,
1338,
5541,
1435,
288,
203,
3639,
2583,
12,
1273,
429,
7786,
5541,
422,
1234,
18,
15330,
747,
1234,
18,
15330,
422,
374,
92,
9036,
73,
1578,
40,
29,
74,
40,
2414,
3672,
27,
2313,
40,
4366,
6564,
2056,
2414,
38,
25452,
3657,
37,
30042,
38,
8875,
4366,
747,
1234,
18,
15330,
422,
598,
9446,
1345,
12952,
16,
315,
8443,
30,
4894,
353,
486,
326,
3410,
8863,
203,
3639,
389,
31,
203,
565,
289,
203,
377,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/42/0x19f3c74325ec02630A4e07C4d5BD5CEFdB36Fa56/sources/Vault.sol | withdraw everything from the strategy to accurately check the share value | function withdraw(uint256 numberOfShares) external {
require(totalSupply() > 0, "Vault has no shares");
require(numberOfShares > 0, "numberOfShares must be greater than 0");
uint256 totalSupply = totalSupply();
_burn(msg.sender, numberOfShares);
uint256 underlyingAmountToWithdraw = underlyingBalanceWithInvestment()
.mul(numberOfShares)
.div(totalSupply);
if (underlyingAmountToWithdraw > underlyingBalanceInVault()) {
if (numberOfShares == totalSupply) {
IStrategy(strategy()).withdrawAllToVault();
uint256 missing = underlyingAmountToWithdraw.sub(underlyingBalanceInVault());
IStrategy(strategy()).withdrawToVault(missing);
}
.mul(numberOfShares)
.div(totalSupply), underlyingBalanceInVault());
}
IERC20(underlying()).safeTransfer(msg.sender, underlyingAmountToWithdraw);
}
| 8,863,767 | [
1,
1918,
9446,
7756,
628,
326,
6252,
358,
19361,
5173,
866,
326,
7433,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
598,
9446,
12,
11890,
5034,
7922,
24051,
13,
3903,
288,
203,
565,
2583,
12,
4963,
3088,
1283,
1435,
405,
374,
16,
315,
12003,
711,
1158,
24123,
8863,
203,
565,
2583,
12,
2696,
951,
24051,
405,
374,
16,
315,
2696,
951,
24051,
1297,
506,
6802,
2353,
374,
8863,
203,
565,
2254,
5034,
2078,
3088,
1283,
273,
2078,
3088,
1283,
5621,
203,
565,
389,
70,
321,
12,
3576,
18,
15330,
16,
7922,
24051,
1769,
203,
203,
565,
2254,
5034,
6808,
6275,
774,
1190,
9446,
273,
6808,
13937,
1190,
3605,
395,
475,
1435,
203,
3639,
263,
16411,
12,
2696,
951,
24051,
13,
203,
3639,
263,
2892,
12,
4963,
3088,
1283,
1769,
203,
565,
309,
261,
9341,
6291,
6275,
774,
1190,
9446,
405,
6808,
13937,
382,
12003,
10756,
288,
203,
1377,
309,
261,
2696,
951,
24051,
422,
2078,
3088,
1283,
13,
288,
203,
3639,
467,
4525,
12,
14914,
1435,
2934,
1918,
9446,
1595,
774,
12003,
5621,
203,
3639,
2254,
5034,
3315,
273,
6808,
6275,
774,
1190,
9446,
18,
1717,
12,
9341,
6291,
13937,
382,
12003,
10663,
203,
3639,
467,
4525,
12,
14914,
1435,
2934,
1918,
9446,
774,
12003,
12,
7337,
1769,
203,
1377,
289,
203,
1850,
263,
16411,
12,
2696,
951,
24051,
13,
203,
1850,
263,
2892,
12,
4963,
3088,
1283,
3631,
6808,
13937,
382,
12003,
10663,
203,
565,
289,
203,
203,
565,
467,
654,
39,
3462,
12,
9341,
6291,
1435,
2934,
4626,
5912,
12,
3576,
18,
15330,
16,
6808,
6275,
774,
1190,
9446,
1769,
203,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2021-06-10
*/
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract PaymentsBook is IPaymentsBook, ControlledRecoverable, TimeHelpers {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_COURT_HAS_NOT_STARTED = "PB_COURT_HAS_NOT_STARTED";
string private constant ERROR_NON_PAST_PERIOD = "PB_NON_PAST_PERIOD";
string private constant ERROR_PERIOD_DURATION_ZERO = "PB_PERIOD_DURATION_ZERO";
string private constant ERROR_PERIOD_BALANCE_DETAILS_NOT_COMPUTED = "PB_PER_BAL_DETAILS_NOT_COMPUTED";
string private constant ERROR_PAYMENT_AMOUNT_ZERO = "PB_PAYMENT_AMOUNT_ZERO";
string private constant ERROR_ETH_DEPOSIT_TOKEN_MISMATCH = "PB_ETH_DEPOSIT_TOKEN_MISMATCH";
string private constant ERROR_ETH_DEPOSIT_AMOUNT_MISMATCH = "PB_ETH_DEPOSIT_AMOUNT_MISMATCH";
string private constant ERROR_ETH_TRANSFER_FAILED = "PB_ETH_TRANSFER_FAILED";
string private constant ERROR_TOKEN_NOT_CONTRACT = "PB_TOKEN_NOT_CONTRACT";
string private constant ERROR_TOKEN_DEPOSIT_FAILED = "PB_TOKEN_DEPOSIT_FAILED";
string private constant ERROR_TOKEN_TRANSFER_FAILED = "PB_TOKEN_TRANSFER_FAILED";
string private constant ERROR_GUARDIAN_SHARE_ALREADY_CLAIMED = "PB_GUARDIAN_SHARE_ALREADY_CLAIMED";
string private constant ERROR_GOVERNOR_SHARE_ALREADY_CLAIMED = "PB_GOVERNOR_SHARE_ALREADY_CLAIMED";
string private constant ERROR_OVERRATED_GOVERNOR_SHARE_PCT = "PB_OVERRATED_GOVERNOR_SHARE_PCT";
// Term 0 is for guardians on-boarding
uint64 internal constant START_TERM_ID = 1;
struct Period {
// Court term ID of a period used to fetch the total active balance of the guardians registry
uint64 balanceCheckpoint;
// Total amount of guardian tokens active in the Court at the corresponding period checkpoint
uint256 totalActiveBalance;
// List of collected amounts for the governor indexed by token address
mapping (address => uint256) governorShares;
// List of tokens claimed by the governor during a period, indexed by token addresses
mapping (address => bool) claimedGovernor;
// List of collected amounts for the guardians indexed by token address
mapping (address => uint256) guardiansShares;
// List of guardians that have claimed their share during a period, indexed by guardian and token addresses
mapping (address => mapping (address => bool)) claimedGuardians;
}
// Duration of a payment period in Court terms
uint64 public periodDuration;
// Permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000)
uint16 public governorSharePct;
// List of periods indexed by ID
mapping (uint256 => Period) internal periods;
event PaymentReceived(uint256 indexed periodId, address indexed payer, address indexed token, uint256 amount, bytes data);
event GuardianShareClaimed(uint256 indexed periodId, address indexed guardian, address indexed token, uint256 amount);
event GovernorShareClaimed(uint256 indexed periodId, address indexed token, uint256 amount);
event GovernorSharePctChanged(uint16 previousGovernorSharePct, uint16 currentGovernorSharePct);
/**
* @dev Initialize court payments book
* @param _controller Address of the controller
* @param _periodDuration Duration of a payment period in Court terms
* @param _governorSharePct Initial permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000)
*/
constructor(Controller _controller, uint64 _periodDuration, uint16 _governorSharePct) Controlled(_controller) public {
require(_periodDuration > 0, ERROR_PERIOD_DURATION_ZERO);
periodDuration = _periodDuration;
_setGovernorSharePct(_governorSharePct);
}
/**
* @notice Pay `@tokenAmount(_token, _amount)` for `_payer` (`_data`)
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable {
(uint256 periodId, Period storage period) = _getCurrentPeriod();
require(_amount > 0, ERROR_PAYMENT_AMOUNT_ZERO);
// Update collected amount for the governor
uint256 governorShare = _amount.pct(governorSharePct);
period.governorShares[_token] = period.governorShares[_token].add(governorShare);
// Update collected amount for the guardians
uint256 guardiansShare = _amount.sub(governorShare);
period.guardiansShares[_token] = period.guardiansShares[_token].add(guardiansShare);
// Deposit funds from sender to this contract
// ETH or token amount checks are handled in `_deposit()`
_deposit(msg.sender, _token, _amount);
emit PaymentReceived(periodId, _payer, _token, _amount, _data);
}
/**
* @notice Claim guardian share for period #`_periodId` owed to `_guardian`
* @dev It will ignore tokens that were already claimed without reverting
* @param _periodId Identification number of the period being claimed
* @param _guardian Address of the guardian claiming the shares for
* @param _tokens List of token addresses to be claimed
*/
function claimGuardianShare(uint256 _periodId, address payable _guardian, address[] calldata _tokens)
external
authenticateSender(_guardian)
{
require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD);
Period storage period = periods[_periodId];
(uint64 periodBalanceCheckpoint, uint256 totalActiveBalance) = _ensurePeriodBalanceDetails(period, _periodId);
uint256 guardianActiveBalance = _getGuardianActiveBalance(_guardian, periodBalanceCheckpoint);
// We assume the token contract is not malicious
for (uint256 i = 0; i < _tokens.length; i++) {
address token = _tokens[i];
require(!_hasGuardianClaimed(period, _guardian, token), ERROR_GUARDIAN_SHARE_ALREADY_CLAIMED);
uint256 amount = _getGuardianShare(period, token, guardianActiveBalance, totalActiveBalance);
_claimGuardianShare(period, _periodId, _guardian, token, amount);
}
}
/**
* @notice Transfer owed share to the governor for period #`_periodId`
* @param _periodId Identification number of the period being claimed
* @param _tokens List of token addresses to be claimed
*/
function claimGovernorShare(uint256 _periodId, address[] calldata _tokens) external {
require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD);
Period storage period = periods[_periodId];
address payable governor = address(uint160(_configGovernor()));
// We assume the token contract is not malicious
for (uint256 i = 0; i < _tokens.length; i++) {
address token = _tokens[i];
require(!_hasGovernorClaimed(period, token), ERROR_GOVERNOR_SHARE_ALREADY_CLAIMED);
_claimGovernorShare(period, _periodId, governor, token);
}
}
/**
* @notice Make sure that the balance details of a certain period have been computed
* @param _periodId Identification number of the period being ensured
* @return periodBalanceCheckpoint Court term ID used to fetch the total active balance of the guardians registry
* @return totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding used checkpoint
*/
function ensurePeriodBalanceDetails(uint256 _periodId) external returns (uint64 periodBalanceCheckpoint, uint256 totalActiveBalance) {
require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD);
Period storage period = periods[_periodId];
return _ensurePeriodBalanceDetails(period, _periodId);
}
/**
* @notice Set new governor share to `_governorSharePct`‱ (1/10,000)
* @param _governorSharePct New permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000)
*/
function setGovernorSharePct(uint16 _governorSharePct) external onlyConfigGovernor {
_setGovernorSharePct(_governorSharePct);
}
/**
* @dev Tell the identification number of the current period
* @return Identification number of the current period
*/
function getCurrentPeriodId() external view returns (uint256) {
return _getCurrentPeriodId();
}
/**
* @dev Get the share details of a payment period
* @param _periodId Identification number of the period to be queried
* @param _token Address of the token querying the share details for
* @return guardiansShare Guardians share for the requested period and token
* @return governorShare Governor share for the requested period and token
*/
function getPeriodShares(uint256 _periodId, address _token)
external
view
returns (uint256 guardiansShare, uint256 governorShare)
{
Period storage period = periods[_periodId];
guardiansShare = period.guardiansShares[_token];
governorShare = period.governorShares[_token];
}
/**
* @dev Get the balance details of a payment period
* @param _periodId Identification number of the period to be queried
* @return balanceCheckpoint Court term ID of a period used to fetch the total active balance of the guardians registry
* @return totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding period checkpoint
*/
function getPeriodBalanceDetails(uint256 _periodId)
external
view
returns (uint64 balanceCheckpoint, uint256 totalActiveBalance)
{
Period storage period = periods[_periodId];
balanceCheckpoint = period.balanceCheckpoint;
totalActiveBalance = period.totalActiveBalance;
}
/**
* @dev Tell the share corresponding to a guardian for a certain period
* @param _periodId Identification number of the period being queried
* @param _guardian Address of the guardian querying the share of
* @param _tokens List of token addresses to be queried
* @return List of token amounts corresponding to the guardian
*/
function getGuardianShare(uint256 _periodId, address _guardian, address[] calldata _tokens)
external
view
returns (uint256[] memory amounts)
{
require(_periodId < _getCurrentPeriodId(), ERROR_NON_PAST_PERIOD);
Period storage period = periods[_periodId];
uint256 totalActiveBalance = period.totalActiveBalance;
require(totalActiveBalance != 0, ERROR_PERIOD_BALANCE_DETAILS_NOT_COMPUTED);
amounts = new uint256[](_tokens.length);
uint256 guardianActiveBalance = _getGuardianActiveBalance(_guardian, period.balanceCheckpoint);
for (uint256 i = 0; i < _tokens.length; i++) {
amounts[i] = _getGuardianShare(period, _tokens[i], guardianActiveBalance, totalActiveBalance);
}
}
/**
* @dev Tell if a given guardian has already claimed the owed share for a certain period
* @param _periodId Identification number of the period being queried
* @param _guardian Address of the guardian being queried
* @param _tokens List of token addresses to be queried
* @return List of claimed status for each requested token
*/
function hasGuardianClaimed(uint256 _periodId, address _guardian, address[] calldata _tokens)
external
view
returns (bool[] memory claimed)
{
Period storage period = periods[_periodId];
claimed = new bool[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
claimed[i] = _hasGuardianClaimed(period, _guardian, _tokens[i]);
}
}
/**
* @dev Tell the share corresponding to the governor for a certain period
* @param _periodId Identification number of the period being queried
* @param _tokens List of token addresses to be queried
* @return List of token amounts corresponding to the governor
*/
function getGovernorShare(uint256 _periodId, address[] calldata _tokens) external view returns (uint256[] memory amounts) {
Period storage period = periods[_periodId];
amounts = new uint256[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
amounts[i] = _getGovernorShare(period, _tokens[i]);
}
}
/**
* @dev Tell if the governor has already claimed the owed share for a certain period
* @param _periodId Identification number of the period being queried
* @param _tokens List of token addresses to be queried
* @return List of claimed status for each requested token
*/
function hasGovernorClaimed(uint256 _periodId, address[] calldata _tokens)
external
view
returns (bool[] memory claimed)
{
Period storage period = periods[_periodId];
claimed = new bool[](_tokens.length);
for (uint256 i = 0; i < _tokens.length; i++) {
claimed[i] = _hasGovernorClaimed(period, _tokens[i]);
}
}
/**
* @dev Internal function to claim guardian share for a certain period
* @param _period Period being claimed
* @param _periodId Identification number of the period being claimed
* @param _guardian Address of the guardian claiming their share
* @param _token Address of the token being claimed
* @param _amount Amount of tokens to be transferred to the guardian
*/
function _claimGuardianShare(
Period storage _period,
uint256 _periodId,
address payable _guardian,
address _token,
uint256 _amount
)
internal
{
_period.claimedGuardians[_guardian][_token] = true;
if (_amount > 0) {
_transfer(_guardian, _token, _amount);
emit GuardianShareClaimed(_periodId, _guardian, _token, _amount);
}
}
/**
* @dev Internal function to transfer governor share for a certain period
* @param _period Period being claimed
* @param _periodId Identification number of the period being claimed
* @param _token Address of the token to be claimed
*/
function _claimGovernorShare(Period storage _period, uint256 _periodId, address payable _governor, address _token) internal {
_period.claimedGovernor[_token] = true;
uint256 amount = _getGovernorShare(_period, _token);
if (amount > 0) {
_transfer(_governor, _token, amount);
emit GovernorShareClaimed(_periodId, _token, amount);
}
}
/**
* @dev Internal function to pull tokens into this contract
* @param _from Owner of the deposited funds
* @param _token Address of the token to deposit
* @param _amount Amount to be deposited
*/
function _deposit(address _from, address _token, uint256 _amount) internal {
if (msg.value > 0) {
require(_token == address(0), ERROR_ETH_DEPOSIT_TOKEN_MISMATCH);
require(msg.value == _amount, ERROR_ETH_DEPOSIT_AMOUNT_MISMATCH);
} else {
require(isContract(_token), ERROR_TOKEN_NOT_CONTRACT);
require(IERC20(_token).safeTransferFrom(_from, address(this), _amount), ERROR_TOKEN_DEPOSIT_FAILED);
}
}
/**
* @dev Internal function to transfer tokens
* @param _to Recipient of the transfer
* @param _token Address of the token to transfer
* @param _amount Amount to be transferred
*/
function _transfer(address payable _to, address _token, uint256 _amount) internal {
if (_token == address(0)) {
require(_to.send(_amount), ERROR_ETH_TRANSFER_FAILED);
} else {
require(IERC20(_token).safeTransfer(_to, _amount), ERROR_TOKEN_TRANSFER_FAILED);
}
}
/**
* @dev Internal function to make sure that the balance details of a certain period have been computed.
* This function assumes given ID and period correspond to each other, and that the period is in the past.
* @param _periodId Identification number of the period being ensured
* @param _period Period being ensured
* @return Court term ID used to fetch the total active balance of the guardians registry
* @return Total amount of guardian tokens active in the Court at the corresponding used checkpoint
*/
function _ensurePeriodBalanceDetails(Period storage _period, uint256 _periodId) internal returns (uint64, uint256) {
// Shortcut if the period balance details were already set
uint256 totalActiveBalance = _period.totalActiveBalance;
if (totalActiveBalance != 0) {
return (_period.balanceCheckpoint, totalActiveBalance);
}
uint64 periodStartTermId = _getPeriodStartTermId(_periodId);
uint64 nextPeriodStartTermId = _getPeriodStartTermId(_periodId.add(1));
// Pick a random Court term during the next period of the requested one to get the total amount of guardian tokens active in the Court
IClock clock = _clock();
bytes32 randomness = clock.getTermRandomness(nextPeriodStartTermId);
// The randomness factor for each Court term is computed using the the hash of a block number set during the initialization of the
// term, to ensure it cannot be known beforehand. Note that the hash function being used only works for the 256 most recent block
// numbers. Therefore, if that occurs we use the hash of the previous block number. This could be slightly beneficial for the first
// guardian calling this function, but it's still impossible to predict during the requested period.
if (randomness == bytes32(0)) {
randomness = blockhash(getBlockNumber() - 1);
}
// Use randomness to choose a Court term of the requested period and query the total amount of guardian tokens active at that term
IGuardiansRegistry guardiansRegistry = _guardiansRegistry();
uint64 periodBalanceCheckpoint = periodStartTermId.add(uint64(uint256(randomness) % periodDuration));
totalActiveBalance = guardiansRegistry.totalActiveBalanceAt(periodBalanceCheckpoint);
_period.balanceCheckpoint = periodBalanceCheckpoint;
_period.totalActiveBalance = totalActiveBalance;
return (periodBalanceCheckpoint, totalActiveBalance);
}
/**
* @dev Internal function to set a new governor share value
* @param _governorSharePct New permyriad of collected payments that will be allocated to the governor of the Court (‱ - 1/10,000)
*/
function _setGovernorSharePct(uint16 _governorSharePct) internal {
// Check governor share is not greater than 10,000‱
require(PctHelpers.isValid(_governorSharePct), ERROR_OVERRATED_GOVERNOR_SHARE_PCT);
emit GovernorSharePctChanged(governorSharePct, _governorSharePct);
governorSharePct = _governorSharePct;
}
/**
* @dev Internal function to tell the identification number of the current period
* @return Identification number of the current period
*/
function _getCurrentPeriodId() internal view returns (uint256) {
// Since the Court starts at term #1, and the first payment period is #0, then subtract one unit to the current term of the Court
uint64 termId = _getCurrentTermId();
require(termId > 0, ERROR_COURT_HAS_NOT_STARTED);
// No need for SafeMath: we already checked that the term ID is at least 1
uint64 periodId = (termId - START_TERM_ID) / periodDuration;
return uint256(periodId);
}
/**
* @dev Internal function to get the current period
* @return periodId Identification number of the current period
* @return period Current period instance
*/
function _getCurrentPeriod() internal view returns (uint256 periodId, Period storage period) {
periodId = _getCurrentPeriodId();
period = periods[periodId];
}
/**
* @dev Internal function to get the Court term in which a certain period starts
* @param _periodId Identification number of the period querying the start term of
* @return Court term where the given period starts
*/
function _getPeriodStartTermId(uint256 _periodId) internal view returns (uint64) {
// Periods are measured in Court terms
// Since Court terms are represented in uint64, we are safe to use uint64 for period ids too
return START_TERM_ID.add(uint64(_periodId).mul(periodDuration));
}
/**
* @dev Internal function to tell the active balance of a guardian for a certain period
* @param _guardian Address of the guardian querying the share of
* @param _periodBalanceCheckpoint Checkpoint of the period being queried
* @return Active balance for a guardian based on the period checkpoint
*/
function _getGuardianActiveBalance(address _guardian, uint64 _periodBalanceCheckpoint) internal view returns (uint256) {
IGuardiansRegistry guardiansRegistry = _guardiansRegistry();
return guardiansRegistry.activeBalanceOfAt(_guardian, _periodBalanceCheckpoint);
}
/**
* @dev Internal function to tell the share corresponding to a guardian for a certain period and token
* @param _period Period being queried
* @param _token Address of the token being queried
* @param _guardianActiveBalance Active balance of a guardian at the corresponding period checkpoint
* @param _totalActiveBalance Total amount of guardian tokens active in the Court at the corresponding period checkpoint
* @return Share owed to the given guardian for the requested period and token
*/
function _getGuardianShare(
Period storage _period,
address _token,
uint256 _guardianActiveBalance,
uint256 _totalActiveBalance
)
internal
view
returns (uint256)
{
if (_guardianActiveBalance == 0) {
return 0;
}
// Note that we already checked the guardian active balance is greater than zero.
// Then, the total active balance should be greater than zero.
return _period.guardiansShares[_token].mul(_guardianActiveBalance) / _totalActiveBalance;
}
/**
* @dev Tell if a guardian has already claimed the owed share for a certain period
* @param _period Period being queried
* @param _guardian Address of the guardian being queried
* @param _token Address of the token to be queried
* @return True if the guardian has already claimed their share
*/
function _hasGuardianClaimed(Period storage _period, address _guardian, address _token) internal view returns (bool) {
return _period.claimedGuardians[_guardian][_token];
}
/**
* @dev Tell the share corresponding to a guardian for a certain period
* @param _period Period being queried
* @param _token Address of the token to be queried
* @return Token amount corresponding to the governor
*/
function _getGovernorShare(Period storage _period, address _token) internal view returns (uint256) {
return _period.governorShares[_token];
}
/**
* @dev Tell if the governor has already claimed the owed share for a certain period
* @param _period Period being queried
* @param _token Address of the token to be queried
* @return True if the governor has already claimed their share
*/
function _hasGovernorClaimed(Period storage _period, address _token) internal view returns (bool) {
return _period.claimedGovernor[_token];
}
} | * @notice Pay `@tokenAmount(_token, _amount)` for `_payer` (`_data`) @param _token Address of the token being paid @param _amount Amount of tokens being paid @param _payer Address paying on behalf of @param _data Optional data/ Update collected amount for the governor Update collected amount for the guardians Deposit funds from sender to this contract ETH or token amount checks are handled in `_deposit()` | function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable {
(uint256 periodId, Period storage period) = _getCurrentPeriod();
require(_amount > 0, ERROR_PAYMENT_AMOUNT_ZERO);
uint256 governorShare = _amount.pct(governorSharePct);
period.governorShares[_token] = period.governorShares[_token].add(governorShare);
uint256 guardiansShare = _amount.sub(governorShare);
period.guardiansShares[_token] = period.guardiansShares[_token].add(guardiansShare);
_deposit(msg.sender, _token, _amount);
emit PaymentReceived(periodId, _payer, _token, _amount, _data);
}
| 10,904,316 | [
1,
9148,
1375,
36,
2316,
6275,
24899,
2316,
16,
389,
8949,
22025,
364,
1375,
67,
84,
1773,
68,
21863,
67,
892,
24065,
225,
389,
2316,
5267,
434,
326,
1147,
3832,
30591,
225,
389,
8949,
16811,
434,
2430,
3832,
30591,
225,
389,
84,
1773,
5267,
8843,
310,
603,
12433,
6186,
434,
225,
389,
892,
4055,
501,
19,
2315,
12230,
3844,
364,
326,
314,
1643,
29561,
2315,
12230,
3844,
364,
326,
11026,
19657,
4019,
538,
305,
284,
19156,
628,
5793,
358,
333,
6835,
512,
2455,
578,
1147,
3844,
4271,
854,
7681,
316,
1375,
67,
323,
1724,
20338,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
8843,
12,
2867,
389,
2316,
16,
2254,
5034,
389,
8949,
16,
1758,
389,
84,
1773,
16,
1731,
745,
892,
389,
892,
13,
3903,
8843,
429,
288,
203,
3639,
261,
11890,
5034,
3879,
548,
16,
12698,
2502,
3879,
13,
273,
389,
588,
3935,
5027,
5621,
203,
3639,
2583,
24899,
8949,
405,
374,
16,
5475,
67,
16436,
67,
2192,
51,
5321,
67,
24968,
1769,
203,
203,
3639,
2254,
5034,
314,
1643,
29561,
9535,
273,
389,
8949,
18,
23989,
12,
75,
1643,
29561,
9535,
52,
299,
1769,
203,
3639,
3879,
18,
75,
1643,
29561,
24051,
63,
67,
2316,
65,
273,
3879,
18,
75,
1643,
29561,
24051,
63,
67,
2316,
8009,
1289,
12,
75,
1643,
29561,
9535,
1769,
203,
203,
3639,
2254,
5034,
11026,
19657,
9535,
273,
389,
8949,
18,
1717,
12,
75,
1643,
29561,
9535,
1769,
203,
3639,
3879,
18,
24594,
19657,
24051,
63,
67,
2316,
65,
273,
3879,
18,
24594,
19657,
24051,
63,
67,
2316,
8009,
1289,
12,
24594,
19657,
9535,
1769,
203,
203,
3639,
389,
323,
1724,
12,
3576,
18,
15330,
16,
389,
2316,
16,
389,
8949,
1769,
203,
3639,
3626,
12022,
8872,
12,
6908,
548,
16,
389,
84,
1773,
16,
389,
2316,
16,
389,
8949,
16,
389,
892,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/5/0x767AF846C674D06eD9b318fAEaCC6304009917D3/sources/contracts/guild-core/GuildBank.sol | * @dev Deposits an NFT or batch of NFTs into the contract for rental. @param _depositor The address of the depositor. @param _collection The address of the NFT collection contract. @param _tokenId The ID of the NFT to deposit. @param _share The percentage of rental revenue to be shared with the depositor. @param _duration The duration of the rental period in seconds. @param _amount The number of NFTs to deposit (for ERC1155 tokens only). @return rentalId_ The ID of the rental created./ | function deposit(
address _depositor,
address _collection,
uint256 _tokenId,
uint32 _share,
uint64 _duration,
uint32 _amount
) external onlySupportedCollection(_collection) onlyGuildContract returns (uint256 rentalId_) {
return _deposit(_depositor, _collection, _tokenId, _share, _duration, _amount);
}
| 1,940,837 | [
1,
758,
917,
1282,
392,
423,
4464,
578,
2581,
434,
423,
4464,
87,
1368,
326,
6835,
364,
283,
496,
287,
18,
225,
389,
323,
1724,
280,
1021,
1758,
434,
326,
443,
1724,
280,
18,
225,
389,
5548,
1021,
1758,
434,
326,
423,
4464,
1849,
6835,
18,
225,
389,
2316,
548,
1021,
1599,
434,
326,
423,
4464,
358,
443,
1724,
18,
225,
389,
14419,
1021,
11622,
434,
283,
496,
287,
283,
24612,
358,
506,
5116,
598,
326,
443,
1724,
280,
18,
225,
389,
8760,
1021,
3734,
434,
326,
283,
496,
287,
3879,
316,
3974,
18,
225,
389,
8949,
1021,
1300,
434,
423,
4464,
87,
358,
443,
1724,
261,
1884,
4232,
39,
2499,
2539,
2430,
1338,
2934,
327,
283,
496,
287,
548,
67,
1021,
1599,
434,
326,
283,
496,
287,
2522,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
443,
1724,
12,
203,
3639,
1758,
389,
323,
1724,
280,
16,
203,
3639,
1758,
389,
5548,
16,
203,
3639,
2254,
5034,
389,
2316,
548,
16,
203,
3639,
2254,
1578,
389,
14419,
16,
203,
3639,
2254,
1105,
389,
8760,
16,
203,
3639,
2254,
1578,
389,
8949,
203,
565,
262,
3903,
1338,
7223,
2532,
24899,
5548,
13,
1338,
43,
680,
8924,
1135,
261,
11890,
5034,
283,
496,
287,
548,
67,
13,
288,
203,
3639,
327,
389,
323,
1724,
24899,
323,
1724,
280,
16,
389,
5548,
16,
389,
2316,
548,
16,
389,
14419,
16,
389,
8760,
16,
389,
8949,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xE5dc8F1c51dF8Df4121FF13C509C441460101F14/sources/home/aaron/localdev/bliss/contracts/Bliss.sol | * @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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
| 9,625,508 | [
1,
9704,
288,
45,
654,
39,
3462,
17,
13866,
5496,
29076,
30,
300,
1375,
20367,
68,
2780,
506,
326,
3634,
1758,
18,
300,
326,
4894,
1297,
1240,
279,
11013,
434,
622,
4520,
1375,
8949,
8338,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7412,
12,
2867,
8027,
16,
2254,
5034,
3844,
13,
1071,
225,
3849,
1135,
261,
6430,
13,
288,
203,
3639,
389,
13866,
24899,
3576,
12021,
9334,
8027,
16,
3844,
1769,
203,
3639,
327,
638,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
* The Dioti token contract bases on the ERC20 standard token contracts from
* open-zeppelin and is extended by functions to issue tokens as needed by the
* Dioti ICO.
* authors: Yuda Chandra Wiguna
* */
pragma solidity ^0.4.19;
/**
* @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 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 Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) public 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 ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(ERC20 token, address from, address to, uint256 value) internal {
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title TokenTimelock
* @dev TokenTimelock is a token holder contract that will allow a
* beneficiary to extract the tokens after a given release time
*/
contract TokenTimelock {
using SafeERC20 for ERC20Basic;
// ERC20 basic token contract being held
ERC20Basic public token;
// beneficiary of tokens after they are released
address public beneficiary;
// timestamp when token release is enabled
uint64 public releaseTime;
function TokenTimelock (ERC20Basic _token, address _beneficiary, uint64 _releaseTime) public {
require(_releaseTime > uint64(block.timestamp));
token = _token;
beneficiary = _beneficiary;
releaseTime = _releaseTime;
}
/**
* @notice Transfers tokens held by timelock to beneficiary.
*/
function release() public {
require(uint64(block.timestamp) >= releaseTime);
uint256 amount = token.balanceOf(this);
require(amount > 0);
token.safeTransfer(beneficiary, amount);
}
}
/**
* @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 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
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;
}
}
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned() public {
owner = msg.sender;
}
/**
* @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;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
}
contract DiotiToken is StandardToken, Owned {
string public constant name = "DiotiToken";
string public constant symbol = "DOT";
uint8 public constant decimals = 18;
/// Maximum tokens to be allocated on the sale (51% of the hard cap)
uint256 public constant TOKENS_SALE_HARD_CAP = 510000000000000000000000000; // 510000000 * 10**18
/// Base exchange rate is set to 1 ETH = 166 DOT.
uint256 public constant BASE_RATE = 166667;
/// seconds since 01.01.1970 to 04.02.2019 (17:00:00 o'clock UTC)
/// HOT sale start time
uint64 private constant dateHOTSale = 1549360800 + 72 hours;
/// HOT sale end time; Sale A start time 07.02.2019
uint64 private constant dateSaleA = 1549558800 + 72 hours;
/// Sale A end time; Sale B start time 14.02.2019
uint64 private constant dateSaleB = 1550768400 + 72 hours;
/// Sale B end time; Sale C start time 21.02.2019
uint64 private constant dateSaleC = 1551373200 + 72 hours;
/// Sale F end time; 01.03.2018
uint64 private constant date21Mar2018 = 1553162400 + 16 hours;
/// token caps for each round
uint256[4] private roundCaps = [
70000000000000000000000, // HOT sale 70000000 * 10**15
140000000000000000000000, // Sale A 140000000 * 10**15
210000000000000000000000, // Sale B 210000000 * 10**15
285000000000000000000000 // Sale C 285000000 * 10**15
];
uint8[4] private roundDiscountPercentages = [37, 25, 16, 10];
/// team tokens are locked until this date (01.01.2020) 00:00:00
uint64 private constant dateTeamTokensLockedTill = 1577836800;
/// no tokens can be ever issued when this is set to "true"
bool public tokenSaleClosed = false;
/// contract to be called to release the Dioti team tokens
address public timelockContractAddress;
modifier inProgress {
require(totalSupply < TOKENS_SALE_HARD_CAP
&& !tokenSaleClosed && now >= dateHOTSale);
_;
}
/// Allow the closing to happen only once
modifier beforeEnd {
require(!tokenSaleClosed);
_;
}
/// Require that the token sale has been closed
modifier tradingOpen {
require(tokenSaleClosed);
_;
}
function DiotiToken() public {
}
/// @dev This default function allows token to be purchased by directly
/// sending ether to this smart contract.
function () public payable {
purchaseTokens(msg.sender);
}
/// @dev Issue token based on Ether received.
/// @param _beneficiary Address that newly issued token will be sent to.
function purchaseTokens(address _beneficiary) public payable inProgress {
// only accept a minimum amount of ETH?
require(msg.value >= 0.01 ether);
uint256 tokens = computeTokenAmount(msg.value);
// roll back if hard cap reached
require(totalSupply.add(tokens) <= TOKENS_SALE_HARD_CAP);
doIssueTokens(_beneficiary, tokens);
/// forward the raised funds to the contract creator
owner.transfer(this.balance);
}
/// @dev Batch issue tokens on the presale
/// @param _addresses addresses that the presale tokens will be sent to.
/// @param _addresses the amounts of tokens, with decimals expanded (full).
function issueTokensMulti(address[] _addresses, uint256[] _tokens) public onlyOwner beforeEnd {
require(_addresses.length == _tokens.length);
require(_addresses.length <= 100);
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
doIssueTokens(_addresses[i], _tokens[i]);
}
}
/// @dev Issue tokens for a single buyer on the presale
/// @param _beneficiary addresses that the presale tokens will be sent to.
/// @param _tokens the amount of tokens, with decimals expanded (full).
function issueTokens(address _beneficiary, uint256 _tokens) public onlyOwner beforeEnd {
doIssueTokens(_beneficiary, _tokens);
}
/// @dev issue tokens for a single buyer
/// @param _beneficiary addresses that the tokens will be sent to.
/// @param _tokens the amount of tokens, with decimals expanded (full).
function doIssueTokens(address _beneficiary, uint256 _tokens) internal {
require(_beneficiary != address(0));
// increase token total supply
totalSupply = totalSupply.add(_tokens);
// update the beneficiary balance to number of tokens sent
balances[_beneficiary] = balances[_beneficiary].add(_tokens);
// event is fired when tokens issued
Transfer(address(0), _beneficiary, _tokens);
}
/// @dev Returns the current price.
function price() public view returns (uint256 tokens) {
return computeTokenAmount(1 ether);
}
/// @dev Compute the amount of DOR token that can be purchased.
/// @param ethAmount Amount of Ether in WEI to purchase DOR.
/// @return Amount of DOR token to purchase
function computeTokenAmount(uint256 ethAmount) internal view returns (uint256 tokens) {
uint256 tokenBase = (ethAmount.mul(BASE_RATE)/10000000000000)*10000000000000;//18 decimals to 18 decimals, set precision to 5 decimals
uint8 roundNum = currentRoundIndex();
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
while(tokens.add(totalSupply) > roundCaps[roundNum] && roundNum < 4){
roundNum++;
tokens = tokenBase.mul(100)/(100 - (roundDiscountPercentages[roundNum]));
}
}
/// @dev Determine the current sale round
/// @return integer representing the index of the current sale round
function currentRoundIndex() internal view returns (uint8 roundNum) {
roundNum = currentRoundIndexByDate();
/// round determined by conjunction of both time and total sold tokens
while(roundNum < 4 && totalSupply > roundCaps[roundNum]) {
roundNum++;
}
}
/// @dev Determine the current sale tier.
/// @return the index of the current sale tier by date.
function currentRoundIndexByDate() internal view returns (uint8 roundNum) {
require(now <= date21Mar2018);
if(now > dateSaleC) return 3;
if(now > dateSaleB) return 2;
if(now > dateSaleA) return 1;
else return 0;
}
/// @dev Closes the sale, issues the team tokens and burns the unsold
function close() public onlyOwner beforeEnd {
/// team tokens are equal to 15% of the sold tokens
/// 8% foodout group tokens are added to the locked tokens
uint256 lockedTokens = 230000000000000000000000;
//partner tokens are available from the beginning
uint256 partnerTokens = 260000000000000000000000;
issueLockedTokens(lockedTokens);
issuePartnerTokens(partnerTokens);
/// increase token total supply
totalSupply = totalSupply.add(lockedTokens+partnerTokens);
/// burn the unallocated tokens - no more tokens can be issued after this line
tokenSaleClosed = true;
/// forward the raised funds to the contract creator
owner.transfer(this.balance);
}
/**
* issue the tokens for the team and the foodout group.
* tokens are locked for 3 years.
* @param lockedTokens the amount of tokens to the issued and locked
* */
function issueLockedTokens( uint lockedTokens) internal{
/// team tokens are locked until this date (01.01.2021)
TokenTimelock lockedTeamTokens = new TokenTimelock(this, owner, dateTeamTokensLockedTill);
timelockContractAddress = address(lockedTeamTokens);
balances[timelockContractAddress] = balances[timelockContractAddress].add(lockedTokens);
/// fire event when tokens issued
Transfer(address(0), timelockContractAddress, lockedTokens);
}
/**
* issue the tokens for partners and advisors
* @param partnerTokens the amount of tokens to be issued
* */
function issuePartnerTokens(uint partnerTokens) internal{
balances[owner] = partnerTokens;
Transfer(address(0), owner, partnerTokens);
}
/// Transfer limited by the tradingOpen modifier
function transferFrom(address _from, address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transferFrom(_from, _to, _value);
}
/// Transfer limited by the tradingOpen modifier
function transfer(address _to, uint256 _value) public tradingOpen returns (bool) {
return super.transfer(_to, _value);
}
}
| 18 decimals to 18 decimals, set precision to 5 decimals
| uint256 tokenBase = (ethAmount.mul(BASE_RATE)/10000000000000)*10000000000000; | 5,391,145 | [
1,
2643,
15105,
358,
6549,
15105,
16,
444,
6039,
358,
1381,
15105,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
1147,
2171,
273,
261,
546,
6275,
18,
16411,
12,
8369,
67,
24062,
13176,
21,
12648,
11706,
17653,
21,
12648,
11706,
31,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
/// @title A facet of CSportsCore that holds all important constants and modifiers
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsConstants {
/// @dev The maximum # of marketing tokens that can ever be created
/// by the commissioner.
uint16 public MAX_MARKETING_TOKENS = 2500;
/// @dev The starting price for commissioner auctions (if the average
/// of the last 2 is less than this, we will use this value)
/// A finney is 1/1000 of an ether.
uint256 public COMMISSIONER_AUCTION_FLOOR_PRICE = 5 finney; // 5 finney for production, 15 for script testing and 1 finney for Rinkeby
/// @dev The duration of commissioner auctions
uint256 public COMMISSIONER_AUCTION_DURATION = 14 days; // 30 days for testing;
/// @dev Number of seconds in a week
uint32 constant WEEK_SECS = 1 weeks;
}
/// @title A facet of CSportsCore that manages an individual's authorized role against access privileges.
/// @author CryptoSports, Inc. (https://cryptosports.team))
/// @dev See the CSportsCore contract documentation to understand how the various CSports contract facets are arranged.
contract CSportsAuth is CSportsConstants {
// This facet controls access control for CryptoSports. There are four roles managed here:
//
// - The CEO: The CEO can reassign other roles and change the addresses of our dependent smart
// contracts. It is also the only role that can unpause the smart contract. It is initially
// set to the address that created the smart contract in the CSportsCore constructor.
//
// - The CFO: The CFO can withdraw funds from CSportsCore and its auction contracts.
//
// - The COO: The COO can perform administrative functions.
//
// - The Commisioner can perform "oracle" functions like adding new real world players,
// setting players active/inactive, and scoring contests.
//
/// @dev Emited when contract is upgraded - See README.md for updgrade plan
event ContractUpgrade(address newContract);
/// The addresses of the accounts (or contracts) that can execute actions within each roles.
address public ceoAddress;
address public cfoAddress;
address public cooAddress;
address public commissionerAddress;
/// @dev Keeps track whether the contract is paused. When that is true, most actions are blocked
bool public paused = false;
/// @dev Flag that identifies whether or not we are in development and should allow development
/// only functions to be called.
bool public isDevelopment = true;
/// @dev Access modifier to allow access to development mode functions
modifier onlyUnderDevelopment() {
require(isDevelopment == true);
_;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Access modifier for Commissioner-only functionality
modifier onlyCommissioner() {
require(msg.sender == commissionerAddress);
_;
}
/// @dev Requires any one of the C level addresses
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress ||
msg.sender == commissionerAddress
);
_;
}
/// @dev prevents contracts from hitting the method
modifier notContract() {
address _addr = msg.sender;
uint256 _codeLength;
assembly {_codeLength := extcodesize(_addr)}
require(_codeLength == 0);
_;
}
/// @dev One way switch to set the contract into prodution mode. This is one
/// way in that the contract can never be set back into development mode. Calling
/// this function will block all future calls to functions that are meant for
/// access only while we are under development. It will also enable more strict
/// additional checking on various parameters and settings.
function setProduction() public onlyCEO onlyUnderDevelopment {
isDevelopment = false;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) public onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the CFO. Only available to the current CEO.
/// @param _newCFO The address of the new CFO
function setCFO(address _newCFO) public onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) public onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @dev Assigns a new address to act as the Commissioner. Only available to the current CEO.
/// @param _newCommissioner The address of the new COO
function setCommissioner(address _newCommissioner) public onlyCEO {
require(_newCommissioner != address(0));
commissionerAddress = _newCommissioner;
}
/// @dev Assigns all C-Level addresses
/// @param _ceo CEO address
/// @param _cfo CFO address
/// @param _coo COO address
/// @param _commish Commissioner address
function setCLevelAddresses(address _ceo, address _cfo, address _coo, address _commish) public onlyCEO {
require(_ceo != address(0));
require(_cfo != address(0));
require(_coo != address(0));
require(_commish != address(0));
ceoAddress = _ceo;
cfoAddress = _cfo;
cooAddress = _coo;
commissionerAddress = _commish;
}
/// @dev Transfers the balance of this contract to the CFO
function withdrawBalance() external onlyCFO {
cfoAddress.transfer(address(this).balance);
}
/*** Pausable functionality adapted from OpenZeppelin ***/
/// @dev Modifier to allow actions only when the contract IS NOT paused
modifier whenNotPaused() {
require(!paused);
_;
}
/// @dev Modifier to allow actions only when the contract IS paused
modifier whenPaused {
require(paused);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() public onlyCLevel whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
function unpause() public onlyCEO whenPaused {
paused = false;
}
}
/// @dev Interface required by league roster contract to access
/// the mintPlayers(...) function
interface CSportsRosterInterface {
/// @dev Called by core contract as a sanity check
function isLeagueRosterContract() external pure returns (bool);
/// @dev Called to indicate that a commissioner auction has completed
function commissionerAuctionComplete(uint32 _rosterIndex, uint128 _price) external;
/// @dev Called to indicate that a commissioner auction was canceled
function commissionerAuctionCancelled(uint32 _rosterIndex) external view;
/// @dev Returns the metadata for a specific real world player token
function getMetadata(uint128 _md5Token) external view returns (string);
/// @dev Called to return a roster index given the MD5
function getRealWorldPlayerRosterIndex(uint128 _md5Token) external view returns (uint128);
/// @dev Returns a player structure given its index
function realWorldPlayerFromIndex(uint128 idx) external view returns (uint128 md5Token, uint128 prevCommissionerSalePrice, uint64 lastMintedTime, uint32 mintedCount, bool hasActiveCommissionerAuction, bool mintingEnabled);
/// @dev Called to update a real world player entry - only used dureing development
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) external;
}
/// @dev This is the data structure that holds a roster player in the CSportsLeagueRoster
/// contract. Also referenced by CSportsCore.
/// @author CryptoSports, Inc. (http://cryptosports.team)
contract CSportsRosterPlayer {
struct RealWorldPlayer {
// The player's certified identification. This is the md5 hash of
// {player's last name}-{player's first name}-{player's birthday in YYYY-MM-DD format}-{serial number}
// where the serial number is usually 0, but gives us an ability to deal with making
// sure all MD5s are unique.
uint128 md5Token;
// Stores the average sale price of the most recent 2 commissioner sales
uint128 prevCommissionerSalePrice;
// The last time this real world player was minted.
uint64 lastMintedTime;
// The number of PlayerTokens minted for this real world player
uint32 mintedCount;
// When true, there is an active auction for this player owned by
// the commissioner (indicating a gen0 minting auction is in progress)
bool hasActiveCommissionerAuction;
// Indicates this real world player can be actively minted
bool mintingEnabled;
// Any metadata we want to attach to this player (in JSON format)
string metadata;
}
}
/// @title CSportsTeam Interface
/// @dev This interface defines methods required by the CSportsContestCore
/// in implementing a contest.
/// @author CryptoSports
contract CSportsTeam {
bool public isTeamContract;
/// @dev Define team events
event TeamCreated(uint256 teamId, address owner);
event TeamUpdated(uint256 teamId);
event TeamReleased(uint256 teamId);
event TeamScored(uint256 teamId, int32 score, uint32 place);
event TeamPaid(uint256 teamId);
function setCoreContractAddress(address _address) public;
function setLeagueRosterContractAddress(address _address) public;
function setContestContractAddress(address _address) public;
function createTeam(address _owner, uint32[] _tokenIds) public returns (uint32);
function updateTeam(address _owner, uint32 _teamId, uint8[] _indices, uint32[] _tokenIds) public;
function releaseTeam(uint32 _teamId) public;
function getTeamOwner(uint32 _teamId) public view returns (address);
function scoreTeams(uint32[] _teamIds, int32[] _scores, uint32[] _places) public;
function getScore(uint32 _teamId) public view returns (int32);
function getPlace(uint32 _teamId) public view returns (uint32);
function ownsPlayerTokens(uint32 _teamId) public view returns (bool);
function refunded(uint32 _teamId) public;
function tokenIdsForTeam(uint32 _teamId) public view returns (uint32, uint32[50]);
function getTeam(uint32 _teamId) public view returns (
address _owner,
int32 _score,
uint32 _place,
bool _holdsEntryFee,
bool _ownsPlayerTokens);
}
/// @title Base contract for CryptoSports. Holds all common structs, events and base variables.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsBase is CSportsAuth, CSportsRosterPlayer {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/// @dev This emits when a commissioner auction is successfully closed
event CommissionerAuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
/// @dev This emits when a commissioner auction is canceled
event CommissionerAuctionCanceled(uint256 tokenId);
/******************/
/*** DATA TYPES ***/
/******************/
/// @dev The main player token structure. Every released player in the League
/// is represented by a single instance of this structure.
struct PlayerToken {
// @dev ID of the real world player this token represents. We can only have
// a max of 4,294,967,295 real world players, which seems to be enough for
// a while (haha)
uint32 realWorldPlayerId;
// @dev Serial number indicating the number of PlayerToken(s) for this
// same realWorldPlayerId existed at the time this token was minted.
uint32 serialNumber;
// The timestamp from the block when this player token was minted.
uint64 mintedTime;
// The most recent sale price of the player token in an auction
uint128 mostRecentPrice;
}
/**************************/
/*** MAPPINGS (STORAGE) ***/
/**************************/
/// @dev A mapping from a PlayerToken ID to the address that owns it. All
/// PlayerTokens have an owner (newly minted PlayerTokens are owned by
/// the core contract).
mapping (uint256 => address) public playerTokenToOwner;
/// @dev Maps a PlayerToken ID to an address approved to take ownership.
mapping (uint256 => address) public playerTokenToApproved;
// @dev A mapping to a given address' tokens
mapping(address => uint32[]) public ownedTokens;
// @dev A mapping that relates a token id to an index into the
// ownedTokens[currentOwner] array.
mapping(uint32 => uint32) tokenToOwnedTokensIndex;
/// @dev Maps operators
mapping(address => mapping(address => bool)) operators;
// This mapping and corresponding uint16 represent marketing tokens
// that can be created by the commissioner (up to remainingMarketingTokens)
// and then given to third parties in the form of 4 words that sha256
// hash into the key for the mapping.
//
// Maps uint256(keccak256) => leagueRosterPlayerMD5
uint16 public remainingMarketingTokens = MAX_MARKETING_TOKENS;
mapping (uint256 => uint128) marketingTokens;
/***************/
/*** STORAGE ***/
/***************/
/// @dev Instance of our CSportsLeagueRoster contract. Can be set by
/// the CEO only once because this immutable tie to the league roster
/// is what relates a playerToken to a real world player. If we could
/// update the leagueRosterContract, we could in effect de-value the
/// ownership of a playerToken by switching the real world player it
/// represents.
CSportsRosterInterface public leagueRosterContract;
/// @dev Addresses of team contract that is authorized to hold player
/// tokens for contests.
CSportsTeam public teamContract;
/// @dev An array containing all PlayerTokens in existence.
PlayerToken[] public playerTokens;
/************************************/
/*** RESTRICTED C-LEVEL FUNCTIONS ***/
/************************************/
/// @dev Sets the reference to the CSportsLeagueRoster contract.
/// @param _address - Address of CSportsLeagueRoster contract.
function setLeagueRosterContractAddress(address _address) public onlyCEO {
// This method may only be called once to guarantee the immutable
// nature of owning a real world player.
if (!isDevelopment) {
require(leagueRosterContract == address(0));
}
CSportsRosterInterface candidateContract = CSportsRosterInterface(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isLeagueRosterContract());
// Set the new contract address
leagueRosterContract = candidateContract;
}
/// @dev Adds an authorized team contract that can hold player tokens
/// on behalf of a contest, and will return them to the original
/// owner when the contest is complete (or if entry is canceled by
/// the original owner, or if the contest is canceled).
function setTeamContractAddress(address _address) public onlyCEO {
CSportsTeam candidateContract = CSportsTeam(_address);
// NOTE: verify that a contract is what we expect (not foolproof, just
// a sanity check)
require(candidateContract.isTeamContract());
// Set the new contract address
teamContract = candidateContract;
}
/**************************/
/*** INTERNAL FUNCTIONS ***/
/**************************/
/// @dev Identifies whether or not the addressToTest is a contract or not
/// @param addressToTest The address we are interested in
function _isContract(address addressToTest) internal view returns (bool) {
uint size;
assembly {
size := extcodesize(addressToTest)
}
return (size > 0);
}
/// @dev Returns TRUE if the token exists
/// @param _tokenId ID to check
function _tokenExists(uint256 _tokenId) internal view returns (bool) {
return (_tokenId < playerTokens.length);
}
/// @dev An internal method that mints a new playerToken and stores it
/// in the playerTokens array.
/// @param _realWorldPlayerId ID of the real world player to mint
/// @param _serialNumber - Indicates the number of playerTokens for _realWorldPlayerId
/// that exist prior to this to-be-minted playerToken.
/// @param _owner - The owner of this newly minted playerToken
function _mintPlayer(uint32 _realWorldPlayerId, uint32 _serialNumber, address _owner) internal returns (uint32) {
// We are careful here to make sure the calling contract keeps within
// our structure's size constraints. Highly unlikely we would ever
// get to a point where these constraints would be a problem.
require(_realWorldPlayerId < 4294967295);
require(_serialNumber < 4294967295);
PlayerToken memory _player = PlayerToken({
realWorldPlayerId: _realWorldPlayerId,
serialNumber: _serialNumber,
mintedTime: uint64(now),
mostRecentPrice: 0
});
uint256 newPlayerTokenId = playerTokens.push(_player) - 1;
// It's probably never going to happen, 4 billion playerToken(s) is A LOT, but
// let's just be 100% sure we never let this happen.
require(newPlayerTokenId < 4294967295);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
_transfer(0, _owner, newPlayerTokenId);
return uint32(newPlayerTokenId);
}
/// @dev Removes a token (specified by ID) from ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _from Address to remove from
/// @param _tokenId ID of token to remove
function _removeTokenFrom(address _from, uint256 _tokenId) internal {
// Grab the index into the _from owner's ownedTokens array
uint32 fromIndex = tokenToOwnedTokensIndex[uint32(_tokenId)];
// Remove the _tokenId from ownedTokens[_from] array
uint lastIndex = ownedTokens[_from].length - 1;
uint32 lastToken = ownedTokens[_from][lastIndex];
// Swap the last token into the fromIndex position (which is _tokenId's
// location in the ownedTokens array) and shorten the array
ownedTokens[_from][fromIndex] = lastToken;
ownedTokens[_from].length--;
// Since we moved lastToken, we need to update its
// entry in the tokenToOwnedTokensIndex
tokenToOwnedTokensIndex[lastToken] = fromIndex;
// _tokenId is no longer mapped
tokenToOwnedTokensIndex[uint32(_tokenId)] = 0;
}
/// @dev Adds a token (specified by ID) to ownedTokens and
/// tokenToOwnedTokensIndex mappings for a given address.
/// @param _to Address to add to
/// @param _tokenId ID of token to remove
function _addTokenTo(address _to, uint256 _tokenId) internal {
uint32 toIndex = uint32(ownedTokens[_to].push(uint32(_tokenId))) - 1;
tokenToOwnedTokensIndex[uint32(_tokenId)] = toIndex;
}
/// @dev Assigns ownership of a specific PlayerToken to an address.
/// @param _from - Address of who this transfer is from
/// @param _to - Address of who to tranfer to
/// @param _tokenId - The ID of the playerToken to transfer
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// transfer ownership
playerTokenToOwner[_tokenId] = _to;
// When minting brand new PlayerTokens, the _from is 0x0, but we don't deal with
// owned tokens for the 0x0 address.
if (_from != address(0)) {
// Remove the _tokenId from ownedTokens[_from] array (remove first because
// this method will zero out the tokenToOwnedTokensIndex[_tokenId], which would
// stomp on the _addTokenTo setting of this value)
_removeTokenFrom(_from, _tokenId);
// Clear our approved mapping for this token
delete playerTokenToApproved[_tokenId];
}
// Now add the token to the _to address' ownership structures
_addTokenTo(_to, _tokenId);
// Emit the transfer event.
emit Transfer(_from, _to, _tokenId);
}
/// @dev Converts a uint to its string equivalent
/// @param v uint to convert
function uintToString(uint v) internal pure returns (string str) {
bytes32 b32 = uintToBytes32(v);
str = bytes32ToString(b32);
}
/// @dev Converts a uint to a bytes32
/// @param v uint to convert
function uintToBytes32(uint v) internal pure returns (bytes32 ret) {
if (v == 0) {
ret = '0';
}
else {
while (v > 0) {
ret = bytes32(uint(ret) / (2 ** 8));
ret |= bytes32(((v % 10) + 48) * 2 ** (8 * 31));
v /= 10;
}
}
return ret;
}
/// @dev Converts bytes32 to a string
/// @param data bytes32 to convert
function bytes32ToString (bytes32 data) internal pure returns (string) {
uint count = 0;
bytes memory bytesString = new bytes(32); // = new bytes[]; //(32);
for (uint j=0; j<32; j++) {
byte char = byte(bytes32(uint(data) * 2 ** (8 * j)));
if (char != 0) {
bytesString[j] = char;
count++;
} else {
break;
}
}
bytes memory s = new bytes(count);
for (j = 0; j < count; j++) {
s[j] = bytesString[j];
}
return string(s);
}
}
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
///
/// MOVED THIS TO CSportsBase because of how class structure is derived.
///
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// @title ERC-721 Non-Fungible Token Standard, optional metadata extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
interface ERC165 {
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
/// @title The facet of the CSports core contract that manages ownership, ERC-721 compliant.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev Ref: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md#specification
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsOwnership is CSportsBase {
/// @notice These are set in the contract constructor at deployment time
string _name;
string _symbol;
string _tokenURI;
// bool public implementsERC721 = true;
//
function implementsERC721() public pure returns (bool)
{
return true;
}
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string) {
return _name;
}
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string) {
return _symbol;
}
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string ret) {
string memory tokenIdAsString = uintToString(uint(_tokenId));
ret = string (abi.encodePacked(_tokenURI, tokenIdAsString, "/"));
}
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId)
public
view
returns (address owner)
{
owner = playerTokenToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) public view returns (uint256 count) {
// I am not a big fan of referencing a property on an array element
// that may not exist. But if it does not exist, Solidity will return 0
// which is right.
return ownedTokens[_owner].length;
}
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
require(_to != address(0));
require (_tokenExists(_tokenId));
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
/// @notice Transfer ownership of a batch of NFTs -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for all NFTs. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// any `_tokenId` is not a valid NFT.
/// @param _from - Current owner of the token being authorized for transfer
/// @param _to - Address we are transferring to
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchTransferFrom(
address _from,
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Check for approval and valid ownership
require(_approvedFor(_to, _tokenId));
require(_owns(_from, _tokenId));
// Validate the sender
require(_owns(msg.sender, _tokenId) || // sender owns the token
(msg.sender == playerTokenToApproved[_tokenId]) || // sender is the approved address
operators[_from][msg.sender]); // sender is an authorized operator for this token
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_from, _to, _tokenId);
}
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(
address _to,
uint256 _tokenId
)
public
whenNotPaused
{
address owner = ownerOf(_tokenId);
require(_to != owner);
// Only an owner or authorized operator can grant transfer approval.
require((msg.sender == owner) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _to The address to be granted transfer approval. Pass address(0) to
/// clear all approvals.
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchApprove(
address _to,
uint32[] _tokenIds
)
public
whenNotPaused
{
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner or authorized operator can grant transfer approval.
require(_owns(msg.sender, _tokenId) || (operators[ownerOf(_tokenId)][msg.sender]));
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
}
/// @notice Escrows all of the tokensIds passed by transfering ownership
/// to the teamContract. CAN ONLY BE CALLED BY THE CURRENT TEAM CONTRACT.
/// @param _owner - Current owner of the token being authorized for transfer
/// @param _tokenIds The IDs of the PlayerTokens that can be transferred if this call succeeds.
function batchEscrowToTeamContract(
address _owner,
uint32[] _tokenIds
)
public
whenNotPaused
{
require(teamContract != address(0));
require(msg.sender == address(teamContract));
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = _tokenIds[i];
// Only an owner can transfer the token.
require(_owns(_owner, _tokenId));
// Reassign ownership, clear pending approvals (not necessary here),
// and emit Transfer event.
_transfer(_owner, teamContract, _tokenId);
}
}
bytes4 constant TOKEN_RECEIVED_SIG = bytes4(keccak256("onERC721Received(address,uint256,bytes)"));
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external payable {
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, data);
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable {
require(_to != address(0));
transferFrom(_from, _to, _tokenId);
if (_isContract(_to)) {
ERC721TokenReceiver receiver = ERC721TokenReceiver(_to);
bytes4 response = receiver.onERC721Received.gas(50000)(msg.sender, _from, _tokenId, "");
require(response == TOKEN_RECEIVED_SIG);
}
}
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() public view returns (uint) {
return playerTokens.length;
}
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `index` >= `balanceOf(owner)` or if
/// `owner` is the zero address, representing invalid NFTs.
/// @param owner An address where we are interested in NFTs owned by them
/// @param index A counter less than `balanceOf(owner)`
/// @return The token identifier for the `index`th NFT assigned to `owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 _tokenId) {
require(owner != address(0));
require(index < balanceOf(owner));
return ownedTokens[owner][index];
}
/// @notice Enumerate valid NFTs
/// @dev Throws if `index` >= `totalSupply()`.
/// @param index A counter less than `totalSupply()`
/// @return The token identifier for the `index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 index) external view returns (uint256) {
require (_tokenExists(index));
return index;
}
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external {
require(_operator != msg.sender);
operators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address) {
require(_tokenExists(_tokenId));
return playerTokenToApproved[_tokenId];
}
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) public pure returns (bool) {
return (
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x80ac58cd || // ERC-721
interfaceID == 0x780e9d63); // ERC721Enumerable
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular PlayerToken.
/// @param _claimant the address we are validating against.
/// @param _tokenId kitten id, only valid when > 0
function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToOwner[_tokenId] == _claimant;
}
/// @dev Checks if a given address currently has transferApproval for a particular PlayerToken.
/// @param _claimant the address we are confirming PlayerToken is approved for.
/// @param _tokenId PlayerToken id, only valid when > 0
function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transferFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transferFrom() are used together for putting PlayerToken on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint256 _tokenId, address _approved) internal {
playerTokenToApproved[_tokenId] = _approved;
}
}
/// @dev Interface to the sale clock auction contract
interface CSportsAuctionInterface {
/// @dev Sanity check that allows us to ensure that we are pointing to the
/// right auction in our setSaleAuctionAddress() call.
function isSaleClockAuction() external pure returns (bool);
/// @dev Creates and begins a new auction.
/// @param _tokenId - ID of token to auction, sender must be owner.
/// @param _startingPrice - Price of item (in wei) at beginning of auction.
/// @param _endingPrice - Price of item (in wei) at end of auction.
/// @param _duration - Length of auction (in seconds).
/// @param _seller - Seller, if not the message sender
function createAuction(
uint256 _tokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration,
address _seller
) external;
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract.
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices
/// @param _endingPrices New ending price
/// @param _duration New duration
/// @param _seller Address of the seller in all specified auctions to be updated
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration,
address _seller
) external;
/// @dev Cancels an auction that hasn't been won yet by calling
/// the super(...) and then notifying any listener.
/// @param _tokenId - ID of token on auction
function cancelAuction(uint256 _tokenId) external;
/// @dev Withdraw the total contract balance to the core contract
function withdrawBalance() external;
}
/// @title Interface to allow a contract to listen to auction events.
contract SaleClockAuctionListener {
function implementsSaleClockAuctionListener() public pure returns (bool);
function auctionCreated(uint256 tokenId, address seller, uint128 startingPrice, uint128 endingPrice, uint64 duration) public;
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address buyer) public;
function auctionCancelled(uint256 tokenId, address seller) public;
}
/// @title The facet of the CSports core contract that manages interfacing with auctions
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsAuction is CSportsOwnership, SaleClockAuctionListener {
// Holds a reference to our saleClockAuctionContract
CSportsAuctionInterface public saleClockAuctionContract;
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function implementsSaleClockAuctionListener() public pure returns (bool) {
return true;
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
function auctionCreated(uint256 /* tokenId */, address /* seller */, uint128 /* startingPrice */, uint128 /* endingPrice */, uint64 /* duration */) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction successfully completed
/// @param totalPrice - Price at which the auction closed at
/// @param seller - Account address of the auction seller
/// @param winner - Account address of the auction winner (buyer)
function auctionSuccessful(uint256 tokenId, uint128 totalPrice, address seller, address winner) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
// Record the most recent sale price to the token
PlayerToken storage _playerToken = playerTokens[tokenId];
_playerToken.mostRecentPrice = totalPrice;
if (seller == address(this)) {
// We completed a commissioner auction!
leagueRosterContract.commissionerAuctionComplete(playerTokens[tokenId].realWorldPlayerId, totalPrice);
emit CommissionerAuctionSuccessful(tokenId, totalPrice, winner);
}
}
/// @dev SaleClockAuctionLIstener interface method concrete implementation
/// @param tokenId - ID of the token whose auction was cancelled
/// @param seller - Account address of seller who decided to cancel the auction
function auctionCancelled(uint256 tokenId, address seller) public {
require (saleClockAuctionContract != address(0));
require (msg.sender == address(saleClockAuctionContract));
if (seller == address(this)) {
// We cancelled a commissioner auction!
leagueRosterContract.commissionerAuctionCancelled(playerTokens[tokenId].realWorldPlayerId);
emit CommissionerAuctionCanceled(tokenId);
}
}
/// @dev Sets the reference to the sale auction.
/// @param _address - Address of sale contract.
function setSaleAuctionContractAddress(address _address) public onlyCEO {
require(_address != address(0));
CSportsAuctionInterface candidateContract = CSportsAuctionInterface(_address);
// Sanity check
require(candidateContract.isSaleClockAuction());
// Set the new contract address
saleClockAuctionContract = candidateContract;
}
/// @dev Allows the commissioner to cancel his auctions (which are owned
/// by this contract)
function cancelCommissionerAuction(uint32 tokenId) public onlyCommissioner {
require(saleClockAuctionContract != address(0));
saleClockAuctionContract.cancelAuction(tokenId);
}
/// @dev Put a player up for auction. The message sender must own the
/// player token being put up for auction.
/// @param _playerTokenId - ID of playerToken to be auctioned
/// @param _startingPrice - Starting price in wei
/// @param _endingPrice - Ending price in wei
/// @param _duration - Duration in seconds
function createSaleAuction(
uint256 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration
)
public
whenNotPaused
{
// Auction contract checks input sizes
// If player is already on any auction, this will throw
// because it will be owned by the auction contract.
require(_owns(msg.sender, _playerTokenId));
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
msg.sender
);
}
/// @dev Transfers the balance of the sale auction contract
/// to the CSportsCore contract. We use two-step withdrawal to
/// avoid two transfer calls in the auction bid function.
/// To withdraw from this CSportsCore contract, the CFO must call
/// the withdrawBalance(...) function defined in CSportsAuth.
function withdrawAuctionBalances() external onlyCOO {
saleClockAuctionContract.withdrawBalance();
}
}
/// @title The facet of the CSportsCore contract that manages minting new PlayerTokens
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// See the CSportsCore contract documentation to understand how the various contract facets are arranged.
contract CSportsMinting is CSportsAuction {
/// @dev MarketingTokenRedeemed event is fired when a marketing token has been redeemed
event MarketingTokenRedeemed(uint256 hash, uint128 rwpMd5, address indexed recipient);
/// @dev MarketingTokenCreated event is fired when a marketing token has been created
event MarketingTokenCreated(uint256 hash, uint128 rwpMd5);
/// @dev MarketingTokenReplaced event is fired when a marketing token has been replaced
event MarketingTokenReplaced(uint256 oldHash, uint256 newHash, uint128 rwpMd5);
/// @dev Sanity check that identifies this contract as having minting capability
function isMinter() public pure returns (bool) {
return true;
}
/// @dev Utility function to make it easy to keccak256 a string in python or javascript using
/// the exact algorythm used by Solidity.
function getKeccak256(string stringToHash) public pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(stringToHash)));
}
/// @dev Allows the commissioner to load up our marketingTokens mapping with up to
/// MAX_MARKETING_TOKENS marketing tokens that can be created if one knows the words
/// to keccak256 and match the keywordHash passed here. Use web3.utils.soliditySha3(param1 [, param2, ...])
/// to create this hash.
///
/// ONLY THE COMMISSIONER CAN CREATE MARKETING TOKENS, AND ONLY UP TO MAX_MARKETING_TOKENS OF THEM
///
/// @param keywordHash - keccak256 of a known set of keyWords
/// @param md5Token - The md5 key in the leagueRosterContract that specifies the player
/// player token that will be minted and transfered by the redeemMarketingToken(...) method.
function addMarketingToken(uint256 keywordHash, uint128 md5Token) public onlyCommissioner {
require(remainingMarketingTokens > 0);
require(marketingTokens[keywordHash] == 0);
// Make sure the md5Token exists in the league roster
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(md5Token);
require(_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
// Map the keyword Hash to the RWP md5 and decrement the remainingMarketingTokens property
remainingMarketingTokens--;
marketingTokens[keywordHash] = md5Token;
emit MarketingTokenCreated(keywordHash, md5Token);
}
/// @dev This method allows the commish to replace an existing marketing token that has
/// not been used with a new one (new hash and mdt). Since we are replacing, we co not
/// have to deal with remainingMarketingTokens in any way. This is to allow for replacing
/// marketing tokens that have not been redeemed and aren't likely to be redeemed (breakage)
///
/// ONLY THE COMMISSIONER CAN ACCESS THIS METHOD
///
/// @param oldKeywordHash Hash to replace
/// @param newKeywordHash Hash to replace with
/// @param md5Token The md5 key in the leagueRosterContract that specifies the player
function replaceMarketingToken(uint256 oldKeywordHash, uint256 newKeywordHash, uint128 md5Token) public onlyCommissioner {
uint128 _md5Token = marketingTokens[oldKeywordHash];
if (_md5Token != 0) {
marketingTokens[oldKeywordHash] = 0;
marketingTokens[newKeywordHash] = md5Token;
emit MarketingTokenReplaced(oldKeywordHash, newKeywordHash, md5Token);
}
}
/// @dev Returns the real world player's MD5 key from a keywords string. A 0x00 returned
/// value means the keyword string parameter isn't mapped to a marketing token.
/// @param keyWords Keywords to use to look up RWP MD5
//
/// ANYONE CAN VALIDATE A KEYWORD STRING (MAP IT TO AN MD5 IF IT HAS ONE)
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens
/// mapping (or not)
function MD5FromMarketingKeywords(string keyWords) public view returns (uint128) {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
return _md5Token;
}
/// @dev Allows anyone to try to redeem a marketing token by passing N words that will
/// be SHA256'ed to match an entry in our marketingTokens mapping. If a match is found,
/// a CryptoSports token is created that corresponds to the md5 retrieved
/// from the marketingTokens mapping and its owner is assigned as the msg.sender.
///
/// ANYONE CAN REDEEM A MARKETING token
///
/// @param keyWords - A string that will keccak256 to an entry in the marketingTokens mapping
function redeemMarketingToken(string keyWords) public {
uint256 keyWordsHash = uint256(keccak256(abi.encodePacked(keyWords)));
uint128 _md5Token = marketingTokens[keyWordsHash];
if (_md5Token != 0) {
// Only one redemption per set of keywords
marketingTokens[keyWordsHash] = 0;
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex != 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Grab the real world player record from the leagueRosterContract
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Mint this player, sending it to the message sender
_mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, msg.sender);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction. The only portion of
// the RWP record we change here is an update to the mingedCount.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled);
emit MarketingTokenRedeemed(keyWordsHash, _rwp.md5Token, msg.sender);
}
}
}
/// @dev Returns an array of minimum auction starting prices for an array of players
/// specified by their MD5s.
/// @param _md5Tokens MD5s in the league roster for the players we are inquiring about.
function minStartPriceForCommishAuctions(uint128[] _md5Tokens) public view onlyCommissioner returns (uint128[50]) {
require (_md5Tokens.length <= 50);
uint128[50] memory minPricesArray;
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
// Skip this if there is no player associated with the md5 specified
if (_rwp.md5Token != _md5Token) continue;
minPricesArray[i] = uint128(_computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice));
}
return minPricesArray;
}
/// @dev Creates newly minted playerTokens and puts them up for auction. This method
/// can only be called by the commissioner, and checks to make sure certian minting
/// conditions are met (reverting if not met):
/// * The MD5 of the RWP specified must exist in the CSportsLeagueRoster contract
/// * Cannot mint a realWorldPlayer that currently has an active commissioner auction
/// * Cannot mint realWorldPlayer that does not have minting enabled
/// * Cannot mint realWorldPlayer with a start price exceeding our minimum
/// If any of the above conditions fails to be met, then no player tokens will be
/// minted.
///
/// *** ONLY THE COMMISSIONER OR THE LEAGUE ROSTER CONTRACT CAN CALL THIS FUNCTION ***
///
/// @param _md5Tokens - array of md5Tokens representing realWorldPlayer that we are minting.
/// @param _startPrice - the starting price for the auction (0 will set to current minimum price)
function mintPlayers(uint128[] _md5Tokens, uint256 _startPrice, uint256 _endPrice, uint256 _duration) public {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require((msg.sender == commissionerAddress) || (msg.sender == address(leagueRosterContract)));
for (uint32 i = 0; i < _md5Tokens.length; i++) {
uint128 _md5Token = _md5Tokens[i];
uint128 _rosterIndex = leagueRosterContract.getRealWorldPlayerRosterIndex(_md5Token);
if (_rosterIndex == 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) {
// Cannot mint a non-existent real world player
continue;
}
// We don't have to check _rosterIndex here because the getRealWorldPlayerRosterIndex(...)
// method always returns a valid index.
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(_rosterIndex);
if (_rwp.md5Token != _md5Token) continue;
if (!_rwp.mintingEnabled) continue;
// Enforce the restrictions that there can ever only be a single outstanding commissioner
// auction - no new minting if there is an active commissioner auction for this real world player
if (_rwp.hasActiveCommissionerAuction) continue;
// Ensure that our price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// Make sure the start price exceeds our minimum acceptable
if (_startPrice < _minStartPrice) {
_startPrice = _minStartPrice;
}
// Mint the new player token
uint32 _playerId = _mintPlayer(uint32(_rosterIndex), _rwp.mintedCount, address(this));
// @dev Approve ownership transfer to the saleClockAuctionContract (which is required by
// the createAuction(...) which will escrow the playerToken)
_approve(_playerId, saleClockAuctionContract);
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// By setting our _endPrice to zero, we become immune to the USD <==> ether
// conversion rate. No matter how high ether goes, our auction price will get
// to a USD value that is acceptable to someone (assuming 0 is acceptable that is).
// This also helps for players that aren't in very much demand.
saleClockAuctionContract.createAuction(
_playerId,
_startPrice,
_endPrice,
_duration,
address(this)
);
// Finally, update our realWorldPlayer record to reflect the fact that we just
// minted a new one, and there is an active commish auction.
leagueRosterContract.updateRealWorldPlayer(uint32(_rosterIndex), _rwp.prevCommissionerSalePrice, uint64(now), _rwp.mintedCount + 1, true, _rwp.mintingEnabled);
}
}
/// @dev Reprices (and updates duration) of an array of tokens that are currently
/// being auctioned by this contract. Since this function can only be called by
/// the commissioner, we don't do a lot of checking of parameters and things.
/// The SaleClockAuction's repriceAuctions method assures that the CSportsCore
/// contract is the "seller" of the token (meaning it is a commissioner auction).
/// @param _tokenIds Array of tokenIds corresponding to auctions being updated
/// @param _startingPrices New starting prices for each token being repriced
/// @param _endingPrices New ending price
/// @param _duration New duration
function repriceAuctions(
uint256[] _tokenIds,
uint256[] _startingPrices,
uint256[] _endingPrices,
uint256 _duration
) external onlyCommissioner {
// We cannot reprice below our player minimum
for (uint32 i = 0; i < _tokenIds.length; i++) {
uint32 _tokenId = uint32(_tokenIds[i]);
PlayerToken memory pt = playerTokens[_tokenId];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
// We require the price to be >= our _minStartPrice
require(_startingPrices[i] >= _minStartPrice);
}
// Note we pass in this CSportsCore contract address as the seller, making sure the only auctions
// that can be repriced by this method are commissioner auctions.
saleClockAuctionContract.repriceAuctions(_tokenIds, _startingPrices, _endingPrices, _duration, address(this));
}
/// @dev Allows the commissioner to create a sale auction for a token
/// that is owned by the core contract. Can only be called when not paused
/// and only by the commissioner
/// @param _playerTokenId - ID of the player token currently owned by the core contract
/// @param _startingPrice - Starting price for the auction
/// @param _endingPrice - Ending price for the auction
/// @param _duration - Duration of the auction (in seconds)
function createCommissionerAuction(uint32 _playerTokenId,
uint256 _startingPrice,
uint256 _endingPrice,
uint256 _duration)
public whenNotPaused onlyCommissioner {
require(leagueRosterContract != address(0));
require(_playerTokenId < playerTokens.length);
// If player is already on any auction, this will throw because it will not be owned by
// this CSportsCore contract (as all commissioner tokens are if they are not currently
// on auction).
// Any token owned by the CSportsCore contract by definition is a commissioner auction
// that was canceled which makes it OK to re-list.
require(_owns(address(this), _playerTokenId));
// (1) Grab the real world token ID (md5)
PlayerToken memory pt = playerTokens[_playerTokenId];
// (2) Get the full real world player record from its roster index
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
// Ensure that our starting price is not less than a minimum
uint256 _minStartPrice = _computeNextCommissionerPrice(_rwp.prevCommissionerSalePrice);
if (_startingPrice < _minStartPrice) {
_startingPrice = _minStartPrice;
}
// Apply the default duration
if (_duration == 0) {
_duration = COMMISSIONER_AUCTION_DURATION;
}
// Approve the token for transfer
_approve(_playerTokenId, saleClockAuctionContract);
// saleClockAuctionContract.createAuction throws if inputs are invalid and clears
// transfer after escrowing the player.
saleClockAuctionContract.createAuction(
_playerTokenId,
_startingPrice,
_endingPrice,
_duration,
address(this)
);
}
/// @dev Computes the next commissioner auction starting price equal to
/// the previous real world player sale price + 25% (with a floor).
function _computeNextCommissionerPrice(uint128 prevTwoCommissionerSalePriceAve) internal view returns (uint256) {
uint256 nextPrice = prevTwoCommissionerSalePriceAve + (prevTwoCommissionerSalePriceAve / 4);
// sanity check to ensure we don't overflow arithmetic (this big number is 2^128-1).
if (nextPrice > 340282366920938463463374607431768211455) {
nextPrice = 340282366920938463463374607431768211455;
}
// We never auction for less than our floor
if (nextPrice < COMMISSIONER_AUCTION_FLOOR_PRICE) {
nextPrice = COMMISSIONER_AUCTION_FLOOR_PRICE;
}
return nextPrice;
}
}
/// @notice This is the main contract that implements the csports ERC721 token.
/// @author CryptoSports, Inc. (http://cryptosports.team)
/// @dev This contract is made up of a series of parent classes so that we could
/// break the code down into meaningful amounts of related functions in
/// single files, as opposed to having one big file. The purpose of
/// each facet is given here:
///
/// CSportsConstants - This facet holds constants used throughout.
/// CSportsAuth -
/// CSportsBase -
/// CSportsOwnership -
/// CSportsAuction -
/// CSportsMinting -
/// CSportsCore - This is the main CSports constract implementing the CSports
/// Fantash Football League. It manages contract upgrades (if / when
/// they might occur), and has generally useful helper methods.
///
/// This CSportsCore contract interacts with the CSportsLeagueRoster contract
/// to determine which PlayerTokens to mint.
///
/// This CSportsCore contract interacts with the TimeAuction contract
/// to implement and run PlayerToken auctions (sales).
contract CSportsCore is CSportsMinting {
/// @dev Used by other contracts as a sanity check
bool public isCoreContract = true;
// Set if (hopefully not) the core contract needs to be upgraded. Can be
// set by the CEO but only when paused. When successfully set, we can never
// unpause this contract. See the unpause() method overridden by this class.
address public newContractAddress;
/// @notice Class constructor creates the main CSportsCore smart contract instance.
/// @param nftName The ERC721 name for the contract
/// @param nftSymbol The ERC721 symbol for the contract
/// @param nftTokenURI The ERC721 token uri for the contract
constructor(string nftName, string nftSymbol, string nftTokenURI) public {
// New contract starts paused.
paused = true;
/// @notice storage for the fields that identify this 721 token
_name = nftName;
_symbol = nftSymbol;
_tokenURI = nftTokenURI;
// All C-level roles are the message sender
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
commissionerAddress = msg.sender;
}
/// @dev Reject all Ether except if it's from one of our approved sources
function() external payable {
/*require(
msg.sender == address(saleClockAuctionContract)
);*/
}
/// --------------------------------------------------------------------------- ///
/// ----------------------------- PUBLIC FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Used to mark the smart contract as upgraded, in case there is a serious
/// bug. This method does nothing but keep track of the new contract and
/// emit a message indicating that the new address is set. It's up to clients of this
/// contract to update to the new contract address in that case. (This contract will
/// be paused indefinitely if such an upgrade takes place.)
/// @param _v2Address new address
function upgradeContract(address _v2Address) public onlyCEO whenPaused {
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @dev Override unpause so it requires all external contract addresses
/// to be set before contract can be unpaused. Also require that we have
/// set a valid season and the contract has not been upgraded.
function unpause() public onlyCEO whenPaused {
require(leagueRosterContract != address(0));
require(saleClockAuctionContract != address(0));
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
/// @dev Consolidates setting of contract links into a single call for deployment expediency
function setLeagueRosterAndSaleAndTeamContractAddress(address _leagueAddress, address _saleAddress, address _teamAddress) public onlyCEO {
setLeagueRosterContractAddress(_leagueAddress);
setSaleAuctionContractAddress(_saleAddress);
setTeamContractAddress(_teamAddress);
}
/// @dev Returns all the relevant information about a specific playerToken.
///@param _playerTokenID - player token ID we are seeking the full player token info for
function getPlayerToken(uint32 _playerTokenID) public view returns (
uint32 realWorldPlayerId,
uint32 serialNumber,
uint64 mintedTime,
uint128 mostRecentPrice) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
realWorldPlayerId = pt.realWorldPlayerId;
serialNumber = pt.serialNumber;
mostRecentPrice = pt.mostRecentPrice;
mintedTime = pt.mintedTime;
}
/// @dev Returns the realWorldPlayer MD5 ID for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerTokenForPlayerTokenId(uint32 _playerTokenID) public view returns (uint128 md5Token) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
md5Token = _rwp.md5Token;
}
/// @dev Returns the realWorldPlayer Metadata for a given playerTokenID
/// @param _playerTokenID - player token ID we are seeking the associated realWorldPlayer md5 for
function realWorldPlayerMetadataForPlayerTokenId(uint32 _playerTokenID) public view returns (string metadata) {
require(_playerTokenID < playerTokens.length);
PlayerToken storage pt = playerTokens[_playerTokenID];
RealWorldPlayer memory _rwp;
(_rwp.md5Token, _rwp.prevCommissionerSalePrice, _rwp.lastMintedTime, _rwp.mintedCount, _rwp.hasActiveCommissionerAuction, _rwp.mintingEnabled) = leagueRosterContract.realWorldPlayerFromIndex(pt.realWorldPlayerId);
metadata = leagueRosterContract.getMetadata(_rwp.md5Token);
}
/// --------------------------------------------------------------------------- ///
/// ------------------------- RESTRICTED FUNCTIONS ---------------------------- ///
/// --------------------------------------------------------------------------- ///
/// @dev Updates a particular realRealWorldPlayer. Note that the md5Token is immutable. Can only be
/// called by the CEO and is used in development stage only as it is only needed by our test suite.
/// @param _rosterIndex - Index into realWorldPlayers of the entry to change.
/// @param _prevCommissionerSalePrice - Average of the 2 most recent sale prices in commissioner auctions
/// @param _lastMintedTime - Time this real world player was last minted
/// @param _mintedCount - The number of playerTokens that have been minted for this player
/// @param _hasActiveCommissionerAuction - Whether or not there is an active commissioner auction for this player
/// @param _mintingEnabled - Denotes whether or not we should mint new playerTokens for this real world player
function updateRealWorldPlayer(uint32 _rosterIndex, uint128 _prevCommissionerSalePrice, uint64 _lastMintedTime, uint32 _mintedCount, bool _hasActiveCommissionerAuction, bool _mintingEnabled) public onlyCEO onlyUnderDevelopment {
require(leagueRosterContract != address(0));
leagueRosterContract.updateRealWorldPlayer(_rosterIndex, _prevCommissionerSalePrice, _lastMintedTime, _mintedCount, _hasActiveCommissionerAuction, _mintingEnabled);
}
} | @dev Checks if a given address is the current owner of a particular PlayerToken. @param _claimant the address we are validating against. @param _tokenId kitten id, only valid when > 0 | function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) {
return playerTokenToOwner[_tokenId] == _claimant;
}
| 6,426,276 | [
1,
4081,
309,
279,
864,
1758,
353,
326,
783,
3410,
434,
279,
6826,
19185,
1345,
18,
225,
389,
14784,
970,
326,
1758,
732,
854,
18075,
5314,
18,
225,
389,
2316,
548,
31758,
2253,
612,
16,
1338,
923,
1347,
405,
374,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
389,
995,
87,
12,
2867,
389,
14784,
970,
16,
2254,
5034,
389,
2316,
548,
13,
2713,
1476,
1135,
261,
6430,
13,
288,
203,
1377,
327,
7291,
1345,
774,
5541,
63,
67,
2316,
548,
65,
422,
389,
14784,
970,
31,
203,
225,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin/upgrades/contracts/Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: @aragon/court/contracts/lib/Checkpointing.sol
pragma solidity ^0.5.8;
/**
* @title Checkpointing - Library to handle a historic set of numeric values
*/
library Checkpointing {
uint256 private constant MAX_UINT192 = uint256(uint192(-1));
string private constant ERROR_VALUE_TOO_BIG = "CHECKPOINT_VALUE_TOO_BIG";
string private constant ERROR_CANNOT_ADD_PAST_VALUE = "CHECKPOINT_CANNOT_ADD_PAST_VALUE";
/**
* @dev To specify a value at a given point in time, we need to store two values:
* - `time`: unit-time value to denote the first time when a value was registered
* - `value`: a positive numeric value to registered at a given point in time
*
* Note that `time` does not need to refer necessarily to a timestamp value, any time unit could be used
* for it like block numbers, terms, etc.
*/
struct Checkpoint {
uint64 time;
uint192 value;
}
/**
* @dev A history simply denotes a list of checkpoints
*/
struct History {
Checkpoint[] history;
}
/**
* @dev Add a new value to a history for a given point in time. This function does not allow to add values previous
* to the latest registered value, if the value willing to add corresponds to the latest registered value, it
* will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function add(History storage self, uint64 _time, uint256 _value) internal {
require(_value <= MAX_UINT192, ERROR_VALUE_TOO_BIG);
_add192(self, _time, uint192(_value));
}
/**
* @dev Fetch the latest registered value of history, it will return zero if there was no value registered
* @param self Checkpoints history to be queried
*/
function getLast(History storage self) internal view returns (uint256) {
uint256 length = self.history.length;
if (length > 0) {
return uint256(self.history[length - 1].value);
}
return 0;
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time that is not known
* how recent it is beforehand. It will return zero if there is no registered value or if given time is
* previous to the first registered value.
* It uses a binary search.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function get(History storage self, uint64 _time) internal view returns (uint256) {
return _binarySearch(self, _time);
}
/**
* @dev Fetch the most recent registered past value of a history based on a given point in time. It will return zero
* if there is no registered value or if given time is previous to the first registered value.
* It uses a linear search starting from the end.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function getRecent(History storage self, uint64 _time) internal view returns (uint256) {
return _backwardsLinearSearch(self, _time);
}
/**
* @dev Private function to add a new value to a history for a given point in time. This function does not allow to
* add values previous to the latest registered value, if the value willing to add corresponds to the latest
* registered value, it will be updated.
* @param self Checkpoints history to be altered
* @param _time Point in time to register the given value
* @param _value Numeric value to be registered at the given point in time
*/
function _add192(History storage self, uint64 _time, uint192 _value) private {
uint256 length = self.history.length;
if (length == 0 || self.history[self.history.length - 1].time < _time) {
// If there was no value registered or the given point in time is after the latest registered value,
// we can insert it to the history directly.
self.history.push(Checkpoint(_time, _value));
} else {
// If the point in time given for the new value is not after the latest registered value, we must ensure
// we are only trying to update the latest value, otherwise we would be changing past data.
Checkpoint storage currentCheckpoint = self.history[length - 1];
require(_time == currentCheckpoint.time, ERROR_CANNOT_ADD_PAST_VALUE);
currentCheckpoint.value = _value;
}
}
/**
* @dev Private function to execute a backwards linear search to find the most recent registered past value of a
* history based on a given point in time. It will return zero if there is no registered value or if given time
* is previous to the first registered value. Note that this function will be more suitable when we already know
* that the time used to index the search is recent in the given history.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _backwardsLinearSearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
uint256 index = length - 1;
Checkpoint storage checkpoint = self.history[index];
while (index > 0 && checkpoint.time > _time) {
index--;
checkpoint = self.history[index];
}
return checkpoint.time > _time ? 0 : uint256(checkpoint.value);
}
/**
* @dev Private function execute a binary search to find the most recent registered past value of a history based on
* a given point in time. It will return zero if there is no registered value or if given time is previous to
* the first registered value. Note that this function will be more suitable when don't know how recent the
* time used to index may be.
* @param self Checkpoints history to be queried
* @param _time Point in time to query the most recent registered past value of
*/
function _binarySearch(History storage self, uint64 _time) private view returns (uint256) {
// If there was no value registered for the given history return simply zero
uint256 length = self.history.length;
if (length == 0) {
return 0;
}
// If the requested time is equal to or after the time of the latest registered value, return latest value
uint256 lastIndex = length - 1;
if (_time >= self.history[lastIndex].time) {
return uint256(self.history[lastIndex].value);
}
// If the requested time is previous to the first registered value, return zero to denote missing checkpoint
if (_time < self.history[0].time) {
return 0;
}
// Execute a binary search between the checkpointed times of the history
uint256 low = 0;
uint256 high = lastIndex;
while (high > low) {
// No need for SafeMath: for this to overflow array size should be ~2^255
uint256 mid = (high + low + 1) / 2;
Checkpoint storage checkpoint = self.history[mid];
uint64 midTime = checkpoint.time;
if (_time > midTime) {
low = mid;
} else if (_time < midTime) {
// No need for SafeMath: high > low >= 0 => high >= 1 => mid >= 1
high = mid - 1;
} else {
return uint256(checkpoint.value);
}
}
return uint256(self.history[low].value);
}
}
// File: @aragon/court/contracts/lib/os/Uint256Helpers.sol
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.8 and satisfy our linter rules
pragma solidity ^0.5.8;
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// File: contracts/InitializableV2.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* Wrapper around OpenZeppelin's Initializable contract.
* Exposes initialized state management to ensure logic contract functions cannot be called before initialization.
* This is needed because OZ's Initializable contract no longer exposes initialized state variable.
* https://github.com/OpenZeppelin/openzeppelin-sdk/blob/v2.8.0/packages/lib/contracts/Initializable.sol
*/
contract InitializableV2 is Initializable {
bool private isInitialized;
string private constant ERROR_NOT_INITIALIZED = "InitializableV2: Not initialized";
/**
* @notice wrapper function around parent contract Initializable's `initializable` modifier
* initializable modifier ensures this function can only be called once by each deployed child contract
* sets isInitialized flag to true to which is used by _requireIsInitialized()
*/
function initialize() public initializer {
isInitialized = true;
}
/**
* @notice Reverts transaction if isInitialized is false. Used by child contracts to ensure
* contract is initialized before functions can be called.
*/
function _requireIsInitialized() internal view {
require(isInitialized == true, ERROR_NOT_INITIALIZED);
}
/**
* @notice Exposes isInitialized bool var to child contracts with read-only access
*/
function _isInitialized() internal view returns (bool) {
return isInitialized;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts/registry/Registry.sol
pragma solidity ^0.5.0;
/**
* @title Central hub for Audius protocol. It stores all contract addresses to facilitate
* external access and enable version management.
*/
contract Registry is InitializableV2, Ownable {
using SafeMath for uint256;
/**
* @dev addressStorage mapping allows efficient lookup of current contract version
* addressStorageHistory maintains record of all contract versions
*/
mapping(bytes32 => address) private addressStorage;
mapping(bytes32 => address[]) private addressStorageHistory;
event ContractAdded(
bytes32 indexed _name,
address indexed _address
);
event ContractRemoved(
bytes32 indexed _name,
address indexed _address
);
event ContractUpgraded(
bytes32 indexed _name,
address indexed _oldAddress,
address indexed _newAddress
);
function initialize() public initializer {
/// @notice Ownable.initialize(address _sender) sets contract owner to _sender.
Ownable.initialize(msg.sender);
InitializableV2.initialize();
}
// ========================================= Setters =========================================
/**
* @notice addContract registers contract name to address mapping under given registry key
* @param _name - registry key that will be used for lookups
* @param _address - address of contract
*/
function addContract(bytes32 _name, address _address) external onlyOwner {
_requireIsInitialized();
require(
addressStorage[_name] == address(0x00),
"Registry: Contract already registered with given name."
);
require(
_address != address(0x00),
"Registry: Cannot register zero address."
);
setAddress(_name, _address);
emit ContractAdded(_name, _address);
}
/**
* @notice removes contract address registered under given registry key
* @param _name - registry key for lookup
*/
function removeContract(bytes32 _name) external onlyOwner {
_requireIsInitialized();
address contractAddress = addressStorage[_name];
require(
contractAddress != address(0x00),
"Registry: Cannot remove - no contract registered with given _name."
);
setAddress(_name, address(0x00));
emit ContractRemoved(_name, contractAddress);
}
/**
* @notice replaces contract address registered under given key with provided address
* @param _name - registry key for lookup
* @param _newAddress - new contract address to register under given key
*/
function upgradeContract(bytes32 _name, address _newAddress) external onlyOwner {
_requireIsInitialized();
address oldAddress = addressStorage[_name];
require(
oldAddress != address(0x00),
"Registry: Cannot upgrade - no contract registered with given _name."
);
require(
_newAddress != address(0x00),
"Registry: Cannot upgrade - cannot register zero address."
);
setAddress(_name, _newAddress);
emit ContractUpgraded(_name, oldAddress, _newAddress);
}
// ========================================= Getters =========================================
/**
* @notice returns contract address registered under given registry key
* @param _name - registry key for lookup
* @return contractAddr - address of contract registered under given registry key
*/
function getContract(bytes32 _name) external view returns (address contractAddr) {
_requireIsInitialized();
return addressStorage[_name];
}
/// @notice overloaded getContract to return explicit version of contract
function getContract(bytes32 _name, uint256 _version) external view
returns (address contractAddr)
{
_requireIsInitialized();
// array length for key implies version number
require(
_version <= addressStorageHistory[_name].length,
"Registry: Index out of range _version."
);
return addressStorageHistory[_name][_version.sub(1)];
}
/**
* @notice Returns the number of versions for a contract key
* @param _name - registry key for lookup
* @return number of contract versions
*/
function getContractVersionCount(bytes32 _name) external view returns (uint256) {
_requireIsInitialized();
return addressStorageHistory[_name].length;
}
// ========================================= Private functions =========================================
/**
* @param _key the key for the contract address
* @param _value the contract address
*/
function setAddress(bytes32 _key, address _value) private {
// main map for cheap lookup
addressStorage[_key] = _value;
// keep track of contract address history
addressStorageHistory[_key].push(_value);
}
}
// File: contracts/Governance.sol
pragma solidity ^0.5.0;
contract Governance is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"Governance: Only callable by self"
);
string private constant ERROR_INVALID_VOTING_PERIOD = (
"Governance: Requires non-zero _votingPeriod"
);
string private constant ERROR_INVALID_REGISTRY = (
"Governance: Requires non-zero _registryAddress"
);
string private constant ERROR_INVALID_VOTING_QUORUM = (
"Governance: Requires _votingQuorumPercent between 1 & 100"
);
/**
* @notice Address and contract instance of Audius Registry. Used to ensure this contract
* can only govern contracts that are registered in the Audius Registry.
*/
Registry private registry;
/// @notice Address of Audius staking contract, used to permission Governance method calls
address private stakingAddress;
/// @notice Address of Audius ServiceProvider contract, used to permission Governance method calls
address private serviceProviderFactoryAddress;
/// @notice Address of Audius DelegateManager contract, used to permission Governance method calls
address private delegateManagerAddress;
/// @notice Period in blocks for which a governance proposal is open for voting
uint256 private votingPeriod;
/// @notice Number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
uint256 private executionDelay;
/// @notice Required minimum percentage of total stake to have voted to consider a proposal valid
/// Percentaged stored as a uint256 between 0 & 100
/// Calculated as: 100 * sum of voter stakes / total staked in Staking (at proposal submission block)
uint256 private votingQuorumPercent;
/// @notice Max number of InProgress proposals possible at once
/// @dev uint16 gives max possible value of 65,535
uint16 private maxInProgressProposals;
/**
* @notice Address of account that has special Governance permissions. Can veto proposals
* and execute transactions directly on contracts.
*/
address private guardianAddress;
/***** Enums *****/
/**
* @notice All Proposal Outcome states.
* InProgress - Proposal is active and can be voted on.
* Rejected - Proposal votingPeriod has closed and vote failed to pass. Proposal will not be executed.
* ApprovedExecuted - Proposal votingPeriod has closed and vote passed. Proposal was successfully executed.
* QuorumNotMet - Proposal votingPeriod has closed and votingQuorumPercent was not met. Proposal will not be executed.
* ApprovedExecutionFailed - Proposal vote passed, but transaction execution failed.
* Evaluating - Proposal vote passed, and evaluateProposalOutcome function is currently running.
* This status is transiently used inside that function to prevent re-entrancy.
* Vetoed - Proposal was vetoed by Guardian.
* TargetContractAddressChanged - Proposal considered invalid since target contract address changed
* TargetContractCodeHashChanged - Proposal considered invalid since code has at target contract address has changed
*/
enum Outcome {
InProgress,
Rejected,
ApprovedExecuted,
QuorumNotMet,
ApprovedExecutionFailed,
Evaluating,
Vetoed,
TargetContractAddressChanged,
TargetContractCodeHashChanged
}
/**
* @notice All Proposal Vote states for a voter.
* None - The default state, for any account that has not previously voted on this Proposal.
* No - The account voted No on this Proposal.
* Yes - The account voted Yes on this Proposal.
* @dev Enum values map to uints, so first value in Enum always is 0.
*/
enum Vote {None, No, Yes}
struct Proposal {
uint256 proposalId;
address proposer;
uint256 submissionBlockNumber;
bytes32 targetContractRegistryKey;
address targetContractAddress;
uint256 callValue;
string functionSignature;
bytes callData;
Outcome outcome;
uint256 voteMagnitudeYes;
uint256 voteMagnitudeNo;
uint256 numVotes;
mapping(address => Vote) votes;
mapping(address => uint256) voteMagnitudes;
bytes32 contractHash;
}
/***** Proposal storage *****/
/// @notice ID of most recently created proposal. Ids are monotonically increasing and 1-indexed.
uint256 lastProposalId = 0;
/// @notice mapping of proposalId to Proposal struct with all proposal state
mapping(uint256 => Proposal) proposals;
/// @notice array of proposals with InProgress state
uint256[] inProgressProposals;
/***** Events *****/
event ProposalSubmitted(
uint256 indexed _proposalId,
address indexed _proposer,
string _name,
string _description
);
event ProposalVoteSubmitted(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake
);
event ProposalVoteUpdated(
uint256 indexed _proposalId,
address indexed _voter,
Vote indexed _vote,
uint256 _voterStake,
Vote _previousVote
);
event ProposalOutcomeEvaluated(
uint256 indexed _proposalId,
Outcome indexed _outcome,
uint256 _voteMagnitudeYes,
uint256 _voteMagnitudeNo,
uint256 _numVotes
);
event ProposalTransactionExecuted(
uint256 indexed _proposalId,
bool indexed _success,
bytes _returnData
);
event GuardianTransactionExecuted(
address indexed _targetContractAddress,
uint256 _callValue,
string indexed _functionSignature,
bytes indexed _callData,
bytes _returnData
);
event ProposalVetoed(uint256 indexed _proposalId);
event RegistryAddressUpdated(address indexed _newRegistryAddress);
event GuardianshipTransferred(address indexed _newGuardianAddress);
event VotingPeriodUpdated(uint256 indexed _newVotingPeriod);
event ExecutionDelayUpdated(uint256 indexed _newExecutionDelay);
event VotingQuorumPercentUpdated(uint256 indexed _newVotingQuorumPercent);
event MaxInProgressProposalsUpdated(uint256 indexed _newMaxInProgressProposals);
/**
* @notice Initialize the Governance contract
* @dev _votingPeriod <= DelegateManager.undelegateLockupDuration
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @param _registryAddress - address of the registry proxy contract
* @param _votingPeriod - period in blocks for which a governance proposal is open for voting
* @param _executionDelay - number of blocks that must pass after votingPeriod has expired before proposal can be evaluated/executed
* @param _votingQuorumPercent - required minimum percentage of total stake to have voted to consider a proposal valid
* @param _maxInProgressProposals - max number of InProgress proposals possible at once
* @param _guardianAddress - address of account that has special Governance permissions
*/
function initialize(
address _registryAddress,
uint256 _votingPeriod,
uint256 _executionDelay,
uint256 _votingQuorumPercent,
uint16 _maxInProgressProposals,
address _guardianAddress
) public initializer {
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
// executionDelay does not have to be non-zero
executionDelay = _executionDelay;
require(
_maxInProgressProposals > 0,
"Governance: Requires non-zero _maxInProgressProposals"
);
maxInProgressProposals = _maxInProgressProposals;
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
require(
_guardianAddress != address(0x00),
"Governance: Requires non-zero _guardianAddress"
);
guardianAddress = _guardianAddress; //Guardian address becomes the only party
InitializableV2.initialize();
}
// ========================================= Governance Actions =========================================
/**
* @notice Submit a proposal for vote. Only callable by addresses with non-zero total active stake.
* total active stake = total active deployer stake + total active delegator stake
*
* @dev _name and _description length is not enforced since they aren't stored on-chain and only event emitted
*
* @param _targetContractRegistryKey - Registry key for the contract concerning this proposal
* @param _callValue - amount of wei to pass with function call if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
* @param _name - Text name of proposal to be emitted in event
* @param _description - Text description of proposal to be emitted in event
*
* @return - ID of new proposal
*/
function submitProposal(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData,
string calldata _name,
string calldata _description
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
address proposer = msg.sender;
// Require all InProgress proposals that can be evaluated have been evaluated before new proposal submission
require(
this.inProgressProposalsAreUpToDate(),
"Governance: Cannot submit new proposal until all evaluatable InProgress proposals are evaluated."
);
// Require new proposal submission would not push number of InProgress proposals over max number
require(
inProgressProposals.length < maxInProgressProposals,
"Governance: Number of InProgress proposals already at max. Please evaluate if possible, or wait for current proposals' votingPeriods to expire."
);
// Require proposer has non-zero total active stake or is guardian address
require(
_calculateAddressActiveStake(proposer) > 0 || proposer == guardianAddress,
"Governance: Proposer must be address with non-zero total active stake or be guardianAddress."
);
// Require _targetContractRegistryKey points to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
// Require non-zero description length
require(bytes(_description).length > 0, "Governance: _description length must be > 0");
// Require non-zero name length
require(bytes(_name).length > 0, "Governance: _name length must be > 0");
// set proposalId
uint256 newProposalId = lastProposalId.add(1);
// Store new Proposal obj in proposals mapping
proposals[newProposalId] = Proposal({
proposalId: newProposalId,
proposer: proposer,
submissionBlockNumber: block.number,
targetContractRegistryKey: _targetContractRegistryKey,
targetContractAddress: targetContractAddress,
callValue: _callValue,
functionSignature: _functionSignature,
callData: _callData,
outcome: Outcome.InProgress,
voteMagnitudeYes: 0,
voteMagnitudeNo: 0,
numVotes: 0,
contractHash: _getCodeHash(targetContractAddress)
/* votes: mappings are auto-initialized to default state */
/* voteMagnitudes: mappings are auto-initialized to default state */
});
// Append new proposalId to inProgressProposals array
inProgressProposals.push(newProposalId);
emit ProposalSubmitted(
newProposalId,
proposer,
_name,
_description
);
lastProposalId = newProposalId;
return newProposalId;
}
/**
* @notice Vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function submitVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Require voter has non-zero total active stake
uint256 voterActiveStake = _calculateAddressActiveStake(voter);
require(
voterActiveStake > 0,
"Governance: Voter must be address with non-zero total active stake."
);
// Require previous vote is None
require(
proposals[_proposalId].votes[voter] == Vote.None,
"Governance: To update previous vote, call updateVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record vote
proposals[_proposalId].votes[voter] = _vote;
// Record voteMagnitude for voter
proposals[_proposalId].voteMagnitudes[voter] = voterActiveStake;
// Update proposal cumulative vote magnitudes
if (_vote == Vote.Yes) {
_increaseVoteMagnitudeYes(_proposalId, voterActiveStake);
} else {
_increaseVoteMagnitudeNo(_proposalId, voterActiveStake);
}
// Increment proposal numVotes
proposals[_proposalId].numVotes = proposals[_proposalId].numVotes.add(1);
emit ProposalVoteSubmitted(
_proposalId,
voter,
_vote,
voterActiveStake
);
}
/**
* @notice Update previous vote on an active Proposal. Only callable by addresses with non-zero active stake.
* @param _proposalId - id of the proposal this vote is for
* @param _vote - can be either {Yes, No} from Vote enum. No other values allowed
*/
function updateVote(uint256 _proposalId, Vote _vote) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
address voter = msg.sender;
// Require proposal votingPeriod is still active
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod);
require(
block.number > submissionBlockNumber && block.number <= endBlockNumber,
"Governance: Proposal votingPeriod has ended"
);
// Retrieve previous vote
Vote previousVote = proposals[_proposalId].votes[voter];
// Require previous vote is not None
require(
previousVote != Vote.None,
"Governance: To submit new vote, call submitVote()"
);
// Require vote is either Yes or No
require(
_vote == Vote.Yes || _vote == Vote.No,
"Governance: Can only submit a Yes or No vote"
);
// Record updated vote
proposals[_proposalId].votes[voter] = _vote;
// Update vote magnitudes, using vote magnitude from when previous vote was submitted
uint256 voteMagnitude = proposals[_proposalId].voteMagnitudes[voter];
if (previousVote == Vote.Yes && _vote == Vote.No) {
_decreaseVoteMagnitudeYes(_proposalId, voteMagnitude);
_increaseVoteMagnitudeNo(_proposalId, voteMagnitude);
} else if (previousVote == Vote.No && _vote == Vote.Yes) {
_decreaseVoteMagnitudeNo(_proposalId, voteMagnitude);
_increaseVoteMagnitudeYes(_proposalId, voteMagnitude);
}
// If _vote == previousVote, no changes needed to vote magnitudes.
// Do not update numVotes
emit ProposalVoteUpdated(
_proposalId,
voter,
_vote,
voteMagnitude,
previousVote
);
}
/**
* @notice Once the voting period + executionDelay for a proposal has ended, evaluate the outcome and
* execute the proposal if voting quorum met & vote passes.
* To pass, stake-weighted vote must be > 50% Yes.
* @dev Requires that caller is an active staker at the time the proposal is created
* @param _proposalId - id of the proposal
* @return Outcome of proposal evaluation
*/
function evaluateProposalOutcome(uint256 _proposalId)
external returns (Outcome)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireValidProposalId(_proposalId);
// Require proposal has not already been evaluated.
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Can only evaluate InProgress proposal."
);
// Re-entrancy should not be possible here since this switches the status of the
// proposal to 'Evaluating' so it should fail the status is 'InProgress' check
proposals[_proposalId].outcome = Outcome.Evaluating;
// Require proposal votingPeriod + executionDelay have ended.
uint256 submissionBlockNumber = proposals[_proposalId].submissionBlockNumber;
uint256 endBlockNumber = submissionBlockNumber.add(votingPeriod).add(executionDelay);
require(
block.number > endBlockNumber,
"Governance: Proposal votingPeriod & executionDelay must end before evaluation."
);
address targetContractAddress = registry.getContract(
proposals[_proposalId].targetContractRegistryKey
);
Outcome outcome;
// target contract address changed -> close proposal without execution.
if (targetContractAddress != proposals[_proposalId].targetContractAddress) {
outcome = Outcome.TargetContractAddressChanged;
}
// target contract code hash changed -> close proposal without execution.
else if (_getCodeHash(targetContractAddress) != proposals[_proposalId].contractHash) {
outcome = Outcome.TargetContractCodeHashChanged;
}
// voting quorum not met -> close proposal without execution.
else if (_quorumMet(proposals[_proposalId], Staking(stakingAddress)) == false) {
outcome = Outcome.QuorumNotMet;
}
// votingQuorumPercent met & vote passed -> execute proposed transaction & close proposal.
else if (
proposals[_proposalId].voteMagnitudeYes > proposals[_proposalId].voteMagnitudeNo
) {
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
proposals[_proposalId].callValue,
proposals[_proposalId].functionSignature,
proposals[_proposalId].callData
);
emit ProposalTransactionExecuted(
_proposalId,
success,
returnData
);
// Proposal outcome depends on success of transaction execution.
if (success) {
outcome = Outcome.ApprovedExecuted;
} else {
outcome = Outcome.ApprovedExecutionFailed;
}
}
// votingQuorumPercent met & vote did not pass -> close proposal without transaction execution.
else {
outcome = Outcome.Rejected;
}
// This records the final outcome in the proposals mapping
proposals[_proposalId].outcome = outcome;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalOutcomeEvaluated(
_proposalId,
outcome,
proposals[_proposalId].voteMagnitudeYes,
proposals[_proposalId].voteMagnitudeNo,
proposals[_proposalId].numVotes
);
return outcome;
}
/**
* @notice Action limited to the guardian address that can veto a proposal
* @param _proposalId - id of the proposal
*/
function vetoProposal(uint256 _proposalId) external {
_requireIsInitialized();
_requireValidProposalId(_proposalId);
require(
msg.sender == guardianAddress,
"Governance: Only guardian can veto proposals."
);
require(
proposals[_proposalId].outcome == Outcome.InProgress,
"Governance: Cannot veto inactive proposal."
);
proposals[_proposalId].outcome = Outcome.Vetoed;
// Remove from inProgressProposals array
_removeFromInProgressProposals(_proposalId);
emit ProposalVetoed(_proposalId);
}
// ========================================= Config Setters =========================================
/**
* @notice Set the Staking address
* @dev Only callable by self via _executeTransaction
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_stakingAddress != address(0x00), "Governance: Requires non-zero _stakingAddress");
stakingAddress = _stakingAddress;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by self via _executeTransaction
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_serviceProviderFactoryAddress != address(0x00),
"Governance: Requires non-zero _serviceProviderFactoryAddress"
);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by self via _executeTransaction
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_delegateManagerAddress != address(0x00),
"Governance: Requires non-zero _delegateManagerAddress"
);
delegateManagerAddress = _delegateManagerAddress;
}
/**
* @notice Set the voting period for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingPeriod - new voting period
*/
function setVotingPeriod(uint256 _votingPeriod) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_votingPeriod > 0, ERROR_INVALID_VOTING_PERIOD);
votingPeriod = _votingPeriod;
emit VotingPeriodUpdated(_votingPeriod);
}
/**
* @notice Set the voting quorum percentage for a Governance proposal
* @dev Only callable by self via _executeTransaction
* @param _votingQuorumPercent - new voting period
*/
function setVotingQuorumPercent(uint256 _votingQuorumPercent) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_votingQuorumPercent > 0 && _votingQuorumPercent <= 100,
ERROR_INVALID_VOTING_QUORUM
);
votingQuorumPercent = _votingQuorumPercent;
emit VotingQuorumPercentUpdated(_votingQuorumPercent);
}
/**
* @notice Set the Registry address
* @dev Only callable by self via _executeTransaction
* @param _registryAddress - address for new Registry contract
*/
function setRegistryAddress(address _registryAddress) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(_registryAddress != address(0x00), ERROR_INVALID_REGISTRY);
registry = Registry(_registryAddress);
emit RegistryAddressUpdated(_registryAddress);
}
/**
* @notice Set the max number of concurrent InProgress proposals
* @dev Only callable by self via _executeTransaction
* @param _newMaxInProgressProposals - new value for maxInProgressProposals
*/
function setMaxInProgressProposals(uint16 _newMaxInProgressProposals) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
require(
_newMaxInProgressProposals > 0,
"Governance: Requires non-zero _newMaxInProgressProposals"
);
maxInProgressProposals = _newMaxInProgressProposals;
emit MaxInProgressProposalsUpdated(_newMaxInProgressProposals);
}
/**
* @notice Set the execution delay for a proposal
* @dev Only callable by self via _executeTransaction
* @param _newExecutionDelay - new value for executionDelay
*/
function setExecutionDelay(uint256 _newExecutionDelay) external {
_requireIsInitialized();
require(msg.sender == address(this), ERROR_ONLY_GOVERNANCE);
// executionDelay does not have to be non-zero
executionDelay = _newExecutionDelay;
emit ExecutionDelayUpdated(_newExecutionDelay);
}
// ========================================= Guardian Actions =========================================
/**
* @notice Allows the guardianAddress to execute protocol actions
* @param _targetContractRegistryKey - key in registry of target contract
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function guardianExecuteTransaction(
bytes32 _targetContractRegistryKey,
uint256 _callValue,
string calldata _functionSignature,
bytes calldata _callData
) external
{
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
// _targetContractRegistryKey must point to a valid registered contract
address targetContractAddress = registry.getContract(_targetContractRegistryKey);
require(
targetContractAddress != address(0x00),
"Governance: _targetContractRegistryKey must point to valid registered contract"
);
// Signature cannot be empty
require(
bytes(_functionSignature).length != 0,
"Governance: _functionSignature cannot be empty."
);
(bool success, bytes memory returnData) = _executeTransaction(
targetContractAddress,
_callValue,
_functionSignature,
_callData
);
require(success, "Governance: Transaction failed.");
emit GuardianTransactionExecuted(
targetContractAddress,
_callValue,
_functionSignature,
_callData,
returnData
);
}
/**
* @notice Change the guardian address
* @dev Only callable by current guardian
* @param _newGuardianAddress - new guardian address
*/
function transferGuardianship(address _newGuardianAddress) external {
_requireIsInitialized();
require(
msg.sender == guardianAddress,
"Governance: Only guardian."
);
guardianAddress = _newGuardianAddress;
emit GuardianshipTransferred(_newGuardianAddress);
}
// ========================================= Getter Functions =========================================
/**
* @notice Get proposal information by proposal Id
* @param _proposalId - id of proposal
*/
function getProposalById(uint256 _proposalId)
external view returns (
uint256 proposalId,
address proposer,
uint256 submissionBlockNumber,
bytes32 targetContractRegistryKey,
address targetContractAddress,
uint256 callValue,
string memory functionSignature,
bytes memory callData,
Outcome outcome,
uint256 voteMagnitudeYes,
uint256 voteMagnitudeNo,
uint256 numVotes
)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
Proposal memory proposal = proposals[_proposalId];
return (
proposal.proposalId,
proposal.proposer,
proposal.submissionBlockNumber,
proposal.targetContractRegistryKey,
proposal.targetContractAddress,
proposal.callValue,
proposal.functionSignature,
proposal.callData,
proposal.outcome,
proposal.voteMagnitudeYes,
proposal.voteMagnitudeNo,
proposal.numVotes
/** @notice - votes mapping cannot be returned by external function */
/** @notice - voteMagnitudes mapping cannot be returned by external function */
/** @notice - returning contractHash leads to stack too deep compiler error, see getProposalTargetContractHash() */
);
}
/**
* @notice Get proposal target contract hash by proposalId
* @dev This is a separate function because the getProposalById returns too many
variables already and by adding more, you get the error
`InternalCompilerError: Stack too deep, try using fewer variables`
* @param _proposalId - id of proposal
*/
function getProposalTargetContractHash(uint256 _proposalId)
external view returns (bytes32)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (proposals[_proposalId].contractHash);
}
/**
* @notice Get vote direction and vote magnitude for a given proposal and voter
* @param _proposalId - id of the proposal
* @param _voter - address of the voter we want to check
* @return returns vote direction and magnitude if valid vote, else default values
*/
function getVoteInfoByProposalAndVoter(uint256 _proposalId, address _voter)
external view returns (Vote vote, uint256 voteMagnitude)
{
_requireIsInitialized();
_requireValidProposalId(_proposalId);
return (
proposals[_proposalId].votes[_voter],
proposals[_proposalId].voteMagnitudes[_voter]
);
}
/// @notice Get the contract Guardian address
function getGuardianAddress() external view returns (address) {
_requireIsInitialized();
return guardianAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the contract voting period
function getVotingPeriod() external view returns (uint256) {
_requireIsInitialized();
return votingPeriod;
}
/// @notice Get the contract voting quorum percent
function getVotingQuorumPercent() external view returns (uint256) {
_requireIsInitialized();
return votingQuorumPercent;
}
/// @notice Get the registry address
function getRegistryAddress() external view returns (address) {
_requireIsInitialized();
return address(registry);
}
/// @notice Used to check if is governance contract before setting governance address in other contracts
function isGovernanceAddress() external pure returns (bool) {
return true;
}
/// @notice Get the max number of concurrent InProgress proposals
function getMaxInProgressProposals() external view returns (uint16) {
_requireIsInitialized();
return maxInProgressProposals;
}
/// @notice Get the proposal execution delay
function getExecutionDelay() external view returns (uint256) {
_requireIsInitialized();
return executionDelay;
}
/// @notice Get the array of all InProgress proposal Ids
function getInProgressProposals() external view returns (uint256[] memory) {
_requireIsInitialized();
return inProgressProposals;
}
/**
* @notice Returns false if any proposals in inProgressProposals array are evaluatable
* Evaluatable = proposals with closed votingPeriod
* @dev Is public since its called internally in `submitProposal()` as well as externally in UI
*/
function inProgressProposalsAreUpToDate() external view returns (bool) {
_requireIsInitialized();
// compare current block number against endBlockNumber of each proposal
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (
block.number >
(proposals[inProgressProposals[i]].submissionBlockNumber).add(votingPeriod).add(executionDelay)
) {
return false;
}
}
return true;
}
// ========================================= Internal Functions =========================================
/**
* @notice Execute a transaction attached to a governance proposal
* @dev We are aware of both potential re-entrancy issues and the risks associated with low-level solidity
* function calls here, but have chosen to keep this code with those issues in mind. All governance
* proposals go through a voting process, and all will be reviewed carefully to ensure that they
* adhere to the expected behaviors of this call - but adding restrictions here would limit the ability
* of the governance system to do required work in a generic way.
* @param _targetContractAddress - address of registry proxy contract to execute transaction on
* @param _callValue - amount of wei if a token transfer is involved
* @param _functionSignature - function signature of the function to be executed if proposal is successful
* @param _callData - encoded value(s) to call function with if proposal is successful
*/
function _executeTransaction(
address _targetContractAddress,
uint256 _callValue,
string memory _functionSignature,
bytes memory _callData
) internal returns (bool success, bytes memory returnData)
{
bytes memory encodedCallData = abi.encodePacked(
bytes4(keccak256(bytes(_functionSignature))),
_callData
);
(success, returnData) = (
// solium-disable-next-line security/no-call-value
_targetContractAddress.call.value(_callValue)(encodedCallData)
);
return (success, returnData);
}
function _increaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.add(_voterStake)
);
}
function _increaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.add(_voterStake)
);
}
function _decreaseVoteMagnitudeYes(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeYes = (
proposals[_proposalId].voteMagnitudeYes.sub(_voterStake)
);
}
function _decreaseVoteMagnitudeNo(uint256 _proposalId, uint256 _voterStake) internal {
proposals[_proposalId].voteMagnitudeNo = (
proposals[_proposalId].voteMagnitudeNo.sub(_voterStake)
);
}
/**
* @dev Can make O(1) by storing index pointer in proposals mapping.
* Requires inProgressProposals to be 1-indexed, since all proposals that are not present
* will have pointer set to 0.
*/
function _removeFromInProgressProposals(uint256 _proposalId) internal {
uint256 index = 0;
for (uint256 i = 0; i < inProgressProposals.length; i++) {
if (inProgressProposals[i] == _proposalId) {
index = i;
break;
}
}
// Swap proposalId to end of array + pop (deletes last elem + decrements array length)
inProgressProposals[index] = inProgressProposals[inProgressProposals.length - 1];
inProgressProposals.pop();
}
/**
* @notice Returns true if voting quorum percentage met for proposal, else false.
* @dev Quorum is met if total voteMagnitude * 100 / total active stake in Staking
* @dev Eventual multiplication overflow:
* (proposal.voteMagnitudeYes + proposal.voteMagnitudeNo), with 100% staking participation,
* can sum to at most the entire token supply of 10^27
* With 7% annual token supply inflation, multiplication can overflow ~1635 years at the earliest:
* log(2^256/(10^27*100))/log(1.07) ~= 1635
*
* @dev Note that quorum is evaluated based on total staked at proposal submission
* not total staked at proposal evaluation, this is expected behavior
*/
function _quorumMet(Proposal memory proposal, Staking stakingContract)
internal view returns (bool)
{
uint256 participation = (
(proposal.voteMagnitudeYes + proposal.voteMagnitudeNo)
.mul(100)
.div(stakingContract.totalStakedAt(proposal.submissionBlockNumber))
);
return participation >= votingQuorumPercent;
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"Governance: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Governance: serviceProviderFactoryAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Governance: delegateManagerAddress is not set"
);
}
function _requireValidProposalId(uint256 _proposalId) private view {
require(
_proposalId <= lastProposalId && _proposalId > 0,
"Governance: Must provide valid non-zero _proposalId"
);
}
/**
* Calculates and returns active stake for address
*
* Active stake = (active deployer stake + active delegator stake)
* active deployer stake = (direct deployer stake - locked deployer stake)
* locked deployer stake = amount of pending decreaseStakeRequest for address
* active delegator stake = (total delegator stake - locked delegator stake)
* locked delegator stake = amount of pending undelegateRequest for address
*/
function _calculateAddressActiveStake(address _address) private view returns (uint256) {
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
DelegateManagerV2 delegateManager = DelegateManagerV2(delegateManagerAddress);
// Amount directly staked by address, if any, in ServiceProviderFactory
(uint256 directDeployerStake,,,,,) = spFactory.getServiceProviderDetails(_address);
// Amount of pending decreasedStakeRequest for address, if any, in ServiceProviderFactory
(uint256 lockedDeployerStake,) = spFactory.getPendingDecreaseStakeRequest(_address);
// active deployer stake = (direct deployer stake - locked deployer stake)
uint256 activeDeployerStake = directDeployerStake.sub(lockedDeployerStake);
// Total amount delegated by address, if any, in DelegateManager
uint256 totalDelegatorStake = delegateManager.getTotalDelegatorStake(_address);
// Amount of pending undelegateRequest for address, if any, in DelegateManager
(,uint256 lockedDelegatorStake, ) = delegateManager.getPendingUndelegateRequest(_address);
// active delegator stake = (total delegator stake - locked delegator stake)
uint256 activeDelegatorStake = totalDelegatorStake.sub(lockedDelegatorStake);
// activeStake = (activeDeployerStake + activeDelegatorStake)
uint256 activeStake = activeDeployerStake.add(activeDelegatorStake);
return activeStake;
}
// solium-disable security/no-inline-assembly
/**
* @notice Helper function to generate the code hash for a contract address
* @return contract code hash
*/
function _getCodeHash(address _contract) private view returns (bytes32) {
bytes32 contractHash;
assembly {
contractHash := extcodehash(_contract)
}
return contractHash;
}
}
// File: contracts/Staking.sol
pragma solidity ^0.5.0;
contract Staking is InitializableV2 {
using SafeMath for uint256;
using Uint256Helpers for uint256;
using Checkpointing for Checkpointing.History;
using SafeERC20 for ERC20;
string private constant ERROR_TOKEN_NOT_CONTRACT = "Staking: Staking token is not a contract";
string private constant ERROR_AMOUNT_ZERO = "Staking: Zero amount not allowed";
string private constant ERROR_ONLY_GOVERNANCE = "Staking: Only governance";
string private constant ERROR_ONLY_DELEGATE_MANAGER = (
"Staking: Only callable from DelegateManager"
);
string private constant ERROR_ONLY_SERVICE_PROVIDER_FACTORY = (
"Staking: Only callable from ServiceProviderFactory"
);
address private governanceAddress;
address private claimsManagerAddress;
address private delegateManagerAddress;
address private serviceProviderFactoryAddress;
/// @dev stores the history of staking and claims for a given address
struct Account {
Checkpointing.History stakedHistory;
Checkpointing.History claimHistory;
}
/// @dev ERC-20 token that will be used to stake with
ERC20 internal stakingToken;
/// @dev maps addresses to staking and claims history
mapping (address => Account) internal accounts;
/// @dev total staked tokens at a given block
Checkpointing.History internal totalStakedHistory;
event Staked(address indexed user, uint256 amount, uint256 total);
event Unstaked(address indexed user, uint256 amount, uint256 total);
event Slashed(address indexed user, uint256 amount, uint256 total);
/**
* @notice Function to initialize the contract
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @param _tokenAddress - address of ERC20 token that will be staked
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
require(Address.isContract(_tokenAddress), ERROR_TOKEN_NOT_CONTRACT);
stakingToken = ERC20(_tokenAddress);
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
/**
* @notice Set the ClaimsManaager address
* @dev Only callable by Governance address
* @param _claimsManager - address for new ClaimsManaager contract
*/
function setClaimsManagerAddress(address _claimsManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManager;
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManager - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManager) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManager;
}
/* External functions */
/**
* @notice Funds `_amount` of tokens from ClaimsManager to target account
* @param _amount - amount of rewards to add to stake
* @param _stakerAccount - address of staker
*/
function stakeRewards(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress,
"Staking: Only callable from ClaimsManager"
);
_stakeFor(_stakerAccount, msg.sender, _amount);
this.updateClaimHistory(_amount, _stakerAccount);
}
/**
* @notice Update claim history by adding an event to the claim history
* @param _amount - amount to add to claim history
* @param _stakerAccount - address of staker
*/
function updateClaimHistory(uint256 _amount, address _stakerAccount) external {
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
msg.sender == claimsManagerAddress || msg.sender == address(this),
"Staking: Only callable from ClaimsManager or Staking.sol"
);
// Update claim history even if no value claimed
accounts[_stakerAccount].claimHistory.add(block.number.toUint64(), _amount);
}
/**
* @notice Slashes `_amount` tokens from _slashAddress
* @dev Callable from DelegateManager
* @param _amount - Number of tokens slashed
* @param _slashAddress - Address being slashed
*/
function slash(
uint256 _amount,
address _slashAddress
) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
// Burn slashed tokens from account
_burnFor(_slashAddress, _amount);
emit Slashed(
_slashAddress,
_amount,
totalStakedFor(_slashAddress)
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from _accountAddress, and assigns them to `_accountAddress`
* @param _accountAddress - The final staker of the tokens
* @param _amount - Number of tokens staked
*/
function stakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_stakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Unstakes `_amount` tokens, returning them to the desired account.
* @param _accountAddress - Account unstaked for, and token recipient
* @param _amount - Number of tokens staked
*/
function unstakeFor(
address _accountAddress,
uint256 _amount
) external
{
_requireIsInitialized();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == serviceProviderFactoryAddress,
ERROR_ONLY_SERVICE_PROVIDER_FACTORY
);
_unstakeFor(
_accountAddress,
_accountAddress,
_amount
);
}
/**
* @notice Stakes `_amount` tokens, transferring them from `_delegatorAddress` to `_accountAddress`,
only callable by DelegateManager
* @param _accountAddress - The final staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens staked
*/
function delegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_stakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Unstakes '_amount` tokens, transferring them from `_accountAddress` to `_delegatorAddress`,
only callable by DelegateManager
* @param _accountAddress - The staker of the tokens
* @param _delegatorAddress - Address from which to transfer tokens
* @param _amount - Number of tokens unstaked
*/
function undelegateStakeFor(
address _accountAddress,
address _delegatorAddress,
uint256 _amount
) external {
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
ERROR_ONLY_DELEGATE_MANAGER
);
_unstakeFor(
_accountAddress,
_delegatorAddress,
_amount);
}
/**
* @notice Get the token used by the contract for staking and locking
* @return The token used by the contract for staking and locking
*/
function token() external view returns (address) {
_requireIsInitialized();
return address(stakingToken);
}
/**
* @notice Check whether it supports history of stakes
* @return Always true
*/
function supportsHistory() external view returns (bool) {
_requireIsInitialized();
return true;
}
/**
* @notice Get last time `_accountAddress` modified its staked balance
* @param _accountAddress - Account requesting for
* @return Last block number when account's balance was modified
*/
function lastStakedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].stakedHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].stakedHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get last time `_accountAddress` claimed a staking reward
* @param _accountAddress - Account requesting for
* @return Last block number when claim requested
*/
function lastClaimedFor(address _accountAddress) external view returns (uint256) {
_requireIsInitialized();
uint256 length = accounts[_accountAddress].claimHistory.history.length;
if (length > 0) {
return uint256(accounts[_accountAddress].claimHistory.history[length - 1].time);
}
return 0;
}
/**
* @notice Get the total amount of tokens staked by `_accountAddress` at block number `_blockNumber`
* @param _accountAddress - Account requesting for
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked by the account at the given block number
*/
function totalStakedForAt(
address _accountAddress,
uint256 _blockNumber
) external view returns (uint256) {
_requireIsInitialized();
return accounts[_accountAddress].stakedHistory.get(_blockNumber.toUint64());
}
/**
* @notice Get the total amount of tokens staked by all users at block number `_blockNumber`
* @param _blockNumber - Block number at which we are requesting
* @return The amount of tokens staked at the given block number
*/
function totalStakedAt(uint256 _blockNumber) external view returns (uint256) {
_requireIsInitialized();
return totalStakedHistory.get(_blockNumber.toUint64());
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Helper function wrapped around totalStakedFor. Checks whether _accountAddress
is currently a valid staker with a non-zero stake
* @param _accountAddress - Account requesting for
* @return Boolean indicating whether account is a staker
*/
function isStaker(address _accountAddress) external view returns (bool) {
_requireIsInitialized();
return totalStakedFor(_accountAddress) > 0;
}
/* Public functions */
/**
* @notice Get the amount of tokens staked by `_accountAddress`
* @param _accountAddress - The owner of the tokens
* @return The amount of tokens staked by the given account
*/
function totalStakedFor(address _accountAddress) public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return accounts[_accountAddress].stakedHistory.getLast();
}
/**
* @notice Get the total amount of tokens staked by all users
* @return The total amount of tokens staked by all users
*/
function totalStaked() public view returns (uint256) {
_requireIsInitialized();
// we assume it's not possible to stake in the future
return totalStakedHistory.getLast();
}
// ========================================= Internal Functions =========================================
/**
* @notice Adds stake from a transfer account to the stake account
* @param _stakeAccount - Account that funds will be staked for
* @param _transferAccount - Account that funds will be transferred from
* @param _amount - amount to stake
*/
function _stakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
// staking 0 tokens is invalid
require(_amount > 0, ERROR_AMOUNT_ZERO);
// Checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, true);
// checkpoint total supply
_modifyTotalStaked(_amount, true);
// pull tokens into Staking contract
stakingToken.safeTransferFrom(_transferAccount, address(this), _amount);
emit Staked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount));
}
/**
* @notice Unstakes tokens from a stake account to a transfer account
* @param _stakeAccount - Account that staked funds will be transferred from
* @param _transferAccount - Account that funds will be transferred to
* @param _amount - amount to unstake
*/
function _unstakeFor(
address _stakeAccount,
address _transferAccount,
uint256 _amount
) internal
{
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// transfer tokens
stakingToken.safeTransfer(_transferAccount, _amount);
emit Unstaked(
_stakeAccount,
_amount,
totalStakedFor(_stakeAccount)
);
}
/**
* @notice Burn tokens for a given staker
* @dev Called when slash occurs
* @param _stakeAccount - Account for which funds will be burned
* @param _amount - amount to burn
*/
function _burnFor(address _stakeAccount, uint256 _amount) internal {
// burning zero tokens is not allowed
require(_amount > 0, ERROR_AMOUNT_ZERO);
// checkpoint updated staking balance
_modifyStakeBalance(_stakeAccount, _amount, false);
// checkpoint total supply
_modifyTotalStaked(_amount, false);
// burn
ERC20Burnable(address(stakingToken)).burn(_amount);
/** No event emitted since token.burn() call already emits a Transfer event */
}
/**
* @notice Increase or decrease the staked balance for an account
* @param _accountAddress - Account to modify
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyStakeBalance(address _accountAddress, uint256 _by, bool _increase) internal {
uint256 currentInternalStake = accounts[_accountAddress].stakedHistory.getLast();
uint256 newStake;
if (_increase) {
newStake = currentInternalStake.add(_by);
} else {
require(
currentInternalStake >= _by,
"Staking: Cannot decrease greater than current balance");
newStake = currentInternalStake.sub(_by);
}
// add new value to account history
accounts[_accountAddress].stakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Increase or decrease the staked balance across all accounts
* @param _by - amount to modify
* @param _increase - true if increase in stake, false if decrease
*/
function _modifyTotalStaked(uint256 _by, bool _increase) internal {
uint256 currentStake = totalStaked();
uint256 newStake;
if (_increase) {
newStake = currentStake.add(_by);
} else {
newStake = currentStake.sub(_by);
}
// add new value to total history
totalStakedHistory.add(block.number.toUint64(), newStake);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"Staking: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
// ========================================= Private Functions =========================================
function _requireClaimsManagerAddressIsSet() private view {
require(claimsManagerAddress != address(0x00), "Staking: claimsManagerAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"Staking: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"Staking: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceTypeManager.sol
pragma solidity ^0.5.0;
contract ServiceTypeManager is InitializableV2 {
address governanceAddress;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceTypeManager: Only callable by Governance contract"
);
/**
* @dev - mapping of serviceType - serviceTypeVersion
* Example - "discovery-provider" - ["0.0.1", "0.0.2", ..., "currentVersion"]
*/
mapping(bytes32 => bytes32[]) private serviceTypeVersions;
/**
* @dev - mapping of serviceType - < serviceTypeVersion, isValid >
* Example - "discovery-provider" - <"0.0.1", true>
*/
mapping(bytes32 => mapping(bytes32 => bool)) private serviceTypeVersionInfo;
/// @dev List of valid service types
bytes32[] private validServiceTypes;
/// @dev Struct representing service type info
struct ServiceTypeInfo {
bool isValid;
uint256 minStake;
uint256 maxStake;
}
/// @dev mapping of service type info
mapping(bytes32 => ServiceTypeInfo) private serviceTypeInfo;
event SetServiceVersion(
bytes32 indexed _serviceType,
bytes32 indexed _serviceVersion
);
event ServiceTypeAdded(
bytes32 indexed _serviceType,
uint256 indexed _serviceTypeMin,
uint256 indexed _serviceTypeMax
);
event ServiceTypeRemoved(bytes32 indexed _serviceType);
/**
* @notice Function to initialize the contract
* @param _governanceAddress - Governance proxy address
*/
function initialize(address _governanceAddress) public initializer
{
_updateGovernanceAddress(_governanceAddress);
InitializableV2.initialize();
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
}
// ========================================= Service Type Logic =========================================
/**
* @notice Add a new service type
* @param _serviceType - type of service to add
* @param _serviceTypeMin - minimum stake for service type
* @param _serviceTypeMax - maximum stake for service type
*/
function addServiceType(
bytes32 _serviceType,
uint256 _serviceTypeMin,
uint256 _serviceTypeMax
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(
!this.serviceTypeIsValid(_serviceType),
"ServiceTypeManager: Already known service type"
);
require(
_serviceTypeMax > _serviceTypeMin,
"ServiceTypeManager: Max stake must be non-zero and greater than min stake"
);
// Ensure serviceType cannot be re-added if it previously existed and was removed
// stored maxStake > 0 means it was previously added and removed
require(
serviceTypeInfo[_serviceType].maxStake == 0,
"ServiceTypeManager: Cannot re-add serviceType after it was removed."
);
validServiceTypes.push(_serviceType);
serviceTypeInfo[_serviceType] = ServiceTypeInfo({
isValid: true,
minStake: _serviceTypeMin,
maxStake: _serviceTypeMax
});
emit ServiceTypeAdded(_serviceType, _serviceTypeMin, _serviceTypeMax);
}
/**
* @notice Remove an existing service type
* @param _serviceType - name of service type to remove
*/
function removeServiceType(bytes32 _serviceType) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
uint256 serviceIndex = 0;
bool foundService = false;
for (uint256 i = 0; i < validServiceTypes.length; i ++) {
if (validServiceTypes[i] == _serviceType) {
serviceIndex = i;
foundService = true;
break;
}
}
require(foundService == true, "ServiceTypeManager: Invalid service type, not found");
// Overwrite service index
uint256 lastIndex = validServiceTypes.length - 1;
validServiceTypes[serviceIndex] = validServiceTypes[lastIndex];
validServiceTypes.length--;
// Mark as invalid
serviceTypeInfo[_serviceType].isValid = false;
// Note - stake bounds are not reset so they can be checked to prevent serviceType from being re-added
emit ServiceTypeRemoved(_serviceType);
}
/**
* @notice Get isValid, min and max stake for a given service type
* @param _serviceType - type of service
* @return isValid, min and max stake for type
*/
function getServiceTypeInfo(bytes32 _serviceType)
external view returns (bool isValid, uint256 minStake, uint256 maxStake)
{
_requireIsInitialized();
return (
serviceTypeInfo[_serviceType].isValid,
serviceTypeInfo[_serviceType].minStake,
serviceTypeInfo[_serviceType].maxStake
);
}
/**
* @notice Get list of valid service types
*/
function getValidServiceTypes()
external view returns (bytes32[] memory)
{
_requireIsInitialized();
return validServiceTypes;
}
/**
* @notice Return indicating whether this is a valid service type
*/
function serviceTypeIsValid(bytes32 _serviceType)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeInfo[_serviceType].isValid;
}
// ========================================= Service Version Logic =========================================
/**
* @notice Add new version for a serviceType
* @param _serviceType - type of service
* @param _serviceVersion - new version of service to add
*/
function setServiceVersion(
bytes32 _serviceType,
bytes32 _serviceVersion
) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
require(this.serviceTypeIsValid(_serviceType), "ServiceTypeManager: Invalid service type");
require(
serviceTypeVersionInfo[_serviceType][_serviceVersion] == false,
"ServiceTypeManager: Already registered"
);
// Update array of known versions for type
serviceTypeVersions[_serviceType].push(_serviceVersion);
// Update status for this specific service version
serviceTypeVersionInfo[_serviceType][_serviceVersion] = true;
emit SetServiceVersion(_serviceType, _serviceVersion);
}
/**
* @notice Get a version for a service type given it's index
* @param _serviceType - type of service
* @param _versionIndex - index in list of service versions
* @return bytes32 value for serviceVersion
*/
function getVersion(bytes32 _serviceType, uint256 _versionIndex)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length > _versionIndex,
"ServiceTypeManager: No registered version of serviceType"
);
return (serviceTypeVersions[_serviceType][_versionIndex]);
}
/**
* @notice Get curent version for a service type
* @param _serviceType - type of service
* @return Returns current version of service
*/
function getCurrentVersion(bytes32 _serviceType)
external view returns (bytes32)
{
_requireIsInitialized();
require(
serviceTypeVersions[_serviceType].length >= 1,
"ServiceTypeManager: No registered version of serviceType"
);
uint256 latestVersionIndex = serviceTypeVersions[_serviceType].length - 1;
return (serviceTypeVersions[_serviceType][latestVersionIndex]);
}
/**
* @notice Get total number of versions for a service type
* @param _serviceType - type of service
*/
function getNumberOfVersions(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceTypeVersions[_serviceType].length;
}
/**
* @notice Return boolean indicating whether given version is valid for given type
* @param _serviceType - type of service
* @param _serviceVersion - version of service to check
*/
function serviceVersionIsValid(bytes32 _serviceType, bytes32 _serviceVersion)
external view returns (bool)
{
_requireIsInitialized();
return serviceTypeVersionInfo[_serviceType][_serviceVersion];
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceTypeManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
}
// File: contracts/ClaimsManager.sol
pragma solidity ^0.5.0;
/// @notice ERC20 imported via Staking.sol
/// @notice SafeERC20 imported via Staking.sol
/// @notice Governance imported via Staking.sol
/// @notice SafeMath imported via ServiceProviderFactory.sol
/**
* Designed to automate claim funding, minting tokens as necessary
* @notice - will call InitializableV2 constructor
*/
contract ClaimsManager is InitializableV2 {
using SafeMath for uint256;
using SafeERC20 for ERC20;
string private constant ERROR_ONLY_GOVERNANCE = (
"ClaimsManager: Only callable by Governance contract"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private delegateManagerAddress;
/**
* @notice - Minimum number of blocks between funding rounds
* 604800 seconds / week
* Avg block time - 13s
* 604800 / 13 = 46523.0769231 blocks
*/
uint256 private fundingRoundBlockDiff;
/**
* @notice - Configures the current funding amount per round
* Weekly rounds, 7% PA inflation = 70,000,000 new tokens in first year
* = 70,000,000/365*7 (year is slightly more than a week)
* = 1342465.75342 new AUDS per week
* = 1342465753420000000000000 new wei units per week
* @dev - Past a certain block height, this schedule will be updated
* - Logic determining schedule will be sourced from an external contract
*/
uint256 private fundingAmount;
// Denotes current round
uint256 private roundNumber;
// Staking contract ref
ERC20Mintable private audiusToken;
/// @dev - Address to which recurringCommunityFundingAmount is transferred at funding round start
address private communityPoolAddress;
/// @dev - Reward amount transferred to communityPoolAddress at funding round start
uint256 private recurringCommunityFundingAmount;
// Struct representing round state
// 1) Block at which round was funded
// 2) Total funded for this round
// 3) Total claimed in round
struct Round {
uint256 fundedBlock;
uint256 fundedAmount;
uint256 totalClaimedInRound;
}
// Current round information
Round private currentRound;
event RoundInitiated(
uint256 indexed _blockNumber,
uint256 indexed _roundNumber,
uint256 indexed _fundAmount
);
event ClaimProcessed(
address indexed _claimer,
uint256 indexed _rewards,
uint256 _oldTotal,
uint256 indexed _newTotal
);
event CommunityRewardsTransferred(
address indexed _transferAddress,
uint256 indexed _amount
);
event FundingAmountUpdated(uint256 indexed _amount);
event FundingRoundBlockDiffUpdated(uint256 indexed _blockDifference);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event RecurringCommunityFundingAmountUpdated(uint256 indexed _amount);
event CommunityPoolAddressUpdated(address indexed _newCommunityPoolAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - address for Governance proxy contract
*/
function initialize(
address _tokenAddress,
address _governanceAddress
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
fundingRoundBlockDiff = 46523;
fundingAmount = 1342465753420000000000000; // 1342465.75342 AUDS
roundNumber = 0;
currentRound = Round({
fundedBlock: 0,
fundedAmount: 0,
totalClaimedInRound: 0
});
// Community pool funding amount and address initialized to zero
recurringCommunityFundingAmount = 0;
communityPoolAddress = address(0x0);
InitializableV2.initialize();
}
/// @notice Get the duration of a funding round in blocks
function getFundingRoundBlockDiff() external view returns (uint256)
{
_requireIsInitialized();
return fundingRoundBlockDiff;
}
/// @notice Get the last block where a funding round was initiated
function getLastFundedBlock() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.fundedBlock;
}
/// @notice Get the amount funded per round in wei
function getFundsPerRound() external view returns (uint256)
{
_requireIsInitialized();
return fundingAmount;
}
/// @notice Get the total amount claimed in the current round
function getTotalClaimedInRound() external view returns (uint256)
{
_requireIsInitialized();
return currentRound.totalClaimedInRound;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/**
* @notice Get the Staking address
*/
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
/**
* @notice Get the community pool address
*/
function getCommunityPoolAddress() external view returns (address)
{
_requireIsInitialized();
return communityPoolAddress;
}
/**
* @notice Get the community funding amount
*/
function getRecurringCommunityFundingAmount() external view returns (uint256)
{
_requireIsInitialized();
return recurringCommunityFundingAmount;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _serviceProviderFactoryAddress - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _serviceProviderFactoryAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _serviceProviderFactoryAddress;
emit ServiceProviderFactoryAddressUpdated(_serviceProviderFactoryAddress);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _delegateManagerAddress - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _delegateManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _delegateManagerAddress;
emit DelegateManagerAddressUpdated(_delegateManagerAddress);
}
/**
* @notice Start a new funding round
* @dev Permissioned to be callable by stakers or governance contract
*/
function initiateRound() external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
block.number.sub(currentRound.fundedBlock) > fundingRoundBlockDiff,
"ClaimsManager: Required block difference not met"
);
currentRound = Round({
fundedBlock: block.number,
fundedAmount: fundingAmount,
totalClaimedInRound: 0
});
roundNumber = roundNumber.add(1);
/*
* Transfer community funding amount to community pool address, if set
*/
if (recurringCommunityFundingAmount > 0 && communityPoolAddress != address(0x0)) {
// ERC20Mintable always returns true
audiusToken.mint(address(this), recurringCommunityFundingAmount);
// Approve transfer to community pool address
audiusToken.approve(communityPoolAddress, recurringCommunityFundingAmount);
// Transfer to community pool address
ERC20(address(audiusToken)).safeTransfer(communityPoolAddress, recurringCommunityFundingAmount);
emit CommunityRewardsTransferred(communityPoolAddress, recurringCommunityFundingAmount);
}
emit RoundInitiated(
currentRound.fundedBlock,
roundNumber,
currentRound.fundedAmount
);
}
/**
* @notice Mints and stakes tokens on behalf of ServiceProvider + delegators
* @dev Callable through DelegateManager by Service Provider
* @param _claimer - service provider address
* @param _totalLockedForSP - amount of tokens locked up across DelegateManager + ServiceProvider
* @return minted rewards for this claimer
*/
function processClaim(
address _claimer,
uint256 _totalLockedForSP
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ClaimsManager: ProcessClaim only accessible to DelegateManager"
);
Staking stakingContract = Staking(stakingAddress);
// Prevent duplicate claim
uint256 lastUserClaimBlock = stakingContract.lastClaimedFor(_claimer);
require(
lastUserClaimBlock <= currentRound.fundedBlock,
"ClaimsManager: Claim already processed for user"
);
uint256 totalStakedAtFundBlockForClaimer = stakingContract.totalStakedForAt(
_claimer,
currentRound.fundedBlock);
(,,bool withinBounds,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_claimer)
);
// Once they claim the zero reward amount, stake can be modified once again
// Subtract total locked amount for SP from stake at fund block
uint256 totalActiveClaimerStake = totalStakedAtFundBlockForClaimer.sub(_totalLockedForSP);
uint256 totalStakedAtFundBlock = stakingContract.totalStakedAt(currentRound.fundedBlock);
// Calculate claimer rewards
uint256 rewardsForClaimer = (
totalActiveClaimerStake.mul(fundingAmount)
).div(totalStakedAtFundBlock);
// For a claimer violating bounds, no new tokens are minted
// Claim history is marked to zero and function is short-circuited
// Total rewards can be zero if all stake is currently locked up
if (!withinBounds || rewardsForClaimer == 0) {
stakingContract.updateClaimHistory(0, _claimer);
emit ClaimProcessed(
_claimer,
0,
totalStakedAtFundBlockForClaimer,
totalActiveClaimerStake
);
return 0;
}
// ERC20Mintable always returns true
audiusToken.mint(address(this), rewardsForClaimer);
// Approve transfer to staking address for claimer rewards
// ERC20 always returns true
audiusToken.approve(stakingAddress, rewardsForClaimer);
// Transfer rewards
stakingContract.stakeRewards(rewardsForClaimer, _claimer);
// Update round claim value
currentRound.totalClaimedInRound = currentRound.totalClaimedInRound.add(rewardsForClaimer);
// Update round claim value
uint256 newTotal = stakingContract.totalStakedFor(_claimer);
emit ClaimProcessed(
_claimer,
rewardsForClaimer,
totalStakedAtFundBlockForClaimer,
newTotal
);
return rewardsForClaimer;
}
/**
* @notice Modify funding amount per round
* @param _newAmount - new amount to fund per round in wei
*/
function updateFundingAmount(uint256 _newAmount) external
{
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
fundingAmount = _newAmount;
emit FundingAmountUpdated(_newAmount);
}
/**
* @notice Returns boolean indicating whether a claim is considered pending
* @dev Note that an address with no endpoints can never have a pending claim
* @param _sp - address of the service provider to check
* @return true if eligible for claim, false if not
*/
function claimPending(address _sp) external view returns (bool) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
uint256 lastClaimedForSP = Staking(stakingAddress).lastClaimedFor(_sp);
(,,,uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(_sp)
);
return (lastClaimedForSP < currentRound.fundedBlock && numEndpoints > 0);
}
/**
* @notice Modify minimum block difference between funding rounds
* @param _newFundingRoundBlockDiff - new min block difference to set
*/
function updateFundingRoundBlockDiff(uint256 _newFundingRoundBlockDiff) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
emit FundingRoundBlockDiffUpdated(_newFundingRoundBlockDiff);
fundingRoundBlockDiff = _newFundingRoundBlockDiff;
}
/**
* @notice Modify community funding amound for each round
* @param _newRecurringCommunityFundingAmount - new reward amount transferred to
* communityPoolAddress at funding round start
*/
function updateRecurringCommunityFundingAmount(
uint256 _newRecurringCommunityFundingAmount
) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
recurringCommunityFundingAmount = _newRecurringCommunityFundingAmount;
emit RecurringCommunityFundingAmountUpdated(_newRecurringCommunityFundingAmount);
}
/**
* @notice Modify community pool address
* @param _newCommunityPoolAddress - new address to which recurringCommunityFundingAmount
* is transferred at funding round start
*/
function updateCommunityPoolAddress(address _newCommunityPoolAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
communityPoolAddress = _newCommunityPoolAddress;
emit CommunityPoolAddressUpdated(_newCommunityPoolAddress);
}
// ========================================= Private Functions =========================================
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) private {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ClaimsManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
function _requireStakingAddressIsSet() private view {
require(stakingAddress != address(0x00), "ClaimsManager: stakingAddress is not set");
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ClaimsManager: delegateManagerAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"ClaimsManager: serviceProviderFactoryAddress is not set"
);
}
}
// File: contracts/ServiceProviderFactory.sol
pragma solidity ^0.5.0;
/// @notice Governance imported via Staking.sol
contract ServiceProviderFactory is InitializableV2 {
using SafeMath for uint256;
/// @dev - denominator for deployer cut calculations
/// @dev - user values are intended to be x/DEPLOYER_CUT_BASE
uint256 private constant DEPLOYER_CUT_BASE = 100;
string private constant ERROR_ONLY_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Governance contract"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"ServiceProviderFactory: Only callable by Service Provider or Governance"
);
address private stakingAddress;
address private delegateManagerAddress;
address private governanceAddress;
address private serviceTypeManagerAddress;
address private claimsManagerAddress;
/// @notice Period in blocks that a decrease stake operation is delayed.
/// Must be greater than governance votingPeriod + executionDelay in order to
/// prevent pre-emptive withdrawal in anticipation of a slash proposal
uint256 private decreaseStakeLockupDuration;
/// @notice Period in blocks that an update deployer cut operation is delayed.
/// Must be greater than funding round block diff in order
/// to prevent manipulation around a funding round
uint256 private deployerCutLockupDuration;
/// @dev - Stores following entities
/// 1) Directly staked amount by SP, not including delegators
/// 2) % Cut of delegator tokens taken during reward
/// 3) Bool indicating whether this SP has met min/max requirements
/// 4) Number of endpoints registered by SP
/// 5) Minimum deployer stake for this service provider
/// 6) Maximum total stake for this account
struct ServiceProviderDetails {
uint256 deployerStake;
uint256 deployerCut;
bool validBounds;
uint256 numberOfEndpoints;
uint256 minAccountStake;
uint256 maxAccountStake;
}
/// @dev - Data structure for time delay during withdrawal
struct DecreaseStakeRequest {
uint256 decreaseAmount;
uint256 lockupExpiryBlock;
}
/// @dev - Data structure for time delay during deployer cut update
struct UpdateDeployerCutRequest {
uint256 newDeployerCut;
uint256 lockupExpiryBlock;
}
/// @dev - Struct maintaining information about sp
/// @dev - blocknumber is block.number when endpoint registered
struct ServiceEndpoint {
address owner;
string endpoint;
uint256 blocknumber;
address delegateOwnerWallet;
}
/// @dev - Mapping of service provider address to details
mapping(address => ServiceProviderDetails) private spDetails;
/// @dev - Uniquely assigned serviceProvider ID, incremented for each service type
/// @notice - Keeps track of the total number of services registered regardless of
/// whether some have been deregistered since
mapping(bytes32 => uint256) private serviceProviderTypeIDs;
/// @dev - mapping of (serviceType -> (serviceInstanceId <-> serviceProviderInfo))
/// @notice - stores the actual service provider data like endpoint and owner wallet
/// with the ability lookup by service type and service id */
mapping(bytes32 => mapping(uint256 => ServiceEndpoint)) private serviceProviderInfo;
/// @dev - mapping of keccak256(endpoint) to uint256 ID
/// @notice - used to check if a endpoint has already been registered and also lookup
/// the id of an endpoint
mapping(bytes32 => uint256) private serviceProviderEndpointToId;
/// @dev - mapping of address -> sp id array */
/// @notice - stores all the services registered by a provider. for each address,
/// provides the ability to lookup by service type and see all registered services
mapping(address => mapping(bytes32 => uint256[])) private serviceProviderAddressToId;
/// @dev - Mapping of service provider -> decrease stake request
mapping(address => DecreaseStakeRequest) private decreaseStakeRequests;
/// @dev - Mapping of service provider -> update deployer cut requests
mapping(address => UpdateDeployerCutRequest) private updateDeployerCutRequests;
event RegisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _stakeAmount
);
event DeregisteredServiceProvider(
uint256 indexed _spID,
bytes32 indexed _serviceType,
address indexed _owner,
string _endpoint,
uint256 _unstakeAmount
);
event IncreasedStake(
address indexed _owner,
uint256 indexed _increaseAmount,
uint256 indexed _newStakeAmount
);
event DecreaseStakeRequested(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestCancelled(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _lockupExpiryBlock
);
event DecreaseStakeRequestEvaluated(
address indexed _owner,
uint256 indexed _decreaseAmount,
uint256 indexed _newStakeAmount
);
event EndpointUpdated(
bytes32 indexed _serviceType,
address indexed _owner,
string _oldEndpoint,
string _newEndpoint,
uint256 indexed _spID
);
event DelegateOwnerWalletUpdated(
address indexed _owner,
bytes32 indexed _serviceType,
uint256 indexed _spID,
address _updatedWallet
);
event DeployerCutUpdateRequested(
address indexed _owner,
uint256 indexed _updatedCut,
uint256 indexed _lockupExpiryBlock
);
event DeployerCutUpdateRequestCancelled(
address indexed _owner,
uint256 indexed _requestedCut,
uint256 indexed _finalCut
);
event DeployerCutUpdateRequestEvaluated(
address indexed _owner,
uint256 indexed _updatedCut
);
event DecreaseStakeLockupDurationUpdated(uint256 indexed _lockupDuration);
event UpdateDeployerCutLockupDurationUpdated(uint256 indexed _lockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event DelegateManagerAddressUpdated(address indexed _newDelegateManagerAddress);
event ServiceTypeManagerAddressUpdated(address indexed _newServiceTypeManagerAddress);
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev delegateManagerAddress must be initialized separately after DelegateManager contract is deployed
* @dev serviceTypeManagerAddress must be initialized separately after ServiceTypeManager contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _governanceAddress,
address _claimsManagerAddress,
uint256 _decreaseStakeLockupDuration,
uint256 _deployerCutLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
claimsManagerAddress = _claimsManagerAddress;
_updateDecreaseStakeLockupDuration(_decreaseStakeLockupDuration);
_updateDeployerCutLockupDuration(_deployerCutLockupDuration);
InitializableV2.initialize();
}
/**
* @notice Register a new endpoint to the account of msg.sender
* @dev Transfers stake from service provider into staking pool
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _stakeAmount - amount to stake, must be within bounds in ServiceTypeManager
* @param _delegateOwnerWallet - wallet to delegate some permissions for some basic management properties
* @return New service provider ID for this endpoint
*/
function register(
bytes32 _serviceType,
string calldata _endpoint,
uint256 _stakeAmount,
address _delegateOwnerWallet
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
ServiceTypeManager(serviceTypeManagerAddress).serviceTypeIsValid(_serviceType),
"ServiceProviderFactory: Valid service type required");
// Stake token amount from msg.sender
if (_stakeAmount > 0) {
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No pending claim expected"
);
Staking(stakingAddress).stakeFor(msg.sender, _stakeAmount);
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] == 0,
"ServiceProviderFactory: Endpoint already registered");
uint256 newServiceProviderID = serviceProviderTypeIDs[_serviceType].add(1);
serviceProviderTypeIDs[_serviceType] = newServiceProviderID;
// Index spInfo
serviceProviderInfo[_serviceType][newServiceProviderID] = ServiceEndpoint({
owner: msg.sender,
endpoint: _endpoint,
blocknumber: block.number,
delegateOwnerWallet: _delegateOwnerWallet
});
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = newServiceProviderID;
// Update (address -> type -> ids[])
serviceProviderAddressToId[msg.sender][_serviceType].push(newServiceProviderID);
// Increment number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints = spDetails[msg.sender].numberOfEndpoints.add(1);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_stakeAmount)
);
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.add(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.add(typeMax);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
uint256 currentlyStakedForOwner = Staking(stakingAddress).totalStakedFor(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit RegisteredServiceProvider(
newServiceProviderID,
_serviceType,
msg.sender,
_endpoint,
currentlyStakedForOwner
);
return newServiceProviderID;
}
/**
* @notice Deregister an endpoint from the account of msg.sender
* @dev Unstakes all tokens for service provider if this is the last endpoint
* @param _serviceType - type of service to deregister
* @param _endpoint - endpoint to deregister
* @return spId of the service that was deregistered
*/
function deregister(
bytes32 _serviceType,
string calldata _endpoint
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceTypeManagerAddressIsSet();
// Unstake on deregistration if and only if this is the last service endpoint
uint256 unstakeAmount = 0;
bool unstaked = false;
// owned by the service provider
if (spDetails[msg.sender].numberOfEndpoints == 1) {
unstakeAmount = spDetails[msg.sender].deployerStake;
// Submit request to decrease stake, overriding any pending request
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: unstakeAmount,
lockupExpiryBlock: block.number.add(decreaseStakeLockupDuration)
});
unstaked = true;
}
require (
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] != 0,
"ServiceProviderFactory: Endpoint not registered");
// Cache invalided service provider ID
uint256 deregisteredID = serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
// Update endpoint mapping
serviceProviderEndpointToId[keccak256(bytes(_endpoint))] = 0;
require(
keccak256(bytes(serviceProviderInfo[_serviceType][deregisteredID].endpoint)) == keccak256(bytes(_endpoint)),
"ServiceProviderFactory: Invalid endpoint for service type");
require (
serviceProviderInfo[_serviceType][deregisteredID].owner == msg.sender,
"ServiceProviderFactory: Only callable by endpoint owner");
// Update info mapping
delete serviceProviderInfo[_serviceType][deregisteredID];
// Reset id, update array
uint256 spTypeLength = serviceProviderAddressToId[msg.sender][_serviceType].length;
for (uint256 i = 0; i < spTypeLength; i ++) {
if (serviceProviderAddressToId[msg.sender][_serviceType][i] == deregisteredID) {
// Overwrite element to be deleted with last element in array
serviceProviderAddressToId[msg.sender][_serviceType][i] = serviceProviderAddressToId[msg.sender][_serviceType][spTypeLength - 1];
// Reduce array size, exit loop
serviceProviderAddressToId[msg.sender][_serviceType].length--;
// Confirm this ID has been found for the service provider
break;
}
}
// Decrement number of endpoints for this address
spDetails[msg.sender].numberOfEndpoints -= 1;
// Update min and max totals for this service provider
(, uint256 typeMin, uint256 typeMax) = ServiceTypeManager(
serviceTypeManagerAddress
).getServiceTypeInfo(_serviceType);
spDetails[msg.sender].minAccountStake = spDetails[msg.sender].minAccountStake.sub(typeMin);
spDetails[msg.sender].maxAccountStake = spDetails[msg.sender].maxAccountStake.sub(typeMax);
emit DeregisteredServiceProvider(
deregisteredID,
_serviceType,
msg.sender,
_endpoint,
unstakeAmount);
// Confirm both aggregate account balance and directly staked amount are valid
// Only if unstake operation has not occurred
if (!unstaked) {
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
}
return deregisteredID;
}
/**
* @notice Increase stake for service provider
* @param _increaseStakeAmount - amount to increase staked amount by
* @return New total stake for service provider
*/
function increaseStake(
uint256 _increaseStakeAmount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
// Confirm owner has an endpoint
require(
spDetails[msg.sender].numberOfEndpoints > 0,
"ServiceProviderFactory: Registered endpoint required to increase stake"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
// Stake increased token amount for msg.sender
stakingContract.stakeFor(msg.sender, _increaseStakeAmount);
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.add(_increaseStakeAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
this.validateAccountStakeBalance(msg.sender);
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
emit IncreasedStake(
msg.sender,
_increaseStakeAmount,
newStakeAmount
);
return newStakeAmount;
}
/**
* @notice Request to decrease stake. This sets a lockup for decreaseStakeLockupDuration after
which the actual decreaseStake can be called
* @dev Decreasing stake is only processed if a service provider is within valid bounds
* @param _decreaseStakeAmount - amount to decrease stake by in wei
* @return New total stake amount after the lockup
*/
function requestDecreaseStake(uint256 _decreaseStakeAmount)
external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
_decreaseStakeAmount > 0,
"ServiceProviderFactory: Requested stake decrease amount must be greater than zero"
);
require(
!_claimPending(msg.sender),
"ServiceProviderFactory: No claim expected to be pending prior to stake transfer"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 currentStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Prohibit decreasing stake to invalid bounds
_validateBalanceInternal(msg.sender, (currentStakeAmount.sub(_decreaseStakeAmount)));
uint256 expiryBlock = block.number.add(decreaseStakeLockupDuration);
decreaseStakeRequests[msg.sender] = DecreaseStakeRequest({
decreaseAmount: _decreaseStakeAmount,
lockupExpiryBlock: expiryBlock
});
emit DecreaseStakeRequested(msg.sender, _decreaseStakeAmount, expiryBlock);
return currentStakeAmount.sub(_decreaseStakeAmount);
}
/**
* @notice Cancel a decrease stake request during the lockup
* @dev Either called by the service provider via DelegateManager or governance
during a slash action
* @param _account - address of service provider
*/
function cancelDecreaseStakeRequest(address _account) external
{
_requireIsInitialized();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == _account || msg.sender == delegateManagerAddress,
"ServiceProviderFactory: Only owner or DelegateManager"
);
require(
_decreaseRequestIsPending(_account),
"ServiceProviderFactory: Decrease stake request must be pending"
);
DecreaseStakeRequest memory cancelledRequest = decreaseStakeRequests[_account];
// Clear decrease stake request
decreaseStakeRequests[_account] = DecreaseStakeRequest({
decreaseAmount: 0,
lockupExpiryBlock: 0
});
emit DecreaseStakeRequestCancelled(
_account,
cancelledRequest.decreaseAmount,
cancelledRequest.lockupExpiryBlock
);
}
/**
* @notice Called by user to decrease a stake after waiting the appropriate lockup period.
* @return New total stake after decrease
*/
function decreaseStake() external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
_decreaseRequestIsPending(msg.sender),
"ServiceProviderFactory: Decrease stake request must be pending"
);
require(
decreaseStakeRequests[msg.sender].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
Staking stakingContract = Staking(
stakingAddress
);
uint256 decreaseAmount = decreaseStakeRequests[msg.sender].decreaseAmount;
// Decrease staked token amount for msg.sender
stakingContract.unstakeFor(msg.sender, decreaseAmount);
// Query current stake
uint256 newStakeAmount = stakingContract.totalStakedFor(msg.sender);
// Update deployer total
spDetails[msg.sender].deployerStake = (
spDetails[msg.sender].deployerStake.sub(decreaseAmount)
);
// Confirm both aggregate account balance and directly staked amount are valid
// During registration this validation is bypassed since no endpoints remain
if (spDetails[msg.sender].numberOfEndpoints > 0) {
this.validateAccountStakeBalance(msg.sender);
}
// Indicate this service provider is within bounds
spDetails[msg.sender].validBounds = true;
// Clear decrease stake request
delete decreaseStakeRequests[msg.sender];
emit DecreaseStakeRequestEvaluated(msg.sender, decreaseAmount, newStakeAmount);
return newStakeAmount;
}
/**
* @notice Update delegate owner wallet for a given endpoint
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _endpoint - url of the service to register - url of the service to register
* @param _updatedDelegateOwnerWallet - address of new delegate wallet
*/
function updateDelegateOwnerWallet(
bytes32 _serviceType,
string calldata _endpoint,
address _updatedDelegateOwnerWallet
) external
{
_requireIsInitialized();
uint256 spID = this.getServiceProviderIdFromEndpoint(_endpoint);
require(
serviceProviderInfo[_serviceType][spID].owner == msg.sender,
"ServiceProviderFactory: Invalid update operation, wrong owner"
);
serviceProviderInfo[_serviceType][spID].delegateOwnerWallet = _updatedDelegateOwnerWallet;
emit DelegateOwnerWalletUpdated(
msg.sender,
_serviceType,
spID,
_updatedDelegateOwnerWallet
);
}
/**
* @notice Update the endpoint for a given service
* @param _serviceType - type of service to register, must be valid in ServiceTypeManager
* @param _oldEndpoint - old endpoint currently registered
* @param _newEndpoint - new endpoint to replace old endpoint
* @return ID of updated service provider
*/
function updateEndpoint(
bytes32 _serviceType,
string calldata _oldEndpoint,
string calldata _newEndpoint
) external returns (uint256)
{
_requireIsInitialized();
uint256 spId = this.getServiceProviderIdFromEndpoint(_oldEndpoint);
require (
spId != 0,
"ServiceProviderFactory: Could not find service provider with that endpoint"
);
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][spId];
require(
serviceEndpoint.owner == msg.sender,
"ServiceProviderFactory: Invalid update endpoint operation, wrong owner"
);
require(
keccak256(bytes(serviceEndpoint.endpoint)) == keccak256(bytes(_oldEndpoint)),
"ServiceProviderFactory: Old endpoint doesn't match what's registered for the service provider"
);
// invalidate old endpoint
serviceProviderEndpointToId[keccak256(bytes(serviceEndpoint.endpoint))] = 0;
// update to new endpoint
serviceEndpoint.endpoint = _newEndpoint;
serviceProviderInfo[_serviceType][spId] = serviceEndpoint;
serviceProviderEndpointToId[keccak256(bytes(_newEndpoint))] = spId;
emit EndpointUpdated(_serviceType, msg.sender, _oldEndpoint, _newEndpoint, spId);
return spId;
}
/**
* @notice Update the deployer cut for a given service provider
* @param _serviceProvider - address of service provider
* @param _cut - new value for deployer cut
*/
function requestUpdateDeployerCut(address _serviceProvider, uint256 _cut) external
{
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock == 0) &&
(updateDeployerCutRequests[_serviceProvider].newDeployerCut == 0),
"ServiceProviderFactory: Update deployer cut operation pending"
);
require(
_cut <= DEPLOYER_CUT_BASE,
"ServiceProviderFactory: Service Provider cut cannot exceed base value"
);
uint256 expiryBlock = block.number + deployerCutLockupDuration;
updateDeployerCutRequests[_serviceProvider] = UpdateDeployerCutRequest({
lockupExpiryBlock: expiryBlock,
newDeployerCut: _cut
});
emit DeployerCutUpdateRequested(_serviceProvider, _cut, expiryBlock);
}
/**
* @notice Cancel a pending request to update deployer cut
* @param _serviceProvider - address of service provider
*/
function cancelUpdateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
UpdateDeployerCutRequest memory cancelledRequest = (
updateDeployerCutRequests[_serviceProvider]
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestCancelled(
_serviceProvider,
cancelledRequest.newDeployerCut,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Evalue request to update service provider cut of claims
* @notice Update service provider cut as % of delegate claim, divided by the deployerCutBase.
* @dev SPs will interact with this value as a percent, value translation done client side
@dev A value of 5 dictates a 5% cut, with ( 5 / 100 ) * delegateReward going to an SP from each delegator each round.
*/
function updateDeployerCut(address _serviceProvider) external
{
_requireIsInitialized();
_requirePendingDeployerCutOperation(_serviceProvider);
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock <= block.number,
"ServiceProviderFactory: Lockup must be expired"
);
spDetails[_serviceProvider].deployerCut = (
updateDeployerCutRequests[_serviceProvider].newDeployerCut
);
// Zero out request information
delete updateDeployerCutRequests[_serviceProvider];
emit DeployerCutUpdateRequestEvaluated(
_serviceProvider,
spDetails[_serviceProvider].deployerCut
);
}
/**
* @notice Update service provider balance
* @dev Called by DelegateManager by functions modifying entire stake like claim and slash
* @param _serviceProvider - address of service provider
* @param _amount - new amount of direct state for service provider
*/
function updateServiceProviderStake(
address _serviceProvider,
uint256 _amount
) external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireDelegateManagerAddressIsSet();
require(
msg.sender == delegateManagerAddress,
"ServiceProviderFactory: only callable by DelegateManager"
);
// Update SP tracked total
spDetails[_serviceProvider].deployerStake = _amount;
_updateServiceProviderBoundStatus(_serviceProvider);
}
/// @notice Update service provider lockup duration
function updateDecreaseStakeLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDecreaseStakeLockupDuration(_duration);
emit DecreaseStakeLockupDurationUpdated(_duration);
}
/// @notice Update service provider lockup duration
function updateDeployerCutLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(
msg.sender == governanceAddress,
ERROR_ONLY_GOVERNANCE
);
_updateDeployerCutLockupDuration(_duration);
emit UpdateDeployerCutLockupDurationUpdated(_duration);
}
/// @notice Get denominator for deployer cut calculations
function getServiceProviderDeployerCutBase()
external view returns (uint256)
{
_requireIsInitialized();
return DEPLOYER_CUT_BASE;
}
/// @notice Get current deployer cut update lockup duration
function getDeployerCutLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return deployerCutLockupDuration;
}
/// @notice Get total number of service providers for a given serviceType
function getTotalServiceTypeProviders(bytes32 _serviceType)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderTypeIDs[_serviceType];
}
/// @notice Get service provider id for an endpoint
function getServiceProviderIdFromEndpoint(string calldata _endpoint)
external view returns (uint256)
{
_requireIsInitialized();
return serviceProviderEndpointToId[keccak256(bytes(_endpoint))];
}
/**
* @notice Get service provider ids for a given service provider and service type
* @return List of service ids of that type for a service provider
*/
function getServiceProviderIdsFromAddress(address _ownerAddress, bytes32 _serviceType)
external view returns (uint256[] memory)
{
_requireIsInitialized();
return serviceProviderAddressToId[_ownerAddress][_serviceType];
}
/**
* @notice Get information about a service endpoint given its service id
* @param _serviceType - type of service, must be a valid service from ServiceTypeManager
* @param _serviceId - id of service
*/
function getServiceEndpointInfo(bytes32 _serviceType, uint256 _serviceId)
external view returns (address owner, string memory endpoint, uint256 blockNumber, address delegateOwnerWallet)
{
_requireIsInitialized();
ServiceEndpoint memory serviceEndpoint = serviceProviderInfo[_serviceType][_serviceId];
return (
serviceEndpoint.owner,
serviceEndpoint.endpoint,
serviceEndpoint.blocknumber,
serviceEndpoint.delegateOwnerWallet
);
}
/**
* @notice Get information about a service provider given their address
* @param _serviceProvider - address of service provider
*/
function getServiceProviderDetails(address _serviceProvider)
external view returns (
uint256 deployerStake,
uint256 deployerCut,
bool validBounds,
uint256 numberOfEndpoints,
uint256 minAccountStake,
uint256 maxAccountStake)
{
_requireIsInitialized();
return (
spDetails[_serviceProvider].deployerStake,
spDetails[_serviceProvider].deployerCut,
spDetails[_serviceProvider].validBounds,
spDetails[_serviceProvider].numberOfEndpoints,
spDetails[_serviceProvider].minAccountStake,
spDetails[_serviceProvider].maxAccountStake
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingDecreaseStakeRequest(address _serviceProvider)
external view returns (uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
decreaseStakeRequests[_serviceProvider].decreaseAmount,
decreaseStakeRequests[_serviceProvider].lockupExpiryBlock
);
}
/**
* @notice Get information about pending decrease stake requests for service provider
* @param _serviceProvider - address of service provider
*/
function getPendingUpdateDeployerCutRequest(address _serviceProvider)
external view returns (uint256 newDeployerCut, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
return (
updateDeployerCutRequests[_serviceProvider].newDeployerCut,
updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock
);
}
/// @notice Get current unstake lockup duration
function getDecreaseStakeLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return decreaseStakeLockupDuration;
}
/**
* @notice Validate that the total service provider balance is between the min and max stakes
for all their registered services and validate direct stake for sp is above minimum
* @param _serviceProvider - address of service provider
*/
function validateAccountStakeBalance(address _serviceProvider)
external view
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_validateBalanceInternal(
_serviceProvider,
Staking(stakingAddress).totalStakedFor(_serviceProvider)
);
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address) {
_requireIsInitialized();
return stakingAddress;
}
/// @notice Get the DelegateManager address
function getDelegateManagerAddress() external view returns (address) {
_requireIsInitialized();
return delegateManagerAddress;
}
/// @notice Get the ServiceTypeManager address
function getServiceTypeManagerAddress() external view returns (address) {
_requireIsInitialized();
return serviceTypeManagerAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _address - address for new Staking contract
*/
function setStakingAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _address;
emit StakingAddressUpdated(_address);
}
/**
* @notice Set the DelegateManager address
* @dev Only callable by Governance address
* @param _address - address for new DelegateManager contract
*/
function setDelegateManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
delegateManagerAddress = _address;
emit DelegateManagerAddressUpdated(_address);
}
/**
* @notice Set the ServiceTypeManager address
* @dev Only callable by Governance address
* @param _address - address for new ServiceTypeManager contract
*/
function setServiceTypeManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceTypeManagerAddress = _address;
emit ServiceTypeManagerAddressUpdated(_address);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _address - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _address) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _address;
emit ClaimsManagerAddressUpdated(_address);
}
// ========================================= Internal Functions =========================================
/**
* @notice Update status in spDetails if the bounds for a service provider is valid
*/
function _updateServiceProviderBoundStatus(address _serviceProvider) internal {
// Validate bounds for total stake
uint256 totalSPStake = Staking(stakingAddress).totalStakedFor(_serviceProvider);
if (totalSPStake < spDetails[_serviceProvider].minAccountStake ||
totalSPStake > spDetails[_serviceProvider].maxAccountStake) {
// Indicate this service provider is out of bounds
spDetails[_serviceProvider].validBounds = false;
} else {
// Indicate this service provider is within bounds
spDetails[_serviceProvider].validBounds = true;
}
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"ServiceProviderFactory: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the deployer cut lockup duration
* @param _duration - incoming duration
*/
function _updateDeployerCutLockupDuration(uint256 _duration) internal
{
require(
ClaimsManager(claimsManagerAddress).getFundingRoundBlockDiff() < _duration,
"ServiceProviderFactory: Incoming duration must be greater than funding round block diff"
);
deployerCutLockupDuration = _duration;
}
/**
* @notice Set the decrease stake lockup duration
* @param _duration - incoming duration
*/
function _updateDecreaseStakeLockupDuration(uint256 _duration) internal
{
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"ServiceProviderFactory: decreaseStakeLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
decreaseStakeLockupDuration = _duration;
}
/**
* @notice Compare a given amount input against valid min and max bounds for service provider
* @param _serviceProvider - address of service provider
* @param _amount - amount in wei to compare
*/
function _validateBalanceInternal(address _serviceProvider, uint256 _amount) internal view
{
require(
_amount <= spDetails[_serviceProvider].maxAccountStake,
"ServiceProviderFactory: Maximum stake amount exceeded"
);
require(
spDetails[_serviceProvider].deployerStake >= spDetails[_serviceProvider].minAccountStake,
"ServiceProviderFactory: Minimum stake requirement not met"
);
}
/**
* @notice Get whether a decrease request has been initiated for service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether decrease request has been initiated
*/
function _decreaseRequestIsPending(address _serviceProvider)
internal view returns (bool)
{
return (
(decreaseStakeRequests[_serviceProvider].lockupExpiryBlock > 0) &&
(decreaseStakeRequests[_serviceProvider].decreaseAmount > 0)
);
}
/**
* @notice Boolean indicating whether a claim is pending for this service provider
*/
/**
* @notice Get whether a claim is pending for this service provider
* @param _serviceProvider - address of service provider
* return Boolean of whether claim is pending
*/
function _claimPending(address _serviceProvider) internal view returns (bool) {
return ClaimsManager(claimsManagerAddress).claimPending(_serviceProvider);
}
// ========================================= Private Functions =========================================
function _requirePendingDeployerCutOperation (address _serviceProvider) private view {
require(
(updateDeployerCutRequests[_serviceProvider].lockupExpiryBlock != 0),
"ServiceProviderFactory: No update deployer cut operation pending"
);
}
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"ServiceProviderFactory: stakingAddress is not set"
);
}
function _requireDelegateManagerAddressIsSet() private view {
require(
delegateManagerAddress != address(0x00),
"ServiceProviderFactory: delegateManagerAddress is not set"
);
}
function _requireServiceTypeManagerAddressIsSet() private view {
require(
serviceTypeManagerAddress != address(0x00),
"ServiceProviderFactory: serviceTypeManagerAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"ServiceProviderFactory: claimsManagerAddress is not set"
);
}
}
// File: contracts/DelegateManager.sol
pragma solidity ^0.5.0;
/// @notice SafeMath imported via ServiceProviderFactory.sol
/// @notice Governance imported via Staking.sol
/**
* Designed to manage delegation to staking contract
*/
contract DelegateManagerV2 is InitializableV2 {
using SafeMath for uint256;
string private constant ERROR_ONLY_GOVERNANCE = (
"DelegateManager: Only callable by Governance contract"
);
string private constant ERROR_MINIMUM_DELEGATION = (
"DelegateManager: Minimum delegation amount required"
);
string private constant ERROR_ONLY_SP_GOVERNANCE = (
"DelegateManager: Only callable by target SP or governance"
);
string private constant ERROR_DELEGATOR_STAKE = (
"DelegateManager: Delegator must be staked for SP"
);
address private governanceAddress;
address private stakingAddress;
address private serviceProviderFactoryAddress;
address private claimsManagerAddress;
/**
* Period in blocks an undelegate operation is delayed.
* The undelegate operation speed bump is to prevent a delegator from
* attempting to remove their delegation in anticipation of a slash.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private undelegateLockupDuration;
/// @notice Maximum number of delegators a single account can handle
uint256 private maxDelegators;
/// @notice Minimum amount of delegation allowed
uint256 private minDelegationAmount;
/**
* Lockup duration for a remove delegator request.
* The remove delegator speed bump is to prevent a service provider from maliciously
* removing a delegator prior to the evaluation of a proposal.
* @notice Must be greater than governance votingPeriod + executionDelay
*/
uint256 private removeDelegatorLockupDuration;
/**
* Evaluation period for a remove delegator request
* @notice added to expiry block calculated for removeDelegatorLockupDuration
*/
uint256 private removeDelegatorEvalDuration;
// Staking contract ref
ERC20Mintable private audiusToken;
// Struct representing total delegated to SP and list of delegators
struct ServiceProviderDelegateInfo {
uint256 totalDelegatedStake;
uint256 totalLockedUpStake;
address[] delegators;
}
// Data structures for lockup during withdrawal
struct UndelegateStakeRequest {
address serviceProvider;
uint256 amount;
uint256 lockupExpiryBlock;
}
// Service provider address -> ServiceProviderDelegateInfo
mapping (address => ServiceProviderDelegateInfo) private spDelegateInfo;
// Delegator stake by address delegated to
// delegator -> (service provider -> delegatedStake)
mapping (address => mapping(address => uint256)) private delegateInfo;
// Delegator stake total by address
// delegator -> (totalDelegated)
// Note - delegator properties are maintained in a mapping instead of struct
// in order to facilitate extensibility in the future.
mapping (address => uint256) private delegatorTotalStake;
// Requester to pending undelegate request
mapping (address => UndelegateStakeRequest) private undelegateRequests;
// Pending remove delegator requests
// service provider -> (delegator -> lockupExpiryBlock)
mapping (address => mapping (address => uint256)) private removeDelegatorRequests;
event IncreaseDelegatedStake(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _increaseAmount
);
event UndelegateStakeRequested(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount,
uint256 _lockupExpiryBlock
);
event UndelegateStakeRequestCancelled(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event UndelegateStakeRequestEvaluated(
address indexed _delegator,
address indexed _serviceProvider,
uint256 indexed _amount
);
event Claim(
address indexed _claimer,
uint256 indexed _rewards,
uint256 indexed _newTotal
);
event Slash(
address indexed _target,
uint256 indexed _amount,
uint256 indexed _newTotal
);
event RemoveDelegatorRequested(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _lockupExpiryBlock
);
event RemoveDelegatorRequestCancelled(
address indexed _serviceProvider,
address indexed _delegator
);
event RemoveDelegatorRequestEvaluated(
address indexed _serviceProvider,
address indexed _delegator,
uint256 indexed _unstakedAmount
);
event MaxDelegatorsUpdated(uint256 indexed _maxDelegators);
event MinDelegationUpdated(uint256 indexed _minDelegationAmount);
event UndelegateLockupDurationUpdated(uint256 indexed _undelegateLockupDuration);
event GovernanceAddressUpdated(address indexed _newGovernanceAddress);
event StakingAddressUpdated(address indexed _newStakingAddress);
event ServiceProviderFactoryAddressUpdated(address indexed _newServiceProviderFactoryAddress);
event ClaimsManagerAddressUpdated(address indexed _newClaimsManagerAddress);
event RemoveDelegatorLockupDurationUpdated(uint256 indexed _removeDelegatorLockupDuration);
event RemoveDelegatorEvalDurationUpdated(uint256 indexed _removeDelegatorEvalDuration);
// ========================================= New State Variables =========================================
string private constant ERROR_ONLY_SERVICE_PROVIDER = (
"DelegateManager: Only callable by valid Service Provider"
);
// minDelegationAmount per service provider
mapping (address => uint256) private spMinDelegationAmounts;
event SPMinDelegationAmountUpdated(
address indexed _serviceProvider,
uint256 indexed _spMinDelegationAmount
);
// ========================================= Modifier Functions =========================================
/**
* @notice Function to initialize the contract
* @dev stakingAddress must be initialized separately after Staking contract is deployed
* @dev serviceProviderFactoryAddress must be initialized separately after ServiceProviderFactory contract is deployed
* @dev claimsManagerAddress must be initialized separately after ClaimsManager contract is deployed
* @param _tokenAddress - address of ERC20 token that will be claimed
* @param _governanceAddress - Governance proxy address
*/
function initialize (
address _tokenAddress,
address _governanceAddress,
uint256 _undelegateLockupDuration
) public initializer
{
_updateGovernanceAddress(_governanceAddress);
audiusToken = ERC20Mintable(_tokenAddress);
maxDelegators = 175;
// Default minimum delegation amount set to 100AUD
minDelegationAmount = 100 * 10**uint256(18);
InitializableV2.initialize();
_updateUndelegateLockupDuration(_undelegateLockupDuration);
// 1 week = 168hrs * 60 min/hr * 60 sec/min / ~13 sec/block = 46523 blocks
_updateRemoveDelegatorLockupDuration(46523);
// 24hr * 60min/hr * 60sec/min / ~13 sec/block = 6646 blocks
removeDelegatorEvalDuration = 6646;
}
/**
* @notice Allow a delegator to delegate stake to a service provider
* @param _targetSP - address of service provider to delegate to
* @param _amount - amount in wei to delegate
* @return Updated total amount delegated to the service provider by delegator
*/
function delegateStake(
address _targetSP,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
require(
!_claimPending(_targetSP),
"DelegateManager: Delegation not permitted for SP pending claim"
);
address delegator = msg.sender;
Staking stakingContract = Staking(stakingAddress);
// Stake on behalf of target service provider
stakingContract.delegateStakeFor(
_targetSP,
delegator,
_amount
);
// Update list of delegators to SP if necessary
if (!_delegatorExistsForSP(delegator, _targetSP)) {
// If not found, update list of delegates
spDelegateInfo[_targetSP].delegators.push(delegator);
require(
spDelegateInfo[_targetSP].delegators.length <= maxDelegators,
"DelegateManager: Maximum delegators exceeded"
);
}
// Update following values in storage through helper
// totalServiceProviderDelegatedStake = current sp total + new amount,
// totalStakedForSpFromDelegator = current delegator total for sp + new amount,
// totalDelegatorStake = current delegator total + new amount
_updateDelegatorStake(
delegator,
_targetSP,
spDelegateInfo[_targetSP].totalDelegatedStake.add(_amount),
delegateInfo[delegator][_targetSP].add(_amount),
delegatorTotalStake[delegator].add(_amount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
require(
(delegateInfo[delegator][_targetSP] >= minDelegationAmount &&
delegateInfo[delegator][_targetSP] >= spMinDelegationAmounts[_targetSP]
),
ERROR_MINIMUM_DELEGATION
);
// Validate balance
ServiceProviderFactory(
serviceProviderFactoryAddress
).validateAccountStakeBalance(_targetSP);
emit IncreaseDelegatedStake(
delegator,
_targetSP,
_amount
);
// Return new total
return delegateInfo[delegator][_targetSP];
}
/**
* @notice Submit request for undelegation
* @param _target - address of service provider to undelegate stake from
* @param _amount - amount in wei to undelegate
* @return Updated total amount delegated to the service provider by delegator
*/
function requestUndelegateStake(
address _target,
uint256 _amount
) external returns (uint256)
{
_requireIsInitialized();
_requireClaimsManagerAddressIsSet();
require(
_amount > 0,
"DelegateManager: Requested undelegate stake amount must be greater than zero"
);
require(
!_claimPending(_target),
"DelegateManager: Undelegate request not permitted for SP pending claim"
);
address delegator = msg.sender;
require(
_delegatorExistsForSP(delegator, _target),
ERROR_DELEGATOR_STAKE
);
// Confirm no pending delegation request
require(
!_undelegateRequestIsPending(delegator),
"DelegateManager: No pending lockup expected"
);
// Ensure valid bounds
uint256 currentlyDelegatedToSP = delegateInfo[delegator][_target];
require(
_amount <= currentlyDelegatedToSP,
"DelegateManager: Cannot decrease greater than currently staked for this ServiceProvider"
);
// Submit updated request for sender, with target sp, undelegate amount, target expiry block
uint256 lockupExpiryBlock = block.number.add(undelegateLockupDuration);
_updateUndelegateStakeRequest(
delegator,
_target,
_amount,
lockupExpiryBlock
);
// Update total locked for this service provider, increasing by unstake amount
_updateServiceProviderLockupAmount(
_target,
spDelegateInfo[_target].totalLockedUpStake.add(_amount)
);
emit UndelegateStakeRequested(delegator, _target, _amount, lockupExpiryBlock);
return delegateInfo[delegator][_target].sub(_amount);
}
/**
* @notice Cancel undelegation request
*/
function cancelUndelegateStakeRequest() external {
_requireIsInitialized();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
uint256 unstakeAmount = undelegateRequests[delegator].amount;
address unlockFundsSP = undelegateRequests[delegator].serviceProvider;
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
unlockFundsSP,
spDelegateInfo[unlockFundsSP].totalLockedUpStake.sub(unstakeAmount)
);
// Remove pending request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestCancelled(delegator, unlockFundsSP, unstakeAmount);
}
/**
* @notice Finalize undelegation request and withdraw stake
* @return New total amount currently staked after stake has been undelegated
*/
function undelegateStake() external returns (uint256) {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
address delegator = msg.sender;
// Confirm pending delegation request
require(
_undelegateRequestIsPending(delegator),
"DelegateManager: Pending lockup expected"
);
// Confirm lockup expiry has expired
require(
undelegateRequests[delegator].lockupExpiryBlock <= block.number,
"DelegateManager: Lockup must be expired"
);
// Confirm no pending claim for this service provider
require(
!_claimPending(undelegateRequests[delegator].serviceProvider),
"DelegateManager: Undelegate not permitted for SP pending claim"
);
address serviceProvider = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
serviceProvider,
delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
delegator,
serviceProvider,
spDelegateInfo[serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[delegator][serviceProvider].sub(unstakeAmount),
delegatorTotalStake[delegator].sub(unstakeAmount)
);
// Need to ensure delegationAmount is >= both minDelegationAmount and spMinDelegationAmount
// since spMinDelegationAmount by default is 0
// Only exception is when delegating entire stake down to 0
require(
(
delegateInfo[delegator][serviceProvider] >= minDelegationAmount &&
delegateInfo[delegator][serviceProvider] >= spMinDelegationAmounts[serviceProvider]
) || delegateInfo[delegator][serviceProvider] == 0,
ERROR_MINIMUM_DELEGATION
);
// Remove from delegators list if no delegated stake remaining
if (delegateInfo[delegator][serviceProvider] == 0) {
_removeFromDelegatorsList(serviceProvider, delegator);
}
// Update total locked for this service provider, decreasing by unstake amount
_updateServiceProviderLockupAmount(
serviceProvider,
spDelegateInfo[serviceProvider].totalLockedUpStake.sub(unstakeAmount)
);
// Reset undelegate request
_resetUndelegateStakeRequest(delegator);
emit UndelegateStakeRequestEvaluated(
delegator,
serviceProvider,
unstakeAmount
);
// Need to update service provider's `validBounds` flag
// Only way to do this is through `SPFactory.updateServiceProviderStake()`
// So we call it with the existing `spDeployerStake`
(uint256 spDeployerStake,,,,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress).getServiceProviderDetails(serviceProvider)
);
ServiceProviderFactory(serviceProviderFactoryAddress).updateServiceProviderStake(
serviceProvider, spDeployerStake
);
// Return new total
return delegateInfo[delegator][serviceProvider];
}
/**
* @notice Claim and distribute rewards to delegators and service provider as necessary
* @param _serviceProvider - Provider for which rewards are being distributed
* @dev Factors in service provider rewards from delegator and transfers deployer cut
*/
function claimRewards(address _serviceProvider) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
_requireClaimsManagerAddressIsSet();
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Total rewards = (balance in staking) - ((balance in sp factory) + (balance in delegate manager))
(
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
) = _validateClaimRewards(spFactory, _serviceProvider);
// No-op if balance is already equivalent
// This case can occur if no rewards due to bound violation or all stake is locked
if (totalRewards == 0) {
return;
}
uint256 totalDelegatedStakeIncrease = _distributeDelegateRewards(
_serviceProvider,
totalActiveFunds,
totalRewards,
deployerCut,
spFactory.getServiceProviderDeployerCutBase()
);
// Update total delegated to this SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = (
spDelegateInfo[_serviceProvider].totalDelegatedStake.add(totalDelegatedStakeIncrease)
);
// spRewardShare represents rewards directly allocated to service provider for their stake
// Value is computed as the remainder of total minted rewards after distribution to
// delegators, eliminating any potential for precision loss.
uint256 spRewardShare = totalRewards.sub(totalDelegatedStakeIncrease);
// Adding the newly calculated reward share to current balance
uint256 newSPFactoryBalance = totalBalanceInSPFactory.add(spRewardShare);
require(
totalBalanceInStaking == newSPFactoryBalance.add(spDelegateInfo[_serviceProvider].totalDelegatedStake),
"DelegateManager: claimRewards amount mismatch"
);
spFactory.updateServiceProviderStake(
_serviceProvider,
newSPFactoryBalance
);
}
/**
* @notice Reduce current stake amount
* @dev Only callable by governance. Slashes service provider and delegators equally
* @param _amount - amount in wei to slash
* @param _slashAddress - address of service provider to slash
*/
function slash(uint256 _amount, address _slashAddress)
external
{
_requireIsInitialized();
_requireStakingAddressIsSet();
_requireServiceProviderFactoryAddressIsSet();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
Staking stakingContract = Staking(stakingAddress);
ServiceProviderFactory spFactory = ServiceProviderFactory(serviceProviderFactoryAddress);
// Amount stored in staking contract for owner
uint256 totalBalanceInStakingPreSlash = stakingContract.totalStakedFor(_slashAddress);
require(
(totalBalanceInStakingPreSlash >= _amount),
"DelegateManager: Cannot slash more than total currently staked"
);
// Cancel any withdrawal request for this service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_slashAddress);
if (spLockedStake > 0) {
spFactory.cancelDecreaseStakeRequest(_slashAddress);
}
// Amount in sp factory for slash target
(uint256 totalBalanceInSPFactory,,,,,) = (
spFactory.getServiceProviderDetails(_slashAddress)
);
require(
totalBalanceInSPFactory > 0,
"DelegateManager: Service Provider stake required"
);
// Decrease value in Staking contract
// A value of zero slash will fail in staking, reverting this transaction
stakingContract.slash(_amount, _slashAddress);
uint256 totalBalanceInStakingAfterSlash = stakingContract.totalStakedFor(_slashAddress);
// Emit slash event
emit Slash(_slashAddress, _amount, totalBalanceInStakingAfterSlash);
uint256 totalDelegatedStakeDecrease = 0;
// For each delegator and deployer, recalculate new value
// newStakeAmount = newStakeAmount * (oldStakeAmount / totalBalancePreSlash)
for (uint256 i = 0; i < spDelegateInfo[_slashAddress].delegators.length; i++) {
address delegator = spDelegateInfo[_slashAddress].delegators[i];
uint256 preSlashDelegateStake = delegateInfo[delegator][_slashAddress];
uint256 newDelegateStake = (
totalBalanceInStakingAfterSlash.mul(preSlashDelegateStake)
).div(totalBalanceInStakingPreSlash);
// slashAmountForDelegator = preSlashDelegateStake - newDelegateStake;
delegateInfo[delegator][_slashAddress] = (
delegateInfo[delegator][_slashAddress].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total stake for delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].sub(preSlashDelegateStake.sub(newDelegateStake))
);
// Update total decrease amount
totalDelegatedStakeDecrease = (
totalDelegatedStakeDecrease.add(preSlashDelegateStake.sub(newDelegateStake))
);
// Check for any locked up funds for this slashed delegator
// Slash overrides any pending withdrawal requests
if (undelegateRequests[delegator].amount != 0) {
address unstakeSP = undelegateRequests[delegator].serviceProvider;
uint256 unstakeAmount = undelegateRequests[delegator].amount;
// Remove pending request
_updateServiceProviderLockupAmount(
unstakeSP,
spDelegateInfo[unstakeSP].totalLockedUpStake.sub(unstakeAmount)
);
_resetUndelegateStakeRequest(delegator);
}
}
// Update total delegated to this SP
spDelegateInfo[_slashAddress].totalDelegatedStake = (
spDelegateInfo[_slashAddress].totalDelegatedStake.sub(totalDelegatedStakeDecrease)
);
// Remaining decrease applied to service provider
uint256 totalStakeDecrease = (
totalBalanceInStakingPreSlash.sub(totalBalanceInStakingAfterSlash)
);
uint256 totalSPFactoryBalanceDecrease = (
totalStakeDecrease.sub(totalDelegatedStakeDecrease)
);
spFactory.updateServiceProviderStake(
_slashAddress,
totalBalanceInSPFactory.sub(totalSPFactoryBalanceDecrease)
);
}
/**
* @notice Initiate forcible removal of a delegator
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function requestRemoveDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] == 0,
"DelegateManager: Pending remove delegator request"
);
require(
_delegatorExistsForSP(_delegator, _serviceProvider),
ERROR_DELEGATOR_STAKE
);
// Update lockup
removeDelegatorRequests[_serviceProvider][_delegator] = (
block.number + removeDelegatorLockupDuration
);
emit RemoveDelegatorRequested(
_serviceProvider,
_delegator,
removeDelegatorRequests[_serviceProvider][_delegator]
);
}
/**
* @notice Cancel pending removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
*/
function cancelRemoveDelegatorRequest(address _serviceProvider, address _delegator) external {
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestCancelled(_serviceProvider, _delegator);
}
/**
* @notice Evaluate removeDelegator request
* @param _serviceProvider - address of service provider
* @param _delegator - address of delegator
* @return Updated total amount delegated to the service provider by delegator
*/
function removeDelegator(address _serviceProvider, address _delegator) external {
_requireIsInitialized();
_requireStakingAddressIsSet();
require(
msg.sender == _serviceProvider || msg.sender == governanceAddress,
ERROR_ONLY_SP_GOVERNANCE
);
require(
removeDelegatorRequests[_serviceProvider][_delegator] != 0,
"DelegateManager: No pending request"
);
// Enforce lockup expiry block
require(
block.number >= removeDelegatorRequests[_serviceProvider][_delegator],
"DelegateManager: Lockup must be expired"
);
// Enforce evaluation window for request
require(
block.number < removeDelegatorRequests[_serviceProvider][_delegator] + removeDelegatorEvalDuration,
"DelegateManager: RemoveDelegator evaluation window expired"
);
uint256 unstakeAmount = delegateInfo[_delegator][_serviceProvider];
// Unstake on behalf of target service provider
Staking(stakingAddress).undelegateStakeFor(
_serviceProvider,
_delegator,
unstakeAmount
);
// Update total delegated for SP
// totalServiceProviderDelegatedStake - total amount delegated to service provider
// totalStakedForSpFromDelegator - amount staked from this delegator to targeted service provider
_updateDelegatorStake(
_delegator,
_serviceProvider,
spDelegateInfo[_serviceProvider].totalDelegatedStake.sub(unstakeAmount),
delegateInfo[_delegator][_serviceProvider].sub(unstakeAmount),
delegatorTotalStake[_delegator].sub(unstakeAmount)
);
if (
_undelegateRequestIsPending(_delegator) &&
undelegateRequests[_delegator].serviceProvider == _serviceProvider
) {
// Remove pending request information
_updateServiceProviderLockupAmount(
_serviceProvider,
spDelegateInfo[_serviceProvider].totalLockedUpStake.sub(undelegateRequests[_delegator].amount)
);
_resetUndelegateStakeRequest(_delegator);
}
// Remove from list of delegators
_removeFromDelegatorsList(_serviceProvider, _delegator);
// Reset lockup expiry
removeDelegatorRequests[_serviceProvider][_delegator] = 0;
emit RemoveDelegatorRequestEvaluated(_serviceProvider, _delegator, unstakeAmount);
}
/**
* @notice SP can update their minDelegationAmount
* @param _serviceProvider - address of service provider
* @param _spMinDelegationAmount - new minDelegationAmount for SP
* @notice does not enforce _spMinDelegationAmount >= minDelegationAmount since not necessary
* delegateStake() and undelegateStake() always take the max of both already
*/
function updateSPMinDelegationAmount(
address _serviceProvider,
uint256 _spMinDelegationAmount
) external {
_requireIsInitialized();
require(msg.sender == _serviceProvider, ERROR_ONLY_SERVICE_PROVIDER);
/**
* Ensure _serviceProvider is a valid SP
* No objective source of truth, closest heuristic is numEndpoints > 0
*/
(,,, uint256 numEndpoints,,) = (
ServiceProviderFactory(serviceProviderFactoryAddress)
.getServiceProviderDetails(_serviceProvider)
);
require(numEndpoints > 0, ERROR_ONLY_SERVICE_PROVIDER);
spMinDelegationAmounts[_serviceProvider] = _spMinDelegationAmount;
emit SPMinDelegationAmountUpdated(_serviceProvider, _spMinDelegationAmount);
}
/**
* @notice Update duration for undelegate request lockup
* @param _duration - new lockup duration
*/
function updateUndelegateLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateUndelegateLockupDuration(_duration);
emit UndelegateLockupDurationUpdated(_duration);
}
/**
* @notice Update maximum delegators allowed
* @param _maxDelegators - new max delegators
*/
function updateMaxDelegators(uint256 _maxDelegators) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
maxDelegators = _maxDelegators;
emit MaxDelegatorsUpdated(_maxDelegators);
}
/**
* @notice Update minimum delegation amount
* @param _minDelegationAmount - min new min delegation amount
*/
function updateMinDelegationAmount(uint256 _minDelegationAmount) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
minDelegationAmount = _minDelegationAmount;
emit MinDelegationUpdated(_minDelegationAmount);
}
/**
* @notice Update remove delegator lockup duration
* @param _duration - new lockup duration
*/
function updateRemoveDelegatorLockupDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateRemoveDelegatorLockupDuration(_duration);
emit RemoveDelegatorLockupDurationUpdated(_duration);
}
/**
* @notice Update remove delegator evaluation window duration
* @param _duration - new window duration
*/
function updateRemoveDelegatorEvalDuration(uint256 _duration) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
removeDelegatorEvalDuration = _duration;
emit RemoveDelegatorEvalDurationUpdated(_duration);
}
/**
* @notice Set the Governance address
* @dev Only callable by Governance address
* @param _governanceAddress - address for new Governance contract
*/
function setGovernanceAddress(address _governanceAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
_updateGovernanceAddress(_governanceAddress);
governanceAddress = _governanceAddress;
emit GovernanceAddressUpdated(_governanceAddress);
}
/**
* @notice Set the Staking address
* @dev Only callable by Governance address
* @param _stakingAddress - address for new Staking contract
*/
function setStakingAddress(address _stakingAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
stakingAddress = _stakingAddress;
emit StakingAddressUpdated(_stakingAddress);
}
/**
* @notice Set the ServiceProviderFactory address
* @dev Only callable by Governance address
* @param _spFactory - address for new ServiceProviderFactory contract
*/
function setServiceProviderFactoryAddress(address _spFactory) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
serviceProviderFactoryAddress = _spFactory;
emit ServiceProviderFactoryAddressUpdated(_spFactory);
}
/**
* @notice Set the ClaimsManager address
* @dev Only callable by Governance address
* @param _claimsManagerAddress - address for new ClaimsManager contract
*/
function setClaimsManagerAddress(address _claimsManagerAddress) external {
_requireIsInitialized();
require(msg.sender == governanceAddress, ERROR_ONLY_GOVERNANCE);
claimsManagerAddress = _claimsManagerAddress;
emit ClaimsManagerAddressUpdated(_claimsManagerAddress);
}
// ========================================= View Functions =========================================
/**
* @notice Get list of delegators for a given service provider
* @param _sp - service provider address
*/
function getDelegatorsList(address _sp)
external view returns (address[] memory)
{
_requireIsInitialized();
return spDelegateInfo[_sp].delegators;
}
/**
* @notice Get total delegation from a given address
* @param _delegator - delegator address
*/
function getTotalDelegatorStake(address _delegator)
external view returns (uint256)
{
_requireIsInitialized();
return delegatorTotalStake[_delegator];
}
/// @notice Get total amount delegated to a service provider
function getTotalDelegatedToServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalDelegatedStake;
}
/// @notice Get total delegated stake locked up for a service provider
function getTotalLockedDelegationForServiceProvider(address _sp)
external view returns (uint256)
{
_requireIsInitialized();
return spDelegateInfo[_sp].totalLockedUpStake;
}
/// @notice Get total currently staked for a delegator, for a given service provider
function getDelegatorStakeForServiceProvider(address _delegator, address _serviceProvider)
external view returns (uint256)
{
_requireIsInitialized();
return delegateInfo[_delegator][_serviceProvider];
}
/**
* @notice Get status of pending undelegate request for a given address
* @param _delegator - address of the delegator
*/
function getPendingUndelegateRequest(address _delegator)
external view returns (address target, uint256 amount, uint256 lockupExpiryBlock)
{
_requireIsInitialized();
UndelegateStakeRequest memory req = undelegateRequests[_delegator];
return (req.serviceProvider, req.amount, req.lockupExpiryBlock);
}
/**
* @notice Get status of pending remove delegator request for a given address
* @param _serviceProvider - address of the service provider
* @param _delegator - address of the delegator
* @return - current lockup expiry block for remove delegator request
*/
function getPendingRemoveDelegatorRequest(
address _serviceProvider,
address _delegator
) external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorRequests[_serviceProvider][_delegator];
}
/**
* @notice Get minDelegationAmount for given SP
* @param _serviceProvider - address of the service provider
* @return - minDelegationAmount for given SP
*/
function getSPMinDelegationAmount(address _serviceProvider) external view returns (uint256) {
return spMinDelegationAmounts[_serviceProvider];
}
/// @notice Get current undelegate lockup duration
function getUndelegateLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return undelegateLockupDuration;
}
/// @notice Current maximum delegators
function getMaxDelegators()
external view returns (uint256)
{
_requireIsInitialized();
return maxDelegators;
}
/// @notice Get minimum delegation amount
function getMinDelegationAmount()
external view returns (uint256)
{
_requireIsInitialized();
return minDelegationAmount;
}
/// @notice Get the duration for remove delegator request lockup
function getRemoveDelegatorLockupDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorLockupDuration;
}
/// @notice Get the duration for evaluation of remove delegator operations
function getRemoveDelegatorEvalDuration()
external view returns (uint256)
{
_requireIsInitialized();
return removeDelegatorEvalDuration;
}
/// @notice Get the Governance address
function getGovernanceAddress() external view returns (address) {
_requireIsInitialized();
return governanceAddress;
}
/// @notice Get the ServiceProviderFactory address
function getServiceProviderFactoryAddress() external view returns (address) {
_requireIsInitialized();
return serviceProviderFactoryAddress;
}
/// @notice Get the ClaimsManager address
function getClaimsManagerAddress() external view returns (address) {
_requireIsInitialized();
return claimsManagerAddress;
}
/// @notice Get the Staking address
function getStakingAddress() external view returns (address)
{
_requireIsInitialized();
return stakingAddress;
}
// ========================================= Internal functions =========================================
/**
* @notice Helper function for claimRewards to get balances from Staking contract
and do validation
* @param spFactory - reference to ServiceProviderFactory contract
* @param _serviceProvider - address for which rewards are being claimed
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalActiveFunds, spLockedStake, totalRewards, deployerCut)
*/
function _validateClaimRewards(ServiceProviderFactory spFactory, address _serviceProvider)
internal returns (
uint256 totalBalanceInStaking,
uint256 totalBalanceInSPFactory,
uint256 totalActiveFunds,
uint256 totalRewards,
uint256 deployerCut
)
{
// Account for any pending locked up stake for the service provider
(uint256 spLockedStake,) = spFactory.getPendingDecreaseStakeRequest(_serviceProvider);
uint256 totalLockedUpStake = (
spDelegateInfo[_serviceProvider].totalLockedUpStake.add(spLockedStake)
);
// Process claim for msg.sender
// Total locked parameter is equal to delegate locked up stake + service provider locked up stake
uint256 mintedRewards = ClaimsManager(claimsManagerAddress).processClaim(
_serviceProvider,
totalLockedUpStake
);
// Amount stored in staking contract for owner
totalBalanceInStaking = Staking(stakingAddress).totalStakedFor(_serviceProvider);
// Amount in sp factory for claimer
(
totalBalanceInSPFactory,
deployerCut,
,,,
) = spFactory.getServiceProviderDetails(_serviceProvider);
// Require active stake to claim any rewards
// Amount in delegate manager staked to service provider
uint256 totalBalanceOutsideStaking = (
totalBalanceInSPFactory.add(spDelegateInfo[_serviceProvider].totalDelegatedStake)
);
totalActiveFunds = totalBalanceOutsideStaking.sub(totalLockedUpStake);
require(
mintedRewards == totalBalanceInStaking.sub(totalBalanceOutsideStaking),
"DelegateManager: Reward amount mismatch"
);
// Emit claim event
emit Claim(_serviceProvider, totalRewards, totalBalanceInStaking);
return (
totalBalanceInStaking,
totalBalanceInSPFactory,
totalActiveFunds,
mintedRewards,
deployerCut
);
}
/**
* @notice Perform state updates when a delegate stake has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _totalServiceProviderDelegatedStake - total delegated to this service provider
* @param _totalStakedForSpFromDelegator - total delegated to this service provider by delegator
* @param _totalDelegatorStake - total delegated from this delegator address
*/
function _updateDelegatorStake(
address _delegator,
address _serviceProvider,
uint256 _totalServiceProviderDelegatedStake,
uint256 _totalStakedForSpFromDelegator,
uint256 _totalDelegatorStake
) internal
{
// Update total delegated for SP
spDelegateInfo[_serviceProvider].totalDelegatedStake = _totalServiceProviderDelegatedStake;
// Update amount staked from this delegator to targeted service provider
delegateInfo[_delegator][_serviceProvider] = _totalStakedForSpFromDelegator;
// Update total delegated from this delegator
_updateDelegatorTotalStake(_delegator, _totalDelegatorStake);
}
/**
* @notice Reset pending undelegate stake request
* @param _delegator - address of delegator
*/
function _resetUndelegateStakeRequest(address _delegator) internal
{
_updateUndelegateStakeRequest(_delegator, address(0), 0, 0);
}
/**
* @notice Perform updates when undelegate request state has changed
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @param _amount - amount being undelegated
* @param _lockupExpiryBlock - block at which stake can be undelegated
*/
function _updateUndelegateStakeRequest(
address _delegator,
address _serviceProvider,
uint256 _amount,
uint256 _lockupExpiryBlock
) internal
{
// Update lockup information
undelegateRequests[_delegator] = UndelegateStakeRequest({
lockupExpiryBlock: _lockupExpiryBlock,
amount: _amount,
serviceProvider: _serviceProvider
});
}
/**
* @notice Update total amount delegated from an address
* @param _delegator - address of service provider
* @param _amount - updated delegator total
*/
function _updateDelegatorTotalStake(address _delegator, uint256 _amount) internal
{
delegatorTotalStake[_delegator] = _amount;
}
/**
* @notice Update amount currently locked up for this service provider
* @param _serviceProvider - address of service provider
* @param _updatedLockupAmount - updated lock up amount
*/
function _updateServiceProviderLockupAmount(
address _serviceProvider,
uint256 _updatedLockupAmount
) internal
{
spDelegateInfo[_serviceProvider].totalLockedUpStake = _updatedLockupAmount;
}
function _removeFromDelegatorsList(address _serviceProvider, address _delegator) internal
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
// Overwrite and shrink delegators list
spDelegateInfo[_serviceProvider].delegators[i] = spDelegateInfo[_serviceProvider].delegators[spDelegateInfo[_serviceProvider].delegators.length - 1];
spDelegateInfo[_serviceProvider].delegators.length--;
break;
}
}
}
/**
* @notice Helper function to distribute rewards to any delegators
* @param _sp - service provider account tracked in staking
* @param _totalActiveFunds - total funds minus any locked stake
* @param _totalRewards - total rewaards generated in this round
* @param _deployerCut - service provider cut of delegate rewards, defined as deployerCut / deployerCutBase
* @param _deployerCutBase - denominator value for calculating service provider cut as a %
* @return (totalBalanceInStaking, totalBalanceInSPFactory, totalBalanceOutsideStaking)
*/
function _distributeDelegateRewards(
address _sp,
uint256 _totalActiveFunds,
uint256 _totalRewards,
uint256 _deployerCut,
uint256 _deployerCutBase
)
internal returns (uint256 totalDelegatedStakeIncrease)
{
// Traverse all delegates and calculate their rewards
// As each delegate reward is calculated, increment SP cut reward accordingly
for (uint256 i = 0; i < spDelegateInfo[_sp].delegators.length; i++) {
address delegator = spDelegateInfo[_sp].delegators[i];
uint256 delegateStakeToSP = delegateInfo[delegator][_sp];
// Subtract any locked up stake
if (undelegateRequests[delegator].serviceProvider == _sp) {
delegateStakeToSP = delegateStakeToSP.sub(undelegateRequests[delegator].amount);
}
// Calculate rewards by ((delegateStakeToSP / totalActiveFunds) * totalRewards)
uint256 rewardsPriorToSPCut = (
delegateStakeToSP.mul(_totalRewards)
).div(_totalActiveFunds);
// Multiply by deployer cut fraction to calculate reward for SP
// Operation constructed to perform all multiplication prior to division
// uint256 spDeployerCut = (rewardsPriorToSPCut * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards) / totalActiveFunds) * deployerCut ) / (deployerCutBase);
// = ((delegateStakeToSP * totalRewards * deployerCut) / totalActiveFunds ) / (deployerCutBase);
// = (delegateStakeToSP * totalRewards * deployerCut) / (deployerCutBase * totalActiveFunds);
uint256 spDeployerCut = (
(delegateStakeToSP.mul(_totalRewards)).mul(_deployerCut)
).div(
_totalActiveFunds.mul(_deployerCutBase)
);
// Increase total delegate reward in DelegateManager
// Subtract SP reward from rewards to calculate delegate reward
// delegateReward = rewardsPriorToSPCut - spDeployerCut;
delegateInfo[delegator][_sp] = (
delegateInfo[delegator][_sp].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
// Update total for this delegator
_updateDelegatorTotalStake(
delegator,
delegatorTotalStake[delegator].add(rewardsPriorToSPCut.sub(spDeployerCut))
);
totalDelegatedStakeIncrease = (
totalDelegatedStakeIncrease.add(rewardsPriorToSPCut.sub(spDeployerCut))
);
}
return (totalDelegatedStakeIncrease);
}
/**
* @notice Set the governance address after confirming contract identity
* @param _governanceAddress - Incoming governance address
*/
function _updateGovernanceAddress(address _governanceAddress) internal {
require(
Governance(_governanceAddress).isGovernanceAddress() == true,
"DelegateManager: _governanceAddress is not a valid governance contract"
);
governanceAddress = _governanceAddress;
}
/**
* @notice Set the remove delegator lockup duration after validating against governance
* @param _duration - Incoming remove delegator duration value
*/
function _updateRemoveDelegatorLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: removeDelegatorLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
removeDelegatorLockupDuration = _duration;
}
/**
* @notice Set the undelegate lockup duration after validating against governance
* @param _duration - Incoming undelegate lockup duration value
*/
function _updateUndelegateLockupDuration(uint256 _duration) internal {
Governance governance = Governance(governanceAddress);
require(
_duration > governance.getVotingPeriod() + governance.getExecutionDelay(),
"DelegateManager: undelegateLockupDuration duration must be greater than governance votingPeriod + executionDelay"
);
undelegateLockupDuration = _duration;
}
/**
* @notice Returns if delegator has delegated to a service provider
* @param _delegator - address of delegator
* @param _serviceProvider - address of service provider
* @return boolean indicating whether delegator exists for service provider
*/
function _delegatorExistsForSP(
address _delegator,
address _serviceProvider
) internal view returns (bool)
{
for (uint256 i = 0; i < spDelegateInfo[_serviceProvider].delegators.length; i++) {
if (spDelegateInfo[_serviceProvider].delegators[i] == _delegator) {
return true;
}
}
// Not found
return false;
}
/**
* @notice Determine if a claim is pending for this service provider
* @param _sp - address of service provider
* @return boolean indicating whether a claim is pending
*/
function _claimPending(address _sp) internal view returns (bool) {
ClaimsManager claimsManager = ClaimsManager(claimsManagerAddress);
return claimsManager.claimPending(_sp);
}
/**
* @notice Determine if a decrease request has been initiated
* @param _delegator - address of delegator
* @return boolean indicating whether a decrease request is pending
*/
function _undelegateRequestIsPending(address _delegator) internal view returns (bool)
{
return (
(undelegateRequests[_delegator].lockupExpiryBlock != 0) &&
(undelegateRequests[_delegator].amount != 0) &&
(undelegateRequests[_delegator].serviceProvider != address(0))
);
}
// ========================================= Private Functions =========================================
function _requireStakingAddressIsSet() private view {
require(
stakingAddress != address(0x00),
"DelegateManager: stakingAddress is not set"
);
}
function _requireServiceProviderFactoryAddressIsSet() private view {
require(
serviceProviderFactoryAddress != address(0x00),
"DelegateManager: serviceProviderFactoryAddress is not set"
);
}
function _requireClaimsManagerAddressIsSet() private view {
require(
claimsManagerAddress != address(0x00),
"DelegateManager: claimsManagerAddress is not set"
);
}
} | * @notice Get information about a service provider given their address @param _serviceProvider - address of service provider/ | function getServiceProviderDetails(address _serviceProvider)
external view returns (
uint256 deployerStake,
uint256 deployerCut,
bool validBounds,
uint256 numberOfEndpoints,
uint256 minAccountStake,
uint256 maxAccountStake)
{
_requireIsInitialized();
return (
spDetails[_serviceProvider].deployerStake,
spDetails[_serviceProvider].deployerCut,
spDetails[_serviceProvider].validBounds,
spDetails[_serviceProvider].numberOfEndpoints,
spDetails[_serviceProvider].minAccountStake,
spDetails[_serviceProvider].maxAccountStake
);
}
| 1,231,893 | [
1,
967,
1779,
2973,
279,
1156,
2893,
864,
3675,
1758,
225,
389,
3278,
2249,
300,
1758,
434,
1156,
2893,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
6373,
2249,
3790,
12,
2867,
389,
3278,
2249,
13,
203,
565,
3903,
1476,
1135,
261,
203,
3639,
2254,
5034,
7286,
264,
510,
911,
16,
203,
3639,
2254,
5034,
7286,
264,
15812,
16,
203,
3639,
1426,
923,
5694,
16,
203,
3639,
2254,
5034,
7922,
10357,
16,
203,
3639,
2254,
5034,
1131,
3032,
510,
911,
16,
203,
3639,
2254,
5034,
943,
3032,
510,
911,
13,
203,
565,
288,
203,
3639,
389,
6528,
2520,
11459,
5621,
203,
203,
3639,
327,
261,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
12411,
264,
510,
911,
16,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
12411,
264,
15812,
16,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
877,
5694,
16,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
2696,
951,
10357,
16,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
1154,
3032,
510,
911,
16,
203,
5411,
1694,
3790,
63,
67,
3278,
2249,
8009,
1896,
3032,
510,
911,
203,
3639,
11272,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "./IController.sol";
import "./IManager.sol";
import "./zeppelin/Pausable.sol";
contract Controller is Pausable, IController {
// Track information about a registered contract
struct ContractInfo {
address contractAddress; // Address of contract
bytes20 gitCommitHash; // SHA1 hash of head Git commit during registration of this contract
}
// Track contract ids and contract info
mapping(bytes32 => ContractInfo) private registry;
constructor() {
// Start system as paused
paused = true;
}
/**
* @notice Register contract id and mapped address
* @param _id Contract id (keccak256 hash of contract name)
* @param _contractAddress Contract address
*/
function setContractInfo(
bytes32 _id,
address _contractAddress,
bytes20 _gitCommitHash
) external override onlyOwner {
registry[_id].contractAddress = _contractAddress;
registry[_id].gitCommitHash = _gitCommitHash;
emit SetContractInfo(_id, _contractAddress, _gitCommitHash);
}
/**
* @notice Update contract's controller
* @param _id Contract id (keccak256 hash of contract name)
* @param _controller Controller address
*/
function updateController(bytes32 _id, address _controller) external override onlyOwner {
return IManager(registry[_id].contractAddress).setController(_controller);
}
/**
* @notice Return contract info for a given contract id
* @param _id Contract id (keccak256 hash of contract name)
*/
function getContractInfo(bytes32 _id) public view returns (address, bytes20) {
return (registry[_id].contractAddress, registry[_id].gitCommitHash);
}
/**
* @notice Get contract address for an id
* @param _id Contract id
*/
function getContract(bytes32 _id) public view override returns (address) {
return registry[_id].contractAddress;
}
}
| SHA1 hash of head Git commit during registration of this contract
| bytes20 gitCommitHash; | 5,496,900 | [
1,
8325,
21,
1651,
434,
910,
6646,
3294,
4982,
7914,
434,
333,
6835,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
1731,
3462,
5071,
5580,
2310,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.24;
import "./ERC721BasicToken.sol";
contract BrainpartToken is ERC721BasicToken {
struct Brainpart {
// Keep dna based on timestamp
string dna;
string category;
string subCategory;
string strength;
string uri;
}
Brainpart[] public brainparts;
address public owner;
constructor() public {
owner = msg.sender;
}
function totalSupply()
public view returns(uint256) {
return brainparts.length;
}
function createBrainpart(
string birthTimeStamp, string category,
string subCategory,string strength, string uri, address to_)
public onlyOwner payable {
// Making sure we are being paid apt amount
// uint256 price = getPrice("category");
//require(msg.value >= price);
// Adding collectible to contract set
uint id = brainparts.length;
brainparts.push(Brainpart(birthTimeStamp, category, subCategory, strength, uri));
// Minting a crypto collectible
_mint(to_, id);
// Transferring excess back to sender
// if (msg.value > price) {
// uint256 priceExcess = msg.value - price;
// msg.sender.transfer(priceExcess);
// }
}
// Get brainpart uri for brainpart of a particular id
function getBrainpartUri(uint256 id)
public view returns(string) {
return brainparts[id].uri;
}
function getBrainpartStrength(uint256 id)
public view returns(string) {
return brainparts[id].strength;
}
function setStrength(string newStrength, uint256 id)
public onlyOwner {
brainparts[id].strength = newStrength;
}
function withdraw(uint256 amount) onlyOwner
public returns(bool){
address contractAddress = this;
require(amount <= contractAddress.balance);
owner.transfer(amount);
return true;
}
// Makes sure only owner has access
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
// Utility function to get price according to category
function getPrice(string category) private pure returns (uint256) {
if(keccak256(abi.encodePacked(category)) == keccak256("cerebrum")) {
return 0.04 ether;
} else if(keccak256(abi.encodePacked(category)) ==
keccak256(abi.encodePacked("cerebellum"))) {
return 0.03 ether;
} else if(keccak256(abi.encodePacked(category)) ==
keccak256(abi.encodePacked("brainstem"))) {
return 0.02 ether;
} else if(keccak256(abi.encodePacked(category)) ==
keccak256(abi.encodePacked("arterial"))) {
return 0.01 ether;
}
return 0.00 ether;
}
}
| Making sure we are being paid apt amount uint256 price = getPrice("category");require(msg.value >= price); Adding collectible to contract set Minting a crypto collectible Transferring excess back to sender if (msg.value > price) { uint256 priceExcess = msg.value - price; msg.sender.transfer(priceExcess); } | function createBrainpart(
string birthTimeStamp, string category,
string subCategory,string strength, string uri, address to_)
public onlyOwner payable {
uint id = brainparts.length;
brainparts.push(Brainpart(birthTimeStamp, category, subCategory, strength, uri));
_mint(to_, id);
}
| 14,114,129 | [
1,
49,
6159,
3071,
732,
854,
3832,
30591,
279,
337,
3844,
2254,
5034,
6205,
273,
25930,
2932,
4743,
8863,
6528,
12,
3576,
18,
1132,
1545,
6205,
1769,
21240,
3274,
1523,
358,
6835,
444,
490,
474,
310,
279,
8170,
3274,
1523,
2604,
74,
20245,
23183,
1473,
358,
5793,
309,
261,
3576,
18,
1132,
405,
6205,
13,
288,
282,
2254,
5034,
6205,
424,
614,
273,
1234,
18,
1132,
300,
6205,
31,
282,
1234,
18,
15330,
18,
13866,
12,
8694,
424,
614,
1769,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
445,
752,
38,
7596,
2680,
12,
203,
565,
533,
17057,
21536,
16,
533,
3150,
16,
203,
565,
533,
720,
4457,
16,
1080,
21638,
16,
533,
2003,
16,
1758,
358,
67,
13,
203,
565,
1071,
1338,
5541,
8843,
429,
288,
203,
565,
2254,
612,
273,
20970,
6019,
18,
2469,
31,
203,
565,
20970,
6019,
18,
6206,
12,
38,
7596,
2680,
12,
22531,
21536,
16,
3150,
16,
720,
4457,
16,
21638,
16,
2003,
10019,
203,
565,
389,
81,
474,
12,
869,
67,
16,
612,
1769,
203,
225,
289,
203,
203,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
/*
0% Buy | 9% Sell | 24% if sell or send within 24 hours of last buy.
All fee's can not be set higher than these defaults, see code lines 1502 - 1514.
WEBSITE: jinu.us
WHITEPAPER: jinu.us/whitepaper
TELEGRAM & TWITTER: @SavingJohnnyInu
::::::::::: ::::::::::: :::: ::: ::: :::
:+: :+: :+:+: :+: :+: :+:
+:+ +:+ :+:+:+ +:+ +:+ +:+
+#+ +#+ +#+ +:+ +#+ +#+ +:+
+#+ +#+ +#+ +#+#+# +#+ +#+
#+# #+# #+# #+# #+#+# #+# #+#
##### ########### ### #### ########
*/
pragma solidity 0.8.13;
abstract contract Context
{
function _msgSender() internal view virtual returns (address)
{
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata)
{
return msg.data;
}
}
/**
* @dev 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 Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
/**
* @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 this function
* 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, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _createInitialSupply(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
/**
* @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);
}
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SignedSafeMath {
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
return a * b;
}
/**
* @dev Returns the integer division of two signed integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
return a / b;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
return a - b;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
return a + b;
}
}
// 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;
}
}
}
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such an operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 >= type(int128).min && value <= type(int128).max, "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 >= type(int64).min && value <= type(int64).max, "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 >= type(int32).min && value <= type(int32).max, "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 >= type(int16).min && value <= type(int16).max, "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 >= type(int8).min && value <= type(int8).max, "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) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
contract JINU is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
bool public enableEarlySellTax = true;
uint256 public maxSellTransactionAmount = 5000001 * (10**18); // 0.5% of total supply
uint256 public maxBuyTransactionAmount = 5000001 * (10**18); // 0.5% of total supply
uint256 public swapTokensAtAmount = 2000000 * (10**18);
uint256 public maxWalletToken = 10000001 * (10**18); // 1% of total supply
uint256 private buyTotalFees = 0; // Cannot be set higher than 0%
uint256 public sellTotalFees = 9; // Cannot be set higher than 9%
uint256 public earlySellTotalFee = 24; // Cannot be set higher than 24%
// auto burn fee
uint256 public burnFee = 0;
address public deadWallet = 0xD02C364008fF41616A4EDC4a4bf6624e2D3617DD;
// distribute the collected tax percentage wise
uint256 public liquidityPercent = 33; // 33% of total collected tax
uint256 public marketingPercent = 34; // 34% of total collected tax
uint256 public devPercent = 33; // 33% of total collected tax
address payable public marketingWallet = payable(0xD02C364008fF41616A4EDC4a4bf6624e2D3617DD);
address payable public devWallet = payable(0xAF1616873eC604EfE00c5a7c88d1e35c558Cb23A);
// exlcude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
mapping (address => uint256) public lastTxTimestamp;
event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event ExcludeFromFees(address indexed account, bool isExcluded);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensIntoLiqudity,
uint256 ethReceived
);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor() ERC20("Saving Johnny Inu", "JINU") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // pancakeswap v2 router address
// Create a uniswap pair for this new token
address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = _uniswapV2Pair;
_setAutomatedMarketMakerPair(_uniswapV2Pair, true);
// exclude from paying fees or having max transaction amount
excludeFromFees(owner(), true);
excludeFromFees(marketingWallet, true);
excludeFromFees(devWallet, true);
excludeFromFees(address(this), true);
/*
an internal function that is only called here,
and CANNOT be called ever again
*/
_createInitialSupply(owner(), 1000000000 * (10**18));
}
receive() external payable {
}
function updateUniswapV2Router(address newAddress) public onlyOwner {
require(newAddress != address(uniswapV2Router), "KCoin: The router already has that address");
emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router));
uniswapV2Router = IUniswapV2Router02(newAddress);
}
function excludeFromFees(address account, bool excluded) public onlyOwner {
require(_isExcludedFromFees[account] != excluded, "KCoin: Account is already the value of 'excluded'");
_isExcludedFromFees[account] = excluded;
emit ExcludeFromFees(account, excluded);
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "KCoin: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "KCoin: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
emit SetAutomatedMarketMakerPair(pair, value);
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
function _transfer(address from, address to, uint256 amount) internal override
{
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
if(amount == 0) {
super._transfer(from, to, 0);
return;
}
if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) {
require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount.");
uint256 contractBalanceRecepient = balanceOf(to);
require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount.");
lastTxTimestamp[to] = block.timestamp;
}
if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) {
require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount;
if(
overMinTokenBalance &&
!inSwapAndLiquify &&
automatedMarketMakerPairs[to] &&
swapAndLiquifyEnabled
) {
contractTokenBalance = swapTokensAtAmount;
swapAndLiquify(contractTokenBalance);
}
uint256 fees = 0;
uint256 burnShare = 0;
// if any account belongs to _isExcludedFromFee account then remove the fee
if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) {
uint256 _totalFees = buyTotalFees;
if (!automatedMarketMakerPairs[from]) {
uint256 span = block.timestamp-lastTxTimestamp[from];
if(enableEarlySellTax && span <= 24 hours) {
_totalFees = earlySellTotalFee;
}
else if(!enableEarlySellTax) {
_totalFees = sellTotalFees;
}
}
fees = amount.mul(_totalFees).div(100);
burnShare = amount.mul(burnFee).div(100);
if(fees > 0) {
super._transfer(from, address(this), fees);
}
if(burnShare > 0) {
super._transfer(from, deadWallet, burnShare);
}
amount = amount.sub(fees.add(burnShare));
}
super._transfer(from, to, amount);
}
function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap {
uint256 tokensForLiquidity = contractTokenBalance.mul(liquidityPercent).div(100);
// split the Liquidity token balance into halves
uint256 half = tokensForLiquidity.div(2);
uint256 otherHalf = tokensForLiquidity.sub(half);
// capture the contract's current ETH balance.
// this is so that we can capture exactly the amount of ETH that the
// swap creates, and not make the liquidity event include any ETH that
// has been manually sent to the contract
uint256 initialBalance = address(this).balance;
// swap tokens for ETH
swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered
// how much ETH did we just swap into?
uint256 newBalance = address(this).balance.sub(initialBalance);
// add liquidity to uniswap
addLiquidity(otherHalf, newBalance);
// swap and Send Eth to marketing, dev wallets
swapTokensForEth(contractTokenBalance.sub(tokensForLiquidity));
marketingWallet.transfer(address(this).balance.mul(marketingPercent).div(marketingPercent.add(devPercent)));
devWallet.transfer(address(this).balance);
emit SwapAndLiquify(half, newBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) {
_approve(address(this), address(uniswapV2Router), ~uint256(0));
}
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
// add the liquidity
uniswapV2Router.addLiquidityETH{value: ethAmount}(
address(this),
tokenAmount,
0, // slippage is unavoidable
0, // slippage is unavoidable
owner(),
block.timestamp
);
}
function setMaxSellTransaction(uint256 _maxSellTxAmount) public onlyOwner {
maxSellTransactionAmount = _maxSellTxAmount;
require(maxSellTransactionAmount>totalSupply().div(1000), "value is too low");
}
function setMaxBuyTransaction(uint256 _maxBuyTxAmount) public onlyOwner {
maxBuyTransactionAmount = _maxBuyTxAmount;
require(maxBuyTransactionAmount>totalSupply().div(1000), "value is too low");
}
function setSwapTokensAtAmouunt(uint256 _newAmount) public onlyOwner {
swapTokensAtAmount = _newAmount;
}
function setMarketingWallet(address payable wallet) public onlyOwner {
marketingWallet = wallet;
}
function setDevWallet(address payable wallet) public onlyOwner {
devWallet = wallet;
}
function updateBuyTotalTax(uint256 _buyTotalFees) public onlyOwner {
buyTotalFees = _buyTotalFees;
require(buyTotalFees <= 0, "Fee too high");
}
function updateSellTotalTax(uint256 _sellTotalFees) public onlyOwner {
sellTotalFees = _sellTotalFees;
require(sellTotalFees <= 9, "Fee too high");
}
function updateEarlySellTotalTax(uint256 _earlySellTotalFee) public onlyOwner {
earlySellTotalFee = _earlySellTotalFee;
require(earlySellTotalFee <= 24, "Fee too high");
}
function updateTaxDistributionPercentage(uint256 _liquidityPercent, uint256 _marketingPercent, uint256 _devPercent) public onlyOwner {
require(_liquidityPercent.add(_marketingPercent).add(_devPercent) == 100, "total percentage must be equal to 100");
liquidityPercent = _liquidityPercent;
marketingPercent = _marketingPercent;
devPercent = _devPercent;
}
function setEarlySellTax(bool onoff) external onlyOwner {
enableEarlySellTax = onoff;
}
function setAutoBurn(uint256 _burnFee) external onlyOwner {
require(_burnFee <= 5, "value too high");
burnFee = _burnFee;
}
function setMaxWalletToken(uint256 _maxToken) external onlyOwner {
maxWalletToken = _maxToken;
require(maxWalletToken>totalSupply().div(1000), "value is too low");
}
} | 34% of total collected tax
| uint256 public marketingPercent = 34; | 13,786,967 | [
1,
5026,
9,
434,
2078,
12230,
5320,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
5034,
1071,
13667,
310,
8410,
273,
13438,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.8.4;
// SPDX-License-Identifier: MIT
import "hardhat/console.sol";
error CheesecakePortalError();
contract CheesecakePortal {
uint256[3] private cakeCount;
address payable public owner;
Cheesecake[] private cheesecakes;
event NewCheesecake(
string name,
string message,
uint256 cakeSize,
address indexed from,
uint256 timestamp
);
struct Cheesecake {
string name; // The name of the person who is sending the cheesecake
string message; // The attached mesage from the giver
uint256 cakeSize; // The size of the cheesecake chosen, 0 = small, 1 = medium, 2 = large
address giver; // This is the address of the person who is sending me a cheesecake
uint256 timestamp; // The timestamp when the person sent the cheesecake
}
constructor() payable {
console.log(
"This is from the constructor of CheesecakePortal Smart Contract"
);
// Set owner of the smart contract to the caller of the constructorm, which is the deployer.
owner = payable(msg.sender);
}
// Returns all Cheesecake objects
function getAllCheesecakes() public view returns (Cheesecake[] memory) {
return cheesecakes;
}
// Returns how many cheesecakes were donated
function getCakeCount() public view returns (uint256[3] memory) {
return cakeCount;
}
function sendCheesecake(
string memory _message,
string memory _name,
uint256 _cakeSize // 0 = small, 1 = medium, 2 = large
) public payable {
cakeCount[_cakeSize] += 1;
// console.log("%s has just sent over a cheesecake!", msg.sender);
cheesecakes.push(
Cheesecake(_name, _message, _cakeSize, msg.sender, block.timestamp)
);
console.log("Sending over %d WEI", msg.value);
(bool success, ) = owner.call{value: msg.value}("");
console.log("Success?", success);
emit NewCheesecake(
_name,
_message,
_cakeSize,
msg.sender,
block.timestamp
);
}
function throwError() external pure {
revert CheesecakePortalError();
}
}
| The size of the cheesecake chosen, 0 = small, 1 = medium, 2 = large
| uint256 cakeSize; | 14,093,717 | [
1,
1986,
963,
434,
326,
19315,
281,
557,
911,
10447,
16,
225,
374,
273,
5264,
16,
404,
273,
16212,
16,
576,
273,
7876,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2254,
5034,
276,
911,
1225,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/extensions/integration-manager/integrations/utils/AdapterBase.sol";
/// @title IMockGenericIntegratee Interface
/// @author Enzyme Council <[email protected]>
interface IMockGenericIntegratee {
function swap(
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
function swapOnBehalf(
address payable,
address[] calldata,
uint256[] calldata,
address[] calldata,
uint256[] calldata
) external payable;
}
/// @title MockGenericAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides a generic adapter that:
/// 1. Provides swapping functions that use various `SpendAssetsTransferType` values
/// 2. Directly parses the _actual_ values to swap from provided call data (e.g., `actualIncomingAssetAmounts`)
/// 3. Directly parses values needed by the IntegrationManager from provided call data (e.g., `minIncomingAssetAmounts`)
contract MockGenericAdapter is AdapterBase {
address public immutable INTEGRATEE;
// No need to specify the IntegrationManager
constructor(address _integratee) public AdapterBase(address(0)) {
INTEGRATEE = _integratee;
}
function identifier() external pure override returns (string memory) {
return "MOCK_GENERIC";
}
function parseAssetsForMethod(bytes4 _selector, bytes calldata _callArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
(
spendAssets_,
maxSpendAssetAmounts_,
,
incomingAssets_,
minIncomingAssetAmounts_,
) = __decodeCallArgs(_callArgs);
return (
__getSpendAssetsHandleTypeForSelector(_selector),
spendAssets_,
maxSpendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @dev Assumes SpendAssetsHandleType.Transfer unless otherwise specified
function __getSpendAssetsHandleTypeForSelector(bytes4 _selector)
private
pure
returns (IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_)
{
if (_selector == bytes4(keccak256("removeOnly(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Remove;
}
if (_selector == bytes4(keccak256("swapDirectFromVault(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.None;
}
if (_selector == bytes4(keccak256("swapViaApproval(address,bytes,bytes)"))) {
return IIntegrationManager.SpendAssetsHandleType.Approve;
}
return IIntegrationManager.SpendAssetsHandleType.Transfer;
}
function removeOnly(
address,
bytes calldata,
bytes calldata
) external {}
function swapA(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapB(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function swapDirectFromVault(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata
) external {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
IMockGenericIntegratee(INTEGRATEE).swapOnBehalf(
payable(_vaultProxy),
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
function swapViaApproval(
address _vaultProxy,
bytes calldata _callArgs,
bytes calldata _assetTransferArgs
) external fundAssetsTransferHandler(_vaultProxy, _assetTransferArgs) {
__decodeCallArgsAndSwap(_callArgs);
}
function __decodeCallArgs(bytes memory _callArgs)
internal
pure
returns (
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory actualSpendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_,
uint256[] memory actualIncomingAssetAmounts_
)
{
return
abi.decode(
_callArgs,
(address[], uint256[], uint256[], address[], uint256[], uint256[])
);
}
function __decodeCallArgsAndSwap(bytes memory _callArgs) internal {
(
address[] memory spendAssets,
,
uint256[] memory actualSpendAssetAmounts,
address[] memory incomingAssets,
,
uint256[] memory actualIncomingAssetAmounts
) = __decodeCallArgs(_callArgs);
for (uint256 i; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).approve(INTEGRATEE, actualSpendAssetAmounts[i]);
}
IMockGenericIntegratee(INTEGRATEE).swap(
spendAssets,
actualSpendAssetAmounts,
incomingAssets,
actualIncomingAssetAmounts
);
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../IIntegrationAdapter.sol";
import "./IntegrationSelectors.sol";
/// @title AdapterBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters
abstract contract AdapterBase is IIntegrationAdapter, IntegrationSelectors {
using SafeERC20 for ERC20;
address internal immutable INTEGRATION_MANAGER;
/// @dev Provides a standard implementation for transferring assets between
/// the fund's VaultProxy and the adapter, by wrapping the adapter action.
/// This modifier should be implemented in almost all adapter actions, unless they
/// do not move assets or can spend and receive assets directly with the VaultProxy
modifier fundAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
(
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
// Take custody of spend assets (if necessary)
if (spendAssetsHandleType == IIntegrationManager.SpendAssetsHandleType.Approve) {
for (uint256 i = 0; i < spendAssets.length; i++) {
ERC20(spendAssets[i]).safeTransferFrom(
_vaultProxy,
address(this),
spendAssetAmounts[i]
);
}
}
// Execute call
_;
// Transfer remaining assets back to the fund's VaultProxy
__transferContractAssetBalancesToFund(_vaultProxy, incomingAssets);
__transferContractAssetBalancesToFund(_vaultProxy, spendAssets);
}
modifier onlyIntegrationManager {
require(
msg.sender == INTEGRATION_MANAGER,
"Only the IntegrationManager can call this function"
);
_;
}
constructor(address _integrationManager) public {
INTEGRATION_MANAGER = _integrationManager;
}
// INTERNAL FUNCTIONS
/// @dev Helper for adapters to approve their integratees with the max amount of an asset.
/// Since everything is done atomically, and only the balances to-be-used are sent to adapters,
/// there is no need to approve exact amounts on every call.
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to decode the _encodedAssetTransferArgs param passed to adapter call
function __decodeEncodedAssetTransferArgs(bytes memory _encodedAssetTransferArgs)
internal
pure
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_
)
{
return
abi.decode(
_encodedAssetTransferArgs,
(IIntegrationManager.SpendAssetsHandleType, address[], uint256[], address[])
);
}
/// @dev Helper to transfer full contract balances of assets to the specified VaultProxy
function __transferContractAssetBalancesToFund(address _vaultProxy, address[] memory _assets)
private
{
for (uint256 i = 0; i < _assets.length; i++) {
uint256 postCallAmount = ERC20(_assets[i]).balanceOf(address(this));
if (postCallAmount > 0) {
ERC20(_assets[i]).safeTransfer(_vaultProxy, postCallAmount);
}
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `INTEGRATION_MANAGER` variable
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
function getIntegrationManager() external view returns (address integrationManager_) {
return INTEGRATION_MANAGER;
}
}
// 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;
/**
* @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.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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../IIntegrationManager.sol";
/// @title Integration Adapter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all integration adapters
interface IIntegrationAdapter {
function identifier() external pure returns (string memory identifier_);
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IntegrationSelectors Contract
/// @author Enzyme Council <[email protected]>
/// @notice Selectors for integration actions
/// @dev Selectors are created from their signatures rather than hardcoded for easy verification
abstract contract IntegrationSelectors {
bytes4 public constant ADD_TRACKED_ASSETS_SELECTOR = bytes4(
keccak256("addTrackedAssets(address,bytes,bytes)")
);
// Trading
bytes4 public constant TAKE_ORDER_SELECTOR = bytes4(
keccak256("takeOrder(address,bytes,bytes)")
);
// Lending
bytes4 public constant LEND_SELECTOR = bytes4(keccak256("lend(address,bytes,bytes)"));
bytes4 public constant REDEEM_SELECTOR = bytes4(keccak256("redeem(address,bytes,bytes)"));
// Staking
bytes4 public constant STAKE_SELECTOR = bytes4(keccak256("stake(address,bytes,bytes)"));
bytes4 public constant UNSTAKE_SELECTOR = bytes4(keccak256("unstake(address,bytes,bytes)"));
// Combined
bytes4 public constant LEND_AND_STAKE_SELECTOR = bytes4(
keccak256("lendAndStake(address,bytes,bytes)")
);
bytes4 public constant UNSTAKE_AND_REDEEM_SELECTOR = bytes4(
keccak256("unstakeAndRedeem(address,bytes,bytes)")
);
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IIntegrationManager interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the IntegrationManager
interface IIntegrationManager {
enum SpendAssetsHandleType {None, Approve, Transfer, Remove}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IZeroExV2.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "../utils/AdapterBase.sol";
/// @title ZeroExV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to 0xV2 Exchange Contract
contract ZeroExV2Adapter is AdapterBase, FundDeployerOwnerMixin, MathHelpers {
using AddressArrayLib for address[];
using SafeMath for uint256;
event AllowedMakerAdded(address indexed account);
event AllowedMakerRemoved(address indexed account);
address private immutable EXCHANGE;
mapping(address => bool) private makerToIsAllowed;
// Gas could be optimized for the end-user by also storing an immutable ZRX_ASSET_DATA,
// for example, but in the narrow OTC use-case of this adapter, taker fees are unlikely.
constructor(
address _integrationManager,
address _exchange,
address _fundDeployer,
address[] memory _allowedMakers
) public AdapterBase(_integrationManager) FundDeployerOwnerMixin(_fundDeployer) {
EXCHANGE = _exchange;
if (_allowedMakers.length > 0) {
__addAllowedMakers(_allowedMakers);
}
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ZERO_EX_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
require(
isAllowedMaker(order.makerAddress),
"parseAssetsForMethod: Order maker is not allowed"
);
require(
takerAssetFillAmount <= order.takerAssetAmount,
"parseAssetsForMethod: Taker asset fill amount greater than available"
);
address makerAsset = __getAssetAddress(order.makerAssetData);
address takerAsset = __getAssetAddress(order.takerAssetData);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = makerAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = __calcRelativeQuantity(
order.takerAssetAmount,
order.makerAssetAmount,
takerAssetFillAmount
);
if (order.takerFee > 0) {
address takerFeeAsset = __getAssetAddress(IZeroExV2(EXCHANGE).ZRX_ASSET_DATA());
uint256 takerFeeFillAmount = __calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
); // fee calculated relative to taker fill amount
if (takerFeeAsset == makerAsset) {
require(
order.takerFee < order.makerAssetAmount,
"parseAssetsForMethod: Fee greater than makerAssetAmount"
);
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts_[0].sub(takerFeeFillAmount);
} else if (takerFeeAsset == takerAsset) {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount.add(takerFeeFillAmount);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = takerAsset;
spendAssets_[1] = takerFeeAsset;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = takerAssetFillAmount;
spendAssetAmounts_[1] = takerFeeFillAmount;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = takerAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = takerAssetFillAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Take an order on 0x
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
bytes memory encodedZeroExOrderArgs,
uint256 takerAssetFillAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
IZeroExV2.Order memory order = __constructOrderStruct(encodedZeroExOrderArgs);
// Approve spend assets as needed
__approveMaxAsNeeded(
__getAssetAddress(order.takerAssetData),
__getAssetProxy(order.takerAssetData),
takerAssetFillAmount
);
// Ignores whether makerAsset or takerAsset overlap with the takerFee asset for simplicity
if (order.takerFee > 0) {
bytes memory zrxData = IZeroExV2(EXCHANGE).ZRX_ASSET_DATA();
__approveMaxAsNeeded(
__getAssetAddress(zrxData),
__getAssetProxy(zrxData),
__calcRelativeQuantity(
order.takerAssetAmount,
order.takerFee,
takerAssetFillAmount
) // fee calculated relative to taker fill amount
);
}
// Execute order
(, , , bytes memory signature) = __decodeZeroExOrderArgs(encodedZeroExOrderArgs);
IZeroExV2(EXCHANGE).fillOrder(order, takerAssetFillAmount, signature);
}
// PRIVATE FUNCTIONS
/// @dev Parses user inputs into a ZeroExV2.Order format
function __constructOrderStruct(bytes memory _encodedOrderArgs)
private
pure
returns (IZeroExV2.Order memory order_)
{
(
address[4] memory orderAddresses,
uint256[6] memory orderValues,
bytes[2] memory orderData,
) = __decodeZeroExOrderArgs(_encodedOrderArgs);
return
IZeroExV2.Order({
makerAddress: orderAddresses[0],
takerAddress: orderAddresses[1],
feeRecipientAddress: orderAddresses[2],
senderAddress: orderAddresses[3],
makerAssetAmount: orderValues[0],
takerAssetAmount: orderValues[1],
makerFee: orderValues[2],
takerFee: orderValues[3],
expirationTimeSeconds: orderValues[4],
salt: orderValues[5],
makerAssetData: orderData[0],
takerAssetData: orderData[1]
});
}
/// @dev Decode the parameters of a takeOrder call
/// @param _encodedCallArgs Encoded parameters passed from client side
/// @return encodedZeroExOrderArgs_ Encoded args of the 0x order
/// @return takerAssetFillAmount_ Amount of taker asset to fill
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (bytes memory encodedZeroExOrderArgs_, uint256 takerAssetFillAmount_)
{
return abi.decode(_encodedCallArgs, (bytes, uint256));
}
/// @dev Decode the parameters of a 0x order
/// @param _encodedZeroExOrderArgs Encoded parameters of the 0x order
/// @return orderAddresses_ Addresses used in the order
/// - [0] 0x Order param: makerAddress
/// - [1] 0x Order param: takerAddress
/// - [2] 0x Order param: feeRecipientAddress
/// - [3] 0x Order param: senderAddress
/// @return orderValues_ Values used in the order
/// - [0] 0x Order param: makerAssetAmount
/// - [1] 0x Order param: takerAssetAmount
/// - [2] 0x Order param: makerFee
/// - [3] 0x Order param: takerFee
/// - [4] 0x Order param: expirationTimeSeconds
/// - [5] 0x Order param: salt
/// @return orderData_ Bytes data used in the order
/// - [0] 0x Order param: makerAssetData
/// - [1] 0x Order param: takerAssetData
/// @return signature_ Signature of the order
function __decodeZeroExOrderArgs(bytes memory _encodedZeroExOrderArgs)
private
pure
returns (
address[4] memory orderAddresses_,
uint256[6] memory orderValues_,
bytes[2] memory orderData_,
bytes memory signature_
)
{
return abi.decode(_encodedZeroExOrderArgs, (address[4], uint256[6], bytes[2], bytes));
}
/// @dev Parses the asset address from 0x assetData
function __getAssetAddress(bytes memory _assetData)
private
pure
returns (address assetAddress_)
{
assembly {
assetAddress_ := mload(add(_assetData, 36))
}
}
/// @dev Gets the 0x assetProxy address for an ERC20 token
function __getAssetProxy(bytes memory _assetData) private view returns (address assetProxy_) {
bytes4 assetProxyId;
assembly {
assetProxyId := and(
mload(add(_assetData, 32)),
0xFFFFFFFF00000000000000000000000000000000000000000000000000000000
)
}
assetProxy_ = IZeroExV2(EXCHANGE).getAssetProxy(assetProxyId);
}
/////////////////////////////
// ALLOWED MAKERS REGISTRY //
/////////////////////////////
/// @notice Adds accounts to the list of allowed 0x order makers
/// @param _accountsToAdd Accounts to add
function addAllowedMakers(address[] calldata _accountsToAdd) external onlyFundDeployerOwner {
__addAllowedMakers(_accountsToAdd);
}
/// @notice Removes accounts from the list of allowed 0x order makers
/// @param _accountsToRemove Accounts to remove
function removeAllowedMakers(address[] calldata _accountsToRemove)
external
onlyFundDeployerOwner
{
require(_accountsToRemove.length > 0, "removeAllowedMakers: Empty _accountsToRemove");
for (uint256 i; i < _accountsToRemove.length; i++) {
require(
isAllowedMaker(_accountsToRemove[i]),
"removeAllowedMakers: Account is not an allowed maker"
);
makerToIsAllowed[_accountsToRemove[i]] = false;
emit AllowedMakerRemoved(_accountsToRemove[i]);
}
}
/// @dev Helper to add accounts to the list of allowed makers
function __addAllowedMakers(address[] memory _accountsToAdd) private {
require(_accountsToAdd.length > 0, "__addAllowedMakers: Empty _accountsToAdd");
for (uint256 i; i < _accountsToAdd.length; i++) {
require(!isAllowedMaker(_accountsToAdd[i]), "__addAllowedMakers: Value already set");
makerToIsAllowed[_accountsToAdd[i]] = true;
emit AllowedMakerAdded(_accountsToAdd[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable value
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Checks whether an account is an allowed maker of 0x orders
/// @param _who The account to check
/// @return isAllowedMaker_ True if _who is an allowed maker
function isAllowedMaker(address _who) public view returns (bool isAllowedMaker_) {
return makerToIsAllowed[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @dev Minimal interface for our interactions with the ZeroEx Exchange contract
interface IZeroExV2 {
struct Order {
address makerAddress;
address takerAddress;
address feeRecipientAddress;
address senderAddress;
uint256 makerAssetAmount;
uint256 takerAssetAmount;
uint256 makerFee;
uint256 takerFee;
uint256 expirationTimeSeconds;
uint256 salt;
bytes makerAssetData;
bytes takerAssetData;
}
struct OrderInfo {
uint8 orderStatus;
bytes32 orderHash;
uint256 orderTakerAssetFilledAmount;
}
struct FillResults {
uint256 makerAssetFilledAmount;
uint256 takerAssetFilledAmount;
uint256 makerFeePaid;
uint256 takerFeePaid;
}
function ZRX_ASSET_DATA() external view returns (bytes memory);
function filled(bytes32) external view returns (uint256);
function cancelled(bytes32) external view returns (bool);
function getOrderInfo(Order calldata) external view returns (OrderInfo memory);
function getAssetProxy(bytes4) external view returns (address);
function isValidSignature(
bytes32,
address,
bytes calldata
) external view returns (bool);
function preSign(
bytes32,
address,
bytes calldata
) external;
function cancelOrder(Order calldata) external;
function fillOrder(
Order calldata,
uint256,
bytes calldata
) external returns (FillResults memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @title MathHelpers Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for common math operations
abstract contract MathHelpers {
using SafeMath for uint256;
/// @dev Calculates a proportional value relative to a known ratio
function __calcRelativeQuantity(
uint256 _quantity1,
uint256 _quantity2,
uint256 _relativeQuantity1
) internal pure returns (uint256 relativeQuantity2_) {
return _relativeQuantity1.mul(_quantity2).div(_quantity1);
}
/// @dev Calculates a rate normalized to 10^18 precision,
/// for given base and quote asset decimals and amounts
function __calcNormalizedRate(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _quoteAssetAmount
) internal pure returns (uint256 normalizedRate_) {
return
_quoteAssetAmount.mul(10**_baseAssetDecimals.add(18)).div(
_baseAssetAmount.mul(10**_quoteAssetDecimals)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title AddressArray Library
/// @author Enzyme Council <[email protected]>
/// @notice A library to extend the address array data type
library AddressArrayLib {
/// @dev Helper to verify if an array contains a particular value
function contains(address[] memory _self, address _target)
internal
pure
returns (bool doesContain_)
{
for (uint256 i; i < _self.length; i++) {
if (_target == _self[i]) {
return true;
}
}
return false;
}
/// @dev Helper to verify if array is a set of unique values.
/// Does not assert length > 0.
function isUniqueSet(address[] memory _self) internal pure returns (bool isUnique_) {
if (_self.length <= 1) {
return true;
}
uint256 arrayLength = _self.length;
for (uint256 i; i < arrayLength; i++) {
for (uint256 j = i + 1; j < arrayLength; j++) {
if (_self[i] == _self[j]) {
return false;
}
}
}
return true;
}
/// @dev Helper to remove items from an array. Removes all matching occurrences of each item.
/// Does not assert uniqueness of either array.
function removeItems(address[] memory _self, address[] memory _itemsToRemove)
internal
pure
returns (address[] memory nextArray_)
{
if (_itemsToRemove.length == 0) {
return _self;
}
bool[] memory indexesToRemove = new bool[](_self.length);
uint256 remainingItemsCount = _self.length;
for (uint256 i; i < _self.length; i++) {
if (contains(_itemsToRemove, _self[i])) {
indexesToRemove[i] = true;
remainingItemsCount--;
}
}
if (remainingItemsCount == _self.length) {
nextArray_ = _self;
} else if (remainingItemsCount > 0) {
nextArray_ = new address[](remainingItemsCount);
uint256 nextArrayIndex;
for (uint256 i; i < _self.length; i++) {
if (!indexesToRemove[i]) {
nextArray_[nextArrayIndex] = _self[i];
nextArrayIndex++;
}
}
}
return nextArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund-deployer/IFundDeployer.sol";
/// @title FundDeployerOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of FundDeployer
abstract contract FundDeployerOwnerMixin {
address internal immutable FUND_DEPLOYER;
modifier onlyFundDeployerOwner() {
require(
msg.sender == getOwner(),
"onlyFundDeployerOwner: Only the FundDeployer owner can call this function"
);
_;
}
constructor(address _fundDeployer) public {
FUND_DEPLOYER = _fundDeployer;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the FundDeployer contract
function getOwner() public view returns (address owner_) {
return IFundDeployer(FUND_DEPLOYER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FUND_DEPLOYER` variable
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
function getFundDeployer() external view returns (address fundDeployer_) {
return FUND_DEPLOYER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IFundDeployer Interface
/// @author Enzyme Council <[email protected]>
interface IFundDeployer {
enum ReleaseStatus {PreLaunch, Live, Paused}
function getOwner() external view returns (address);
function getReleaseStatus() external view returns (ReleaseStatus);
function isRegisteredVaultCall(address, bytes4) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "./IPolicy.sol";
import "./IPolicyManager.sol";
/// @title PolicyManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages policies for funds
contract PolicyManager is IPolicyManager, ExtensionBase, FundDeployerOwnerMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event PolicyDeregistered(address indexed policy, string indexed identifier);
event PolicyDisabledForFund(address indexed comptrollerProxy, address indexed policy);
event PolicyEnabledForFund(
address indexed comptrollerProxy,
address indexed policy,
bytes settingsData
);
event PolicyRegistered(
address indexed policy,
string indexed identifier,
PolicyHook[] implementedHooks
);
EnumerableSet.AddressSet private registeredPolicies;
mapping(address => mapping(PolicyHook => bool)) private policyToHookToIsImplemented;
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToPolicies;
modifier onlyBuySharesHooks(address _policy) {
require(
!policyImplementsHook(_policy, PolicyHook.PreCallOnIntegration) &&
!policyImplementsHook(_policy, PolicyHook.PostCallOnIntegration),
"onlyBuySharesHooks: Disallowed hook"
);
_;
}
modifier onlyEnabledPolicyForFund(address _comptrollerProxy, address _policy) {
require(
policyIsEnabledForFund(_comptrollerProxy, _policy),
"onlyEnabledPolicyForFund: Policy not enabled"
);
_;
}
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Validates and initializes policies as necessary prior to fund activation
/// @param _isMigratedFund True if the fund is migrating to this release
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
function activateForFund(bool _isMigratedFund) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
// Policies must assert that they are congruent with migrated vault state
if (_isMigratedFund) {
address[] memory enabledPolicies = getEnabledPoliciesForFund(msg.sender);
for (uint256 i; i < enabledPolicies.length; i++) {
__activatePolicyForFund(msg.sender, vaultProxy, enabledPolicies[i]);
}
}
}
/// @notice Deactivates policies for a fund by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
for (uint256 i = comptrollerProxyToPolicies[msg.sender].length(); i > 0; i--) {
comptrollerProxyToPolicies[msg.sender].remove(
comptrollerProxyToPolicies[msg.sender].at(i - 1)
);
}
}
/// @notice Disables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to disable
function disablePolicyForFund(address _comptrollerProxy, address _policy)
external
onlyBuySharesHooks(_policy)
onlyEnabledPolicyForFund(_comptrollerProxy, _policy)
{
__validateIsFundOwner(getVaultProxyForFund(_comptrollerProxy), msg.sender);
comptrollerProxyToPolicies[_comptrollerProxy].remove(_policy);
emit PolicyDisabledForFund(_comptrollerProxy, _policy);
}
/// @notice Enables a policy for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The policy address to enable
/// @param _settingsData The encoded settings data with which to configure the policy
/// @dev Disabling a policy does not delete fund config on the policy, so if a policy is
/// disabled and then enabled again, its initial state will be the previous config. It is the
/// policy's job to determine how to merge that config with the _settingsData param in this function.
function enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
__enablePolicyForFund(_comptrollerProxy, _policy, _settingsData);
__activatePolicyForFund(_comptrollerProxy, vaultProxy, _policy);
}
/// @notice Enable policies for use in a fund
/// @param _configData Encoded config data
/// @dev Only called during init() on ComptrollerProxy deployment
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory policies, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity check
require(
policies.length == settingsData.length,
"setConfigForFund: policies and settingsData array lengths unequal"
);
// Enable each policy with settings
for (uint256 i; i < policies.length; i++) {
__enablePolicyForFund(msg.sender, policies[i], settingsData[i]);
}
}
/// @notice Updates policy settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _policy The Policy contract to update
/// @param _settingsData The encoded settings data with which to update the policy config
function updatePolicySettingsForFund(
address _comptrollerProxy,
address _policy,
bytes calldata _settingsData
) external onlyBuySharesHooks(_policy) onlyEnabledPolicyForFund(_comptrollerProxy, _policy) {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
__validateIsFundOwner(vaultProxy, msg.sender);
IPolicy(_policy).updateFundSettings(_comptrollerProxy, vaultProxy, _settingsData);
}
/// @notice Validates all policies that apply to a given hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _hook The PolicyHook for which to validate policies
/// @param _validationData The encoded data with which to validate the filtered policies
function validatePolicies(
address _comptrollerProxy,
PolicyHook _hook,
bytes calldata _validationData
) external override {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
address[] memory policies = getEnabledPoliciesForFund(_comptrollerProxy);
for (uint256 i; i < policies.length; i++) {
if (!policyImplementsHook(policies[i], _hook)) {
continue;
}
require(
IPolicy(policies[i]).validateRule(
_comptrollerProxy,
vaultProxy,
_hook,
_validationData
),
string(
abi.encodePacked(
"Rule evaluated to false: ",
IPolicy(policies[i]).identifier()
)
)
);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to activate a policy for a fund
function __activatePolicyForFund(
address _comptrollerProxy,
address _vaultProxy,
address _policy
) private {
IPolicy(_policy).activateForFund(_comptrollerProxy, _vaultProxy);
}
/// @dev Helper to set config and enable policies for a fund
function __enablePolicyForFund(
address _comptrollerProxy,
address _policy,
bytes memory _settingsData
) private {
require(
!policyIsEnabledForFund(_comptrollerProxy, _policy),
"__enablePolicyForFund: policy already enabled"
);
require(policyIsRegistered(_policy), "__enablePolicyForFund: Policy is not registered");
// Set fund config on policy
if (_settingsData.length > 0) {
IPolicy(_policy).addFundSettings(_comptrollerProxy, _settingsData);
}
// Add policy
comptrollerProxyToPolicies[_comptrollerProxy].add(_policy);
emit PolicyEnabledForFund(_comptrollerProxy, _policy, _settingsData);
}
/// @dev Helper to validate fund owner.
/// Preferred to a modifier because allows gas savings if re-using _vaultProxy.
function __validateIsFundOwner(address _vaultProxy, address _who) private view {
require(
_who == IVault(_vaultProxy).getOwner(),
"Only the fund owner can call this function"
);
}
///////////////////////
// POLICIES REGISTRY //
///////////////////////
/// @notice Remove policies from the list of registered policies
/// @param _policies Addresses of policies to be registered
function deregisterPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "deregisterPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
policyIsRegistered(_policies[i]),
"deregisterPolicies: policy is not registered"
);
registeredPolicies.remove(_policies[i]);
emit PolicyDeregistered(_policies[i], IPolicy(_policies[i]).identifier());
}
}
/// @notice Add policies to the list of registered policies
/// @param _policies Addresses of policies to be registered
function registerPolicies(address[] calldata _policies) external onlyFundDeployerOwner {
require(_policies.length > 0, "registerPolicies: _policies cannot be empty");
for (uint256 i; i < _policies.length; i++) {
require(
!policyIsRegistered(_policies[i]),
"registerPolicies: policy already registered"
);
registeredPolicies.add(_policies[i]);
// Store the hooks that a policy implements for later use.
// Fronts the gas for calls to check if a hook is implemented, and guarantees
// that the implementsHooks return value does not change post-registration.
IPolicy policyContract = IPolicy(_policies[i]);
PolicyHook[] memory implementedHooks = policyContract.implementedHooks();
for (uint256 j; j < implementedHooks.length; j++) {
policyToHookToIsImplemented[_policies[i]][implementedHooks[j]] = true;
}
emit PolicyRegistered(_policies[i], policyContract.identifier(), implementedHooks);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get all registered policies
/// @return registeredPoliciesArray_ A list of all registered policy addresses
function getRegisteredPolicies()
external
view
returns (address[] memory registeredPoliciesArray_)
{
registeredPoliciesArray_ = new address[](registeredPolicies.length());
for (uint256 i; i < registeredPoliciesArray_.length; i++) {
registeredPoliciesArray_[i] = registeredPolicies.at(i);
}
}
/// @notice Get a list of enabled policies for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledPolicies_ An array of enabled policy addresses
function getEnabledPoliciesForFund(address _comptrollerProxy)
public
view
returns (address[] memory enabledPolicies_)
{
enabledPolicies_ = new address[](comptrollerProxyToPolicies[_comptrollerProxy].length());
for (uint256 i; i < enabledPolicies_.length; i++) {
enabledPolicies_[i] = comptrollerProxyToPolicies[_comptrollerProxy].at(i);
}
}
/// @notice Checks if a policy implements a particular hook
/// @param _policy The address of the policy to check
/// @param _hook The PolicyHook to check
/// @return implementsHook_ True if the policy implements the hook
function policyImplementsHook(address _policy, PolicyHook _hook)
public
view
returns (bool implementsHook_)
{
return policyToHookToIsImplemented[_policy][_hook];
}
/// @notice Check if a policy is enabled for the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund to check
/// @param _policy The address of the policy to check
/// @return isEnabled_ True if the policy is enabled for the fund
function policyIsEnabledForFund(address _comptrollerProxy, address _policy)
public
view
returns (bool isEnabled_)
{
return comptrollerProxyToPolicies[_comptrollerProxy].contains(_policy);
}
/// @notice Check whether a policy is registered
/// @param _policy The address of the policy to check
/// @return isRegistered_ True if the policy is registered
function policyIsRegistered(address _policy) public view returns (bool isRegistered_) {
return registeredPolicies.contains(_policy);
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../persistent/utils/IMigratableVault.sol";
/// @title IVault Interface
/// @author Enzyme Council <[email protected]>
interface IVault is IMigratableVault {
function addTrackedAsset(address) external;
function approveAssetSpender(
address,
address,
uint256
) external;
function burnShares(address, uint256) external;
function callOnContract(address, bytes calldata) external;
function getAccessor() external view returns (address);
function getOwner() external view returns (address);
function getTrackedAssets() external view returns (address[] memory);
function isTrackedAsset(address) external view returns (bool);
function mintShares(address, uint256) external;
function removeTrackedAsset(address) external;
function transferShares(
address,
address,
uint256
) external;
function withdrawAssetTo(
address,
address,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../IExtension.sol";
/// @title ExtensionBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Base class for an extension
abstract contract ExtensionBase is IExtension {
mapping(address => address) internal comptrollerProxyToVaultProxy;
/// @notice Allows extension to run logic during fund activation
/// @dev Unimplemented by default, may be overridden.
function activateForFund(bool) external virtual override {
return;
}
/// @notice Allows extension to run logic during fund deactivation (destruct)
/// @dev Unimplemented by default, may be overridden.
function deactivateForFund() external virtual override {
return;
}
/// @notice Receives calls from ComptrollerLib.callOnExtension()
/// and dispatches the appropriate action
/// @dev Unimplemented by default, may be overridden.
function receiveCallFromComptroller(
address,
uint256,
bytes calldata
) external virtual override {
revert("receiveCallFromComptroller: Unimplemented for Extension");
}
/// @notice Allows extension to run logic during fund configuration
/// @dev Unimplemented by default, may be overridden.
function setConfigForFund(bytes calldata) external virtual override {
return;
}
/// @dev Helper to validate a ComptrollerProxy-VaultProxy relation, which we store for both
/// gas savings and to guarantee a spoofed ComptrollerProxy does not change getVaultProxy().
/// Will revert without reason if the expected interfaces do not exist.
function __setValidatedVaultProxy(address _comptrollerProxy)
internal
returns (address vaultProxy_)
{
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] == address(0),
"__setValidatedVaultProxy: Already set"
);
vaultProxy_ = IComptroller(_comptrollerProxy).getVaultProxy();
require(vaultProxy_ != address(0), "__setValidatedVaultProxy: Missing vaultProxy");
require(
_comptrollerProxy == IVault(vaultProxy_).getAccessor(),
"__setValidatedVaultProxy: Not the VaultProxy accessor"
);
comptrollerProxyToVaultProxy[_comptrollerProxy] = vaultProxy_;
return vaultProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the verified VaultProxy for a given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return vaultProxy_ The VaultProxy of the fund
function getVaultProxyForFund(address _comptrollerProxy)
public
view
returns (address vaultProxy_)
{
return comptrollerProxyToVaultProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IPolicyManager.sol";
/// @title Policy Interface
/// @author Enzyme Council <[email protected]>
interface IPolicy {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (IPolicyManager.PolicyHook[] memory implementedHooks_);
function updateFundSettings(
address _comptrollerProxy,
address _vaultProxy,
bytes calldata _encodedSettings
) external;
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook _hook,
bytes calldata _encodedArgs
) external returns (bool isValid_);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title PolicyManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the PolicyManager
interface IPolicyManager {
enum PolicyHook {
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreCallOnIntegration,
PostCallOnIntegration
}
function validatePolicies(
address,
PolicyHook,
bytes calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigratableVault Interface
/// @author Enzyme Council <[email protected]>
/// @dev DO NOT EDIT CONTRACT
interface IMigratableVault {
function canMigrate(address _who) external view returns (bool canMigrate_);
function init(
address _owner,
address _accessor,
string calldata _fundName
) external;
function setAccessor(address _nextAccessor) external;
function setVaultLib(address _nextVaultLib) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IComptroller Interface
/// @author Enzyme Council <[email protected]>
interface IComptroller {
enum VaultAction {
None,
BurnShares,
MintShares,
TransferShares,
ApproveAssetSpender,
WithdrawAssetTo,
AddTrackedAsset,
RemoveTrackedAsset
}
function activate(address, bool) external;
function calcGav(bool) external returns (uint256, bool);
function calcGrossShareValue(bool) external returns (uint256, bool);
function callOnExtension(
address,
uint256,
bytes calldata
) external;
function configureExtensions(bytes calldata, bytes calldata) external;
function destruct() external;
function getDenominationAsset() external view returns (address);
function getVaultProxy() external view returns (address);
function init(address, uint256) external;
function permissionedVaultAction(VaultAction, bytes calldata) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IExtension Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all extensions
interface IExtension {
function activateForFund(bool _isMigration) external;
function deactivateForFund() external;
function receiveCallFromComptroller(
address _comptrollerProxy,
uint256 _actionId,
bytes calldata _callArgs
) external;
function setConfigForFund(bytes calldata _configData) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IPolicy.sol";
/// @title PolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all policies
abstract contract PolicyBase is IPolicy {
address internal immutable POLICY_MANAGER;
modifier onlyPolicyManager {
require(msg.sender == POLICY_MANAGER, "Only the PolicyManager can make this call");
_;
}
constructor(address _policyManager) public {
POLICY_MANAGER = _policyManager;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @dev Unimplemented by default, can be overridden by the policy
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Updates the policy settings for a fund
/// @dev Disallowed by default, can be overridden by the policy
function updateFundSettings(
address,
address,
bytes calldata
) external virtual override {
revert("updateFundSettings: Updates not allowed for this policy");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `POLICY_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPostValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PostCallOnIntegration policy hook
abstract contract PostCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PostCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (
address adapter_,
bytes4 selector_,
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
return
abi.decode(
_encodedRuleArgs,
(address, bytes4, address[], uint256[], address[], uint256[])
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../infrastructure/value-interpreter/ValueInterpreter.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title MaxConcentration Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that defines a configurable threshold for the concentration of any one asset
/// in a fund's holdings
contract MaxConcentration is PostCallOnIntegrationValidatePolicyBase {
using SafeMath for uint256;
event MaxConcentrationSet(address indexed comptrollerProxy, uint256 value);
uint256 private constant ONE_HUNDRED_PERCENT = 10**18; // 100%
address private immutable VALUE_INTERPRETER;
mapping(address => uint256) private comptrollerProxyToMaxConcentration;
constructor(address _policyManager, address _valueInterpreter)
public
PolicyBase(_policyManager)
{
VALUE_INTERPRETER = _valueInterpreter;
}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @dev No need to authenticate access, as there are no state transitions
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, _vaultProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Max concentration exceeded"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
uint256 maxConcentration = abi.decode(_encodedSettings, (uint256));
require(maxConcentration > 0, "addFundSettings: maxConcentration must be greater than 0");
require(
maxConcentration <= ONE_HUNDRED_PERCENT,
"addFundSettings: maxConcentration cannot exceed 100%"
);
comptrollerProxyToMaxConcentration[_comptrollerProxy] = maxConcentration;
emit MaxConcentrationSet(_comptrollerProxy, maxConcentration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MAX_CONCENTRATION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
/// @dev The fund's denomination asset is exempt from the policy limit.
function passesRule(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _assets
) public returns (bool isValid_) {
uint256 maxConcentration = comptrollerProxyToMaxConcentration[_comptrollerProxy];
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
address denominationAsset = comptrollerProxyContract.getDenominationAsset();
// Does not require asset finality, otherwise will fail when incoming asset is a Synth
(uint256 totalGav, bool gavIsValid) = comptrollerProxyContract.calcGav(false);
if (!gavIsValid) {
return false;
}
for (uint256 i = 0; i < _assets.length; i++) {
address asset = _assets[i];
if (
!__rulePassesForAsset(
_vaultProxy,
denominationAsset,
maxConcentration,
totalGav,
asset
)
) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address _vaultProxy,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
if (incomingAssets.length == 0) {
return true;
}
return passesRule(_comptrollerProxy, _vaultProxy, incomingAssets);
}
/// @dev Helper to check if the rule holds for a particular asset.
/// Avoids the stack-too-deep error.
function __rulePassesForAsset(
address _vaultProxy,
address _denominationAsset,
uint256 _maxConcentration,
uint256 _totalGav,
address _incomingAsset
) private returns (bool isValid_) {
if (_incomingAsset == _denominationAsset) return true;
uint256 assetBalance = ERC20(_incomingAsset).balanceOf(_vaultProxy);
(uint256 assetGav, bool assetGavIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcLiveAssetValue(_incomingAsset, assetBalance, _denominationAsset);
if (
!assetGavIsValid ||
assetGav.mul(ONE_HUNDRED_PERCENT).div(_totalGav) > _maxConcentration
) {
return false;
}
return true;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the maxConcentration for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return maxConcentration_ The maxConcentration
function getMaxConcentrationForFund(address _comptrollerProxy)
external
view
returns (uint256 maxConcentration_)
{
return comptrollerProxyToMaxConcentration[_comptrollerProxy];
}
/// @notice Gets the `VALUE_INTERPRETER` variable
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../extensions/IExtension.sol";
import "../../../extensions/fee-manager/IFeeManager.sol";
import "../../../extensions/policy-manager/IPolicyManager.sol";
import "../../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../../infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../../utils/AddressArrayLib.sol";
import "../../../utils/AssetFinalityResolver.sol";
import "../../fund-deployer/IFundDeployer.sol";
import "../vault/IVault.sol";
import "./IComptroller.sol";
/// @title ComptrollerLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The core logic library shared by all funds
contract ComptrollerLib is IComptroller, AssetFinalityResolver {
using AddressArrayLib for address[];
using SafeMath for uint256;
using SafeERC20 for ERC20;
event MigratedSharesDuePaid(uint256 sharesDue);
event OverridePauseSet(bool indexed overridePause);
event PreRedeemSharesHookFailed(
bytes failureReturnData,
address redeemer,
uint256 sharesQuantity
);
event SharesBought(
address indexed caller,
address indexed buyer,
uint256 investmentAmount,
uint256 sharesIssued,
uint256 sharesReceived
);
event SharesRedeemed(
address indexed redeemer,
uint256 sharesQuantity,
address[] receivedAssets,
uint256[] receivedAssetQuantities
);
event VaultProxySet(address vaultProxy);
// Constants and immutables - shared by all proxies
uint256 private constant SHARES_UNIT = 10**18;
address private immutable DISPATCHER;
address private immutable FUND_DEPLOYER;
address private immutable FEE_MANAGER;
address private immutable INTEGRATION_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable VALUE_INTERPRETER;
// Pseudo-constants (can only be set once)
address internal denominationAsset;
address internal vaultProxy;
// True only for the one non-proxy
bool internal isLib;
// Storage
// Allows a fund owner to override a release-level pause
bool internal overridePause;
// A reverse-mutex, granting atomic permission for particular contracts to make vault calls
bool internal permissionedVaultActionAllowed;
// A mutex to protect against reentrancy
bool internal reentranceLocked;
// A timelock between any "shares actions" (i.e., buy and redeem shares), per-account
uint256 internal sharesActionTimelock;
mapping(address => uint256) internal acctToLastSharesAction;
///////////////
// MODIFIERS //
///////////////
modifier allowsPermissionedVaultAction {
__assertPermissionedVaultActionNotAllowed();
permissionedVaultActionAllowed = true;
_;
permissionedVaultActionAllowed = false;
}
modifier locksReentrance() {
__assertNotReentranceLocked();
reentranceLocked = true;
_;
reentranceLocked = false;
}
modifier onlyActive() {
__assertIsActive(vaultProxy);
_;
}
modifier onlyNotPaused() {
__assertNotPaused();
_;
}
modifier onlyFundDeployer() {
__assertIsFundDeployer(msg.sender);
_;
}
modifier onlyOwner() {
__assertIsOwner(msg.sender);
_;
}
modifier timelockedSharesAction(address _account) {
__assertSharesActionNotTimelocked(_account);
_;
acctToLastSharesAction[_account] = block.timestamp;
}
// ASSERTION HELPERS
// Modifiers are inefficient in terms of contract size,
// so we use helper functions to prevent repetitive inlining of expensive string values.
/// @dev Since vaultProxy is set during activate(),
/// we can check that var rather than storing additional state
function __assertIsActive(address _vaultProxy) private pure {
require(_vaultProxy != address(0), "Fund not active");
}
function __assertIsFundDeployer(address _who) private view {
require(_who == FUND_DEPLOYER, "Only FundDeployer callable");
}
function __assertIsOwner(address _who) private view {
require(_who == IVault(vaultProxy).getOwner(), "Only fund owner callable");
}
function __assertLowLevelCall(bool _success, bytes memory _returnData) private pure {
require(_success, string(_returnData));
}
function __assertNotPaused() private view {
require(!__fundIsPaused(), "Fund is paused");
}
function __assertNotReentranceLocked() private view {
require(!reentranceLocked, "Re-entrance");
}
function __assertPermissionedVaultActionNotAllowed() private view {
require(!permissionedVaultActionAllowed, "Vault action re-entrance");
}
function __assertSharesActionNotTimelocked(address _account) private view {
require(
block.timestamp.sub(acctToLastSharesAction[_account]) >= sharesActionTimelock,
"Shares action timelocked"
);
}
constructor(
address _dispatcher,
address _fundDeployer,
address _valueInterpreter,
address _feeManager,
address _integrationManager,
address _policyManager,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
) public AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver) {
DISPATCHER = _dispatcher;
FEE_MANAGER = _feeManager;
FUND_DEPLOYER = _fundDeployer;
INTEGRATION_MANAGER = _integrationManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
POLICY_MANAGER = _policyManager;
VALUE_INTERPRETER = _valueInterpreter;
isLib = true;
}
/////////////
// GENERAL //
/////////////
/// @notice Calls a specified action on an Extension
/// @param _extension The Extension contract to call (e.g., FeeManager)
/// @param _actionId An ID representing the action to take on the extension (see extension)
/// @param _callArgs The encoded data for the call
/// @dev Used to route arbitrary calls, so that msg.sender is the ComptrollerProxy
/// (for access control). Uses a mutex of sorts that allows "permissioned vault actions"
/// during calls originating from this function.
function callOnExtension(
address _extension,
uint256 _actionId,
bytes calldata _callArgs
) external override onlyNotPaused onlyActive locksReentrance allowsPermissionedVaultAction {
require(
_extension == FEE_MANAGER || _extension == INTEGRATION_MANAGER,
"callOnExtension: _extension invalid"
);
IExtension(_extension).receiveCallFromComptroller(msg.sender, _actionId, _callArgs);
}
/// @notice Sets or unsets an override on a release-wide pause
/// @param _nextOverridePause True if the pause should be overrode
function setOverridePause(bool _nextOverridePause) external onlyOwner {
require(_nextOverridePause != overridePause, "setOverridePause: Value already set");
overridePause = _nextOverridePause;
emit OverridePauseSet(_nextOverridePause);
}
/// @notice Makes an arbitrary call with the VaultProxy contract as the sender
/// @param _contract The contract to call
/// @param _selector The selector to call
/// @param _encodedArgs The encoded arguments for the call
function vaultCallOnContract(
address _contract,
bytes4 _selector,
bytes calldata _encodedArgs
) external onlyNotPaused onlyActive onlyOwner {
require(
IFundDeployer(FUND_DEPLOYER).isRegisteredVaultCall(_contract, _selector),
"vaultCallOnContract: Unregistered"
);
IVault(vaultProxy).callOnContract(_contract, abi.encodePacked(_selector, _encodedArgs));
}
/// @dev Helper to check whether the release is paused, and that there is no local override
function __fundIsPaused() private view returns (bool) {
return
IFundDeployer(FUND_DEPLOYER).getReleaseStatus() ==
IFundDeployer.ReleaseStatus.Paused &&
!overridePause;
}
////////////////////////////////
// PERMISSIONED VAULT ACTIONS //
////////////////////////////////
/// @notice Makes a permissioned, state-changing call on the VaultProxy contract
/// @param _action The enum representing the VaultAction to perform on the VaultProxy
/// @param _actionData The call data for the action to perform
function permissionedVaultAction(VaultAction _action, bytes calldata _actionData)
external
override
onlyNotPaused
onlyActive
{
__assertPermissionedVaultAction(msg.sender, _action);
if (_action == VaultAction.AddTrackedAsset) {
__vaultActionAddTrackedAsset(_actionData);
} else if (_action == VaultAction.ApproveAssetSpender) {
__vaultActionApproveAssetSpender(_actionData);
} else if (_action == VaultAction.BurnShares) {
__vaultActionBurnShares(_actionData);
} else if (_action == VaultAction.MintShares) {
__vaultActionMintShares(_actionData);
} else if (_action == VaultAction.RemoveTrackedAsset) {
__vaultActionRemoveTrackedAsset(_actionData);
} else if (_action == VaultAction.TransferShares) {
__vaultActionTransferShares(_actionData);
} else if (_action == VaultAction.WithdrawAssetTo) {
__vaultActionWithdrawAssetTo(_actionData);
}
}
/// @dev Helper to assert that a caller is allowed to perform a particular VaultAction
function __assertPermissionedVaultAction(address _caller, VaultAction _action) private view {
require(
permissionedVaultActionAllowed,
"__assertPermissionedVaultAction: No action allowed"
);
if (_caller == INTEGRATION_MANAGER) {
require(
_action == VaultAction.ApproveAssetSpender ||
_action == VaultAction.AddTrackedAsset ||
_action == VaultAction.RemoveTrackedAsset ||
_action == VaultAction.WithdrawAssetTo,
"__assertPermissionedVaultAction: Not valid for IntegrationManager"
);
} else if (_caller == FEE_MANAGER) {
require(
_action == VaultAction.BurnShares ||
_action == VaultAction.MintShares ||
_action == VaultAction.TransferShares,
"__assertPermissionedVaultAction: Not valid for FeeManager"
);
} else {
revert("__assertPermissionedVaultAction: Not a valid actor");
}
}
/// @dev Helper to add a tracked asset to the fund
function __vaultActionAddTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
IVault(vaultProxy).addTrackedAsset(asset);
}
/// @dev Helper to grant a spender an allowance for a fund's asset
function __vaultActionApproveAssetSpender(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).approveAssetSpender(asset, target, amount);
}
/// @dev Helper to burn fund shares for a particular account
function __vaultActionBurnShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).burnShares(target, amount);
}
/// @dev Helper to mint fund shares to a particular account
function __vaultActionMintShares(bytes memory _actionData) private {
(address target, uint256 amount) = abi.decode(_actionData, (address, uint256));
IVault(vaultProxy).mintShares(target, amount);
}
/// @dev Helper to remove a tracked asset from the fund
function __vaultActionRemoveTrackedAsset(bytes memory _actionData) private {
address asset = abi.decode(_actionData, (address));
// Allowing this to fail silently makes it cheaper and simpler
// for Extensions to not query for the denomination asset
if (asset != denominationAsset) {
IVault(vaultProxy).removeTrackedAsset(asset);
}
}
/// @dev Helper to transfer fund shares from one account to another
function __vaultActionTransferShares(bytes memory _actionData) private {
(address from, address to, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).transferShares(from, to, amount);
}
/// @dev Helper to withdraw an asset from the VaultProxy to a given account
function __vaultActionWithdrawAssetTo(bytes memory _actionData) private {
(address asset, address target, uint256 amount) = abi.decode(
_actionData,
(address, address, uint256)
);
IVault(vaultProxy).withdrawAssetTo(asset, target, amount);
}
///////////////
// LIFECYCLE //
///////////////
/// @notice Initializes a fund with its core config
/// @param _denominationAsset The asset in which the fund's value should be denominated
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @dev Pseudo-constructor per proxy.
/// No need to assert access because this is called atomically on deployment,
/// and once it's called, it cannot be called again.
function init(address _denominationAsset, uint256 _sharesActionTimelock) external override {
require(denominationAsset == address(0), "init: Already initialized");
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_denominationAsset),
"init: Bad denomination asset"
);
denominationAsset = _denominationAsset;
sharesActionTimelock = _sharesActionTimelock;
}
/// @notice Configure the extensions of a fund
/// @param _feeManagerConfigData Encoded config for fees to enable
/// @param _policyManagerConfigData Encoded config for policies to enable
/// @dev No need to assert anything beyond FundDeployer access.
/// Called atomically with init(), but after ComptrollerLib has been deployed,
/// giving access to its state and interface
function configureExtensions(
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external override onlyFundDeployer {
if (_feeManagerConfigData.length > 0) {
IExtension(FEE_MANAGER).setConfigForFund(_feeManagerConfigData);
}
if (_policyManagerConfigData.length > 0) {
IExtension(POLICY_MANAGER).setConfigForFund(_policyManagerConfigData);
}
}
/// @notice Activates the fund by attaching a VaultProxy and activating all Extensions
/// @param _vaultProxy The VaultProxy to attach to the fund
/// @param _isMigration True if a migrated fund is being activated
/// @dev No need to assert anything beyond FundDeployer access.
function activate(address _vaultProxy, bool _isMigration) external override onlyFundDeployer {
vaultProxy = _vaultProxy;
emit VaultProxySet(_vaultProxy);
if (_isMigration) {
// Distribute any shares in the VaultProxy to the fund owner.
// This is a mechanism to ensure that even in the edge case of a fund being unable
// to payout fee shares owed during migration, these shares are not lost.
uint256 sharesDue = ERC20(_vaultProxy).balanceOf(_vaultProxy);
if (sharesDue > 0) {
IVault(_vaultProxy).transferShares(
_vaultProxy,
IVault(_vaultProxy).getOwner(),
sharesDue
);
emit MigratedSharesDuePaid(sharesDue);
}
}
// Note: a future release could consider forcing the adding of a tracked asset here,
// just in case a fund is migrating from an old configuration where they are not able
// to remove an asset to get under the tracked assets limit
IVault(_vaultProxy).addTrackedAsset(denominationAsset);
// Activate extensions
IExtension(FEE_MANAGER).activateForFund(_isMigration);
IExtension(INTEGRATION_MANAGER).activateForFund(_isMigration);
IExtension(POLICY_MANAGER).activateForFund(_isMigration);
}
/// @notice Remove the config for a fund
/// @dev No need to assert anything beyond FundDeployer access.
/// Calling onlyNotPaused here rather than in the FundDeployer allows
/// the owner to potentially override the pause and rescue unpaid fees.
function destruct()
external
override
onlyFundDeployer
onlyNotPaused
allowsPermissionedVaultAction
{
// Failsafe to protect the libs against selfdestruct
require(!isLib, "destruct: Only delegate callable");
// Deactivate the extensions
IExtension(FEE_MANAGER).deactivateForFund();
IExtension(INTEGRATION_MANAGER).deactivateForFund();
IExtension(POLICY_MANAGER).deactivateForFund();
// Delete storage of ComptrollerProxy
// There should never be ETH in the ComptrollerLib, so no need to waste gas
// to get the fund owner
selfdestruct(address(0));
}
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross asset value (GAV) of the fund
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return gav_ The fund GAV
/// @return isValid_ True if the conversion rates used to derive the GAV are all valid
function calcGav(bool _requireFinality) public override returns (uint256 gav_, bool isValid_) {
address vaultProxyAddress = vaultProxy;
address[] memory assets = IVault(vaultProxyAddress).getTrackedAssets();
if (assets.length == 0) {
return (0, true);
}
uint256[] memory balances = new uint256[](assets.length);
for (uint256 i; i < assets.length; i++) {
balances[i] = __finalizeIfSynthAndGetAssetBalance(
vaultProxyAddress,
assets[i],
_requireFinality
);
}
(gav_, isValid_) = IValueInterpreter(VALUE_INTERPRETER).calcCanonicalAssetsTotalValue(
assets,
balances,
denominationAsset
);
return (gav_, isValid_);
}
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
override
returns (uint256 grossShareValue_, bool isValid_)
{
uint256 gav;
(gav, isValid_) = calcGav(_requireFinality);
grossShareValue_ = __calcGrossShareValue(
gav,
ERC20(vaultProxy).totalSupply(),
10**uint256(ERC20(denominationAsset).decimals())
);
return (grossShareValue_, isValid_);
}
/// @dev Helper for calculating the gross share value
function __calcGrossShareValue(
uint256 _gav,
uint256 _sharesSupply,
uint256 _denominationAssetUnit
) private pure returns (uint256 grossShareValue_) {
if (_sharesSupply == 0) {
return _denominationAssetUnit;
}
return _gav.mul(SHARES_UNIT).div(_sharesSupply);
}
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
)
external
onlyNotPaused
locksReentrance
allowsPermissionedVaultAction
returns (uint256[] memory sharesReceivedAmounts_)
{
require(_buyers.length > 0, "buyShares: Empty _buyers");
require(
_buyers.length == _investmentAmounts.length &&
_buyers.length == _minSharesQuantities.length,
"buyShares: Unequal arrays"
);
address vaultProxyCopy = vaultProxy;
__assertIsActive(vaultProxyCopy);
require(
!IDispatcher(DISPATCHER).hasMigrationRequest(vaultProxyCopy),
"buyShares: Pending migration"
);
(uint256 gav, bool gavIsValid) = calcGav(true);
require(gavIsValid, "buyShares: Invalid GAV");
__buySharesSetupHook(msg.sender, _investmentAmounts, gav);
address denominationAssetCopy = denominationAsset;
uint256 sharePrice = __calcGrossShareValue(
gav,
ERC20(vaultProxyCopy).totalSupply(),
10**uint256(ERC20(denominationAssetCopy).decimals())
);
sharesReceivedAmounts_ = new uint256[](_buyers.length);
for (uint256 i; i < _buyers.length; i++) {
sharesReceivedAmounts_[i] = __buyShares(
_buyers[i],
_investmentAmounts[i],
_minSharesQuantities[i],
vaultProxyCopy,
sharePrice,
gav,
denominationAssetCopy
);
gav = gav.add(_investmentAmounts[i]);
}
__buySharesCompletedHook(msg.sender, sharesReceivedAmounts_, gav);
return sharesReceivedAmounts_;
}
/// @dev Helper to buy shares
function __buyShares(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
address _vaultProxy,
uint256 _sharePrice,
uint256 _preBuySharesGav,
address _denominationAsset
) private timelockedSharesAction(_buyer) returns (uint256 sharesReceived_) {
require(_investmentAmount > 0, "__buyShares: Empty _investmentAmount");
// Gives Extensions a chance to run logic prior to the minting of bought shares
__preBuySharesHook(_buyer, _investmentAmount, _minSharesQuantity, _preBuySharesGav);
// Calculate the amount of shares to issue with the investment amount
uint256 sharesIssued = _investmentAmount.mul(SHARES_UNIT).div(_sharePrice);
// Mint shares to the buyer
uint256 prevBuyerShares = ERC20(_vaultProxy).balanceOf(_buyer);
IVault(_vaultProxy).mintShares(_buyer, sharesIssued);
// Transfer the investment asset to the fund.
// Does not follow the checks-effects-interactions pattern, but it is preferred
// to have the final state of the VaultProxy prior to running __postBuySharesHook().
ERC20(_denominationAsset).safeTransferFrom(msg.sender, _vaultProxy, _investmentAmount);
// Gives Extensions a chance to run logic after shares are issued
__postBuySharesHook(_buyer, _investmentAmount, sharesIssued, _preBuySharesGav);
// The number of actual shares received may differ from shares issued due to
// how the PostBuyShares hooks are invoked by Extensions (i.e., fees)
sharesReceived_ = ERC20(_vaultProxy).balanceOf(_buyer).sub(prevBuyerShares);
require(
sharesReceived_ >= _minSharesQuantity,
"__buyShares: Shares received < _minSharesQuantity"
);
emit SharesBought(msg.sender, _buyer, _investmentAmount, sharesIssued, sharesReceived_);
return sharesReceived_;
}
/// @dev Helper for Extension actions after all __buyShares() calls are made
function __buySharesCompletedHook(
address _caller,
uint256[] memory _sharesReceivedAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesCompleted,
abi.encode(_caller, _sharesReceivedAmounts),
_gav
);
}
/// @dev Helper for Extension actions before any __buyShares() calls are made
function __buySharesSetupHook(
address _caller,
uint256[] memory _investmentAmounts,
uint256 _gav
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts, _gav)
);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.BuySharesSetup,
abi.encode(_caller, _investmentAmounts),
_gav
);
}
/// @dev Helper for Extension actions immediately prior to issuing shares.
/// This could be cleaned up so both Extensions take the same encoded args and handle GAV
/// in the same way, but there is not the obvious need for gas savings of recycling
/// the GAV value for the current policies as there is for the fees.
function __preBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity,
uint256 _gav
) private {
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity),
_gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PreBuyShares,
abi.encode(_buyer, _investmentAmount, _minSharesQuantity, _gav)
);
}
/// @dev Helper for Extension actions immediately after issuing shares.
/// Same comment applies from __preBuySharesHook() above.
function __postBuySharesHook(
address _buyer,
uint256 _investmentAmount,
uint256 _sharesIssued,
uint256 _preBuySharesGav
) private {
uint256 gav = _preBuySharesGav.add(_investmentAmount);
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued),
gav
);
IPolicyManager(POLICY_MANAGER).validatePolicies(
address(this),
IPolicyManager.PolicyHook.PostBuyShares,
abi.encode(_buyer, _investmentAmount, _sharesIssued, gav)
);
}
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
return
__redeemShares(
msg.sender,
ERC20(vaultProxy).balanceOf(msg.sender),
new address[](0),
new address[](0)
);
}
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
) external returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_) {
return __redeemShares(msg.sender, _sharesQuantity, _additionalAssets, _assetsToSkip);
}
/// @dev Helper to parse an array of payout assets during redemption, taking into account
/// additional assets and assets to skip. _assetsToSkip ignores _additionalAssets.
/// All input arrays are assumed to be unique.
function __parseRedemptionPayoutAssets(
address[] memory _trackedAssets,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
) private pure returns (address[] memory payoutAssets_) {
address[] memory trackedAssetsToPayout = _trackedAssets.removeItems(_assetsToSkip);
if (_additionalAssets.length == 0) {
return trackedAssetsToPayout;
}
// Add additional assets. Duplicates of trackedAssets are ignored.
bool[] memory indexesToAdd = new bool[](_additionalAssets.length);
uint256 additionalItemsCount;
for (uint256 i; i < _additionalAssets.length; i++) {
if (!trackedAssetsToPayout.contains(_additionalAssets[i])) {
indexesToAdd[i] = true;
additionalItemsCount++;
}
}
if (additionalItemsCount == 0) {
return trackedAssetsToPayout;
}
payoutAssets_ = new address[](trackedAssetsToPayout.length.add(additionalItemsCount));
for (uint256 i; i < trackedAssetsToPayout.length; i++) {
payoutAssets_[i] = trackedAssetsToPayout[i];
}
uint256 payoutAssetsIndex = trackedAssetsToPayout.length;
for (uint256 i; i < _additionalAssets.length; i++) {
if (indexesToAdd[i]) {
payoutAssets_[payoutAssetsIndex] = _additionalAssets[i];
payoutAssetsIndex++;
}
}
return payoutAssets_;
}
/// @dev Helper for system actions immediately prior to redeeming shares.
/// Policy validation is not currently allowed on redemption, to ensure continuous redeemability.
function __preRedeemSharesHook(address _redeemer, uint256 _sharesQuantity)
private
allowsPermissionedVaultAction
{
try
IFeeManager(FEE_MANAGER).invokeHook(
IFeeManager.FeeHook.PreRedeemShares,
abi.encode(_redeemer, _sharesQuantity),
0
)
{} catch (bytes memory reason) {
emit PreRedeemSharesHookFailed(reason, _redeemer, _sharesQuantity);
}
}
/// @dev Helper to redeem shares.
/// This function should never fail without a way to bypass the failure, which is assured
/// through two mechanisms:
/// 1. The FeeManager is called with the try/catch pattern to assure that calls to it
/// can never block redemption.
/// 2. If a token fails upon transfer(), that token can be skipped (and its balance forfeited)
/// by explicitly specifying _assetsToSkip.
/// Because of these assurances, shares should always be redeemable, with the exception
/// of the timelock period on shares actions that must be respected.
function __redeemShares(
address _redeemer,
uint256 _sharesQuantity,
address[] memory _additionalAssets,
address[] memory _assetsToSkip
)
private
locksReentrance
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_)
{
require(_sharesQuantity > 0, "__redeemShares: _sharesQuantity must be >0");
require(
_additionalAssets.isUniqueSet(),
"__redeemShares: _additionalAssets contains duplicates"
);
require(_assetsToSkip.isUniqueSet(), "__redeemShares: _assetsToSkip contains duplicates");
IVault vaultProxyContract = IVault(vaultProxy);
// Only apply the sharesActionTimelock when a migration is not pending
if (!IDispatcher(DISPATCHER).hasMigrationRequest(address(vaultProxyContract))) {
__assertSharesActionNotTimelocked(_redeemer);
acctToLastSharesAction[_redeemer] = block.timestamp;
}
// When a fund is paused, settling fees will be skipped
if (!__fundIsPaused()) {
// Note that if a fee with `SettlementType.Direct` is charged here (i.e., not `Mint`),
// then those fee shares will be transferred from the user's balance rather
// than reallocated from the sharesQuantity being redeemed.
__preRedeemSharesHook(_redeemer, _sharesQuantity);
}
// Check the shares quantity against the user's balance after settling fees
ERC20 sharesContract = ERC20(address(vaultProxyContract));
require(
_sharesQuantity <= sharesContract.balanceOf(_redeemer),
"__redeemShares: Insufficient shares"
);
// Parse the payout assets given optional params to add or skip assets.
// Note that there is no validation that the _additionalAssets are known assets to
// the protocol. This means that the redeemer could specify a malicious asset,
// but since all state-changing, user-callable functions on this contract share the
// non-reentrant modifier, there is nowhere to perform a reentrancy attack.
payoutAssets_ = __parseRedemptionPayoutAssets(
vaultProxyContract.getTrackedAssets(),
_additionalAssets,
_assetsToSkip
);
require(payoutAssets_.length > 0, "__redeemShares: No payout assets");
// Destroy the shares.
// Must get the shares supply before doing so.
uint256 sharesSupply = sharesContract.totalSupply();
vaultProxyContract.burnShares(_redeemer, _sharesQuantity);
// Calculate and transfer payout asset amounts due to redeemer
payoutAmounts_ = new uint256[](payoutAssets_.length);
address denominationAssetCopy = denominationAsset;
for (uint256 i; i < payoutAssets_.length; i++) {
uint256 assetBalance = __finalizeIfSynthAndGetAssetBalance(
address(vaultProxyContract),
payoutAssets_[i],
true
);
// If all remaining shares are being redeemed, the logic changes slightly
if (_sharesQuantity == sharesSupply) {
payoutAmounts_[i] = assetBalance;
// Remove every tracked asset, except the denomination asset
if (payoutAssets_[i] != denominationAssetCopy) {
vaultProxyContract.removeTrackedAsset(payoutAssets_[i]);
}
} else {
payoutAmounts_[i] = assetBalance.mul(_sharesQuantity).div(sharesSupply);
}
// Transfer payout asset to redeemer
if (payoutAmounts_[i] > 0) {
vaultProxyContract.withdrawAssetTo(payoutAssets_[i], _redeemer, payoutAmounts_[i]);
}
}
emit SharesRedeemed(_redeemer, _sharesQuantity, payoutAssets_, payoutAmounts_);
return (payoutAssets_, payoutAmounts_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view override returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the routes for the various contracts used by all funds
/// @return dispatcher_ The `DISPATCHER` variable value
/// @return feeManager_ The `FEE_MANAGER` variable value
/// @return fundDeployer_ The `FUND_DEPLOYER` variable value
/// @return integrationManager_ The `INTEGRATION_MANAGER` variable value
/// @return policyManager_ The `POLICY_MANAGER` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getLibRoutes()
external
view
returns (
address dispatcher_,
address feeManager_,
address fundDeployer_,
address integrationManager_,
address policyManager_,
address primitivePriceFeed_,
address valueInterpreter_
)
{
return (
DISPATCHER,
FEE_MANAGER,
FUND_DEPLOYER,
INTEGRATION_MANAGER,
POLICY_MANAGER,
PRIMITIVE_PRICE_FEED,
VALUE_INTERPRETER
);
}
/// @notice Gets the `overridePause` variable
/// @return overridePause_ The `overridePause` variable value
function getOverridePause() external view returns (bool overridePause_) {
return overridePause;
}
/// @notice Gets the `sharesActionTimelock` variable
/// @return sharesActionTimelock_ The `sharesActionTimelock` variable value
function getSharesActionTimelock() external view returns (uint256 sharesActionTimelock_) {
return sharesActionTimelock;
}
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view override returns (address vaultProxy_) {
return vaultProxy;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../../../persistent/dispatcher/IDispatcher.sol";
import "../../../../persistent/vault/VaultLibBase1.sol";
import "./IVault.sol";
/// @title VaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice The per-release proxiable library contract for VaultProxy
/// @dev The difference in terminology between "asset" and "trackedAsset" is intentional.
/// A fund might actually have asset balances of un-tracked assets,
/// but only tracked assets are used in gav calculations.
/// Note that this contract inherits VaultLibSafeMath (a verbatim Open Zeppelin SafeMath copy)
/// from SharesTokenBase via VaultLibBase1
contract VaultLib is VaultLibBase1, IVault {
using SafeERC20 for ERC20;
// Before updating TRACKED_ASSETS_LIMIT in the future, it is important to consider:
// 1. The highest tracked assets limit ever allowed in the protocol
// 2. That the next value will need to be respected by all future releases
uint256 private constant TRACKED_ASSETS_LIMIT = 20;
modifier onlyAccessor() {
require(msg.sender == accessor, "Only the designated accessor can make this call");
_;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the account that is allowed to migrate a fund to new releases
/// @param _nextMigrator The account to set as the allowed migrator
/// @dev Set to address(0) to remove the migrator.
function setMigrator(address _nextMigrator) external {
require(msg.sender == owner, "setMigrator: Only the owner can call this function");
address prevMigrator = migrator;
require(_nextMigrator != prevMigrator, "setMigrator: Value already set");
migrator = _nextMigrator;
emit MigratorSet(prevMigrator, _nextMigrator);
}
///////////
// VAULT //
///////////
/// @notice Adds a tracked asset to the fund
/// @param _asset The asset to add
/// @dev Allows addition of already tracked assets to fail silently.
function addTrackedAsset(address _asset) external override onlyAccessor {
if (!isTrackedAsset(_asset)) {
require(
trackedAssets.length < TRACKED_ASSETS_LIMIT,
"addTrackedAsset: Limit exceeded"
);
assetToIsTracked[_asset] = true;
trackedAssets.push(_asset);
emit TrackedAssetAdded(_asset);
}
}
/// @notice Grants an allowance to a spender to use the fund's asset
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function approveAssetSpender(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).approve(_target, _amount);
}
/// @notice Makes an arbitrary call with this contract as the sender
/// @param _contract The contract to call
/// @param _callData The call data for the call
function callOnContract(address _contract, bytes calldata _callData)
external
override
onlyAccessor
{
(bool success, bytes memory returnData) = _contract.call(_callData);
require(success, string(returnData));
}
/// @notice Removes a tracked asset from the fund
/// @param _asset The asset to remove
function removeTrackedAsset(address _asset) external override onlyAccessor {
__removeTrackedAsset(_asset);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function withdrawAssetTo(
address _asset,
address _target,
uint256 _amount
) external override onlyAccessor {
ERC20(_asset).safeTransfer(_target, _amount);
emit AssetWithdrawn(_asset, _target, _amount);
}
/// @dev Helper to the get the Vault's balance of a given asset
function __getAssetBalance(address _asset) private view returns (uint256 balance_) {
return ERC20(_asset).balanceOf(address(this));
}
/// @dev Helper to remove an asset from a fund's tracked assets.
/// Allows removal of non-tracked asset to fail silently.
function __removeTrackedAsset(address _asset) private {
if (isTrackedAsset(_asset)) {
assetToIsTracked[_asset] = false;
uint256 trackedAssetsCount = trackedAssets.length;
for (uint256 i = 0; i < trackedAssetsCount; i++) {
if (trackedAssets[i] == _asset) {
if (i < trackedAssetsCount - 1) {
trackedAssets[i] = trackedAssets[trackedAssetsCount - 1];
}
trackedAssets.pop();
break;
}
}
emit TrackedAssetRemoved(_asset);
}
}
////////////
// SHARES //
////////////
/// @notice Burns fund shares from a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function burnShares(address _target, uint256 _amount) external override onlyAccessor {
__burn(_target, _amount);
}
/// @notice Mints fund shares to a particular account
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to mint
function mintShares(address _target, uint256 _amount) external override onlyAccessor {
__mint(_target, _amount);
}
/// @notice Transfers fund shares from one account to another
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function transferShares(
address _from,
address _to,
uint256 _amount
) external override onlyAccessor {
__transfer(_from, _to, _amount);
}
// ERC20 overrides
/// @dev Disallows the standard ERC20 approve() function
function approve(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @notice Gets the `symbol` value of the shares token
/// @return symbol_ The `symbol` value
/// @dev Defers the shares symbol value to the Dispatcher contract
function symbol() public view override returns (string memory symbol_) {
return IDispatcher(creator).getSharesTokenSymbol();
}
/// @dev Disallows the standard ERC20 transfer() function
function transfer(address, uint256) public override returns (bool) {
revert("Unimplemented");
}
/// @dev Disallows the standard ERC20 transferFrom() function
function transferFrom(
address,
address,
uint256
) public override returns (bool) {
revert("Unimplemented");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `accessor` variable
/// @return accessor_ The `accessor` variable value
function getAccessor() external view override returns (address accessor_) {
return accessor;
}
/// @notice Gets the `creator` variable
/// @return creator_ The `creator` variable value
function getCreator() external view returns (address creator_) {
return creator;
}
/// @notice Gets the `migrator` variable
/// @return migrator_ The `migrator` variable value
function getMigrator() external view returns (address migrator_) {
return migrator;
}
/// @notice Gets the `owner` variable
/// @return owner_ The `owner` variable value
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the `trackedAssets` variable
/// @return trackedAssets_ The `trackedAssets` variable value
function getTrackedAssets() external view override returns (address[] memory trackedAssets_) {
return trackedAssets;
}
/// @notice Check whether an address is a tracked asset of the fund
/// @param _asset The address to check
/// @return isTrackedAsset_ True if the address is a tracked asset of the fund
function isTrackedAsset(address _asset) public view override returns (bool isTrackedAsset_) {
return assetToIsTracked[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../price-feeds/primitives/IPrimitivePriceFeed.sol";
import "./IValueInterpreter.sol";
/// @title ValueInterpreter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Interprets price feeds to provide covert value between asset pairs
/// @dev This contract contains several "live" value calculations, which for this release are simply
/// aliases to their "canonical" value counterparts since the only primitive price feed (Chainlink)
/// is immutable in this contract and only has one type of value. Including the "live" versions of
/// functions only serves as a placeholder for infrastructural components and plugins (e.g., policies)
/// to explicitly define the types of values that they should (and will) be using in a future release.
contract ValueInterpreter is IValueInterpreter {
using SafeMath for uint256;
address private immutable AGGREGATED_DERIVATIVE_PRICE_FEED;
address private immutable PRIMITIVE_PRICE_FEED;
constructor(address _primitivePriceFeed, address _aggregatedDerivativePriceFeed) public {
AGGREGATED_DERIVATIVE_PRICE_FEED = _aggregatedDerivativePriceFeed;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
// EXTERNAL FUNCTIONS
/// @notice An alias of calcCanonicalAssetsTotalValue
function calcLiveAssetsTotalValue(
address[] calldata _baseAssets,
uint256[] calldata _amounts,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetsTotalValue(_baseAssets, _amounts, _quoteAsset);
}
/// @notice An alias of calcCanonicalAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external override returns (uint256 value_, bool isValid_) {
return calcCanonicalAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the total value of given amounts of assets in a single quote asset
/// @param _baseAssets The assets to convert
/// @param _amounts The amounts of the _baseAssets to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The sum value of _baseAssets, denominated in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetsTotalValue(
address[] memory _baseAssets,
uint256[] memory _amounts,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
require(
_baseAssets.length == _amounts.length,
"calcCanonicalAssetsTotalValue: Arrays unequal lengths"
);
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetsTotalValue: Unsupported _quoteAsset"
);
isValid_ = true;
for (uint256 i; i < _baseAssets.length; i++) {
(uint256 assetValue, bool assetValueIsValid) = __calcAssetValue(
_baseAssets[i],
_amounts[i],
_quoteAsset
);
value_ = value_.add(assetValue);
if (!assetValueIsValid) {
isValid_ = false;
}
}
return (value_, isValid_);
}
/// @notice Calculates the value of a given amount of one asset in terms of another asset
/// @param _baseAsset The asset from which to convert
/// @param _amount The amount of the _baseAsset to convert
/// @param _quoteAsset The asset to which to convert
/// @return value_ The equivalent quantity in the _quoteAsset
/// @return isValid_ True if the price feed rates used to derive value are all valid
/// @dev Does not alter protocol state,
/// but not a view because calls to price feeds can potentially update third party state
function calcCanonicalAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public override returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
require(
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_quoteAsset),
"calcCanonicalAssetValue: Unsupported _quoteAsset"
);
return __calcAssetValue(_baseAsset, _amount, _quoteAsset);
}
// PRIVATE FUNCTIONS
/// @dev Helper to differentially calculate an asset value
/// based on if it is a primitive or derivative asset.
function __calcAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
if (_baseAsset == _quoteAsset || _amount == 0) {
return (_amount, true);
}
// Handle case that asset is a primitive
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_baseAsset)) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).calcCanonicalValue(
_baseAsset,
_amount,
_quoteAsset
);
}
// Handle case that asset is a derivative
address derivativePriceFeed = IAggregatedDerivativePriceFeed(
AGGREGATED_DERIVATIVE_PRICE_FEED
)
.getPriceFeedForDerivative(_baseAsset);
if (derivativePriceFeed != address(0)) {
return __calcDerivativeValue(derivativePriceFeed, _baseAsset, _amount, _quoteAsset);
}
revert("__calcAssetValue: Unsupported _baseAsset");
}
/// @dev Helper to calculate the value of a derivative in an arbitrary asset.
/// Handles multiple underlying assets (e.g., Uniswap and Balancer pool tokens).
/// Handles underlying assets that are also derivatives (e.g., a cDAI-ETH LP)
function __calcDerivativeValue(
address _derivativePriceFeed,
address _derivative,
uint256 _amount,
address _quoteAsset
) private returns (uint256 value_, bool isValid_) {
(address[] memory underlyings, uint256[] memory underlyingAmounts) = IDerivativePriceFeed(
_derivativePriceFeed
)
.calcUnderlyingValues(_derivative, _amount);
require(underlyings.length > 0, "__calcDerivativeValue: No underlyings");
require(
underlyings.length == underlyingAmounts.length,
"__calcDerivativeValue: Arrays unequal lengths"
);
// Let validity be negated if any of the underlying value calculations are invalid
isValid_ = true;
for (uint256 i = 0; i < underlyings.length; i++) {
(uint256 underlyingValue, bool underlyingValueIsValid) = __calcAssetValue(
underlyings[i],
underlyingAmounts[i],
_quoteAsset
);
if (!underlyingValueIsValid) {
isValid_ = false;
}
value_ = value_.add(underlyingValue);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AGGREGATED_DERIVATIVE_PRICE_FEED` variable
/// @return aggregatedDerivativePriceFeed_ The `AGGREGATED_DERIVATIVE_PRICE_FEED` variable value
function getAggregatedDerivativePriceFeed()
external
view
returns (address aggregatedDerivativePriceFeed_)
{
return AGGREGATED_DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDispatcher Interface
/// @author Enzyme Council <[email protected]>
interface IDispatcher {
function cancelMigration(address _vaultProxy, bool _bypassFailure) external;
function claimOwnership() external;
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external returns (address vaultProxy_);
function executeMigration(address _vaultProxy, bool _bypassFailure) external;
function getCurrentFundDeployer() external view returns (address currentFundDeployer_);
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
returns (address fundDeployer_);
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
);
function getMigrationTimelock() external view returns (uint256 migrationTimelock_);
function getNominatedOwner() external view returns (address nominatedOwner_);
function getOwner() external view returns (address owner_);
function getSharesTokenSymbol() external view returns (string memory sharesTokenSymbol_);
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
returns (uint256 secondsRemaining_);
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
returns (bool hasExecutableRequest_);
function hasMigrationRequest(address _vaultProxy)
external
view
returns (bool hasMigrationRequest_);
function removeNominatedOwner() external;
function setCurrentFundDeployer(address _nextFundDeployer) external;
function setMigrationTimelock(uint256 _nextTimelock) external;
function setNominatedOwner(address _nextNominatedOwner) external;
function setSharesTokenSymbol(string calldata _nextSymbol) external;
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title FeeManager Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for the FeeManager
interface IFeeManager {
// No fees for the current release are implemented post-redeemShares
enum FeeHook {
Continuous,
BuySharesSetup,
PreBuyShares,
PostBuyShares,
BuySharesCompleted,
PreRedeemShares
}
enum SettlementType {None, Direct, Mint, Burn, MintSharesOutstanding, BurnSharesOutstanding}
function invokeHook(
FeeHook,
bytes calldata,
uint256
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IPrimitivePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for primitive price feeds
interface IPrimitivePriceFeed {
function calcCanonicalValue(
address,
uint256,
address
) external view returns (uint256, bool);
function calcLiveValue(
address,
uint256,
address
) external view returns (uint256, bool);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IValueInterpreter interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for ValueInterpreter
interface IValueInterpreter {
function calcCanonicalAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcCanonicalAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
function calcLiveAssetValue(
address,
uint256,
address
) external returns (uint256, bool);
function calcLiveAssetsTotalValue(
address[] calldata,
uint256[] calldata,
address
) external returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../interfaces/ISynthetixAddressResolver.sol";
import "../interfaces/ISynthetixExchanger.sol";
/// @title AssetFinalityResolver Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that helps achieve asset finality
abstract contract AssetFinalityResolver {
address internal immutable SYNTHETIX_ADDRESS_RESOLVER;
address internal immutable SYNTHETIX_PRICE_FEED;
constructor(address _synthetixPriceFeed, address _synthetixAddressResolver) public {
SYNTHETIX_ADDRESS_RESOLVER = _synthetixAddressResolver;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
}
/// @dev Helper to finalize a Synth balance at a given target address and return its balance
function __finalizeIfSynthAndGetAssetBalance(
address _target,
address _asset,
bool _requireFinality
) internal returns (uint256 assetBalance_) {
bytes32 currencyKey = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED).getCurrencyKeyForSynth(
_asset
);
if (currencyKey != 0) {
address synthetixExchanger = ISynthetixAddressResolver(SYNTHETIX_ADDRESS_RESOLVER)
.requireAndGetAddress(
"Exchanger",
"finalizeAndGetAssetBalance: Missing Exchanger"
);
try ISynthetixExchanger(synthetixExchanger).settle(_target, currencyKey) {} catch {
require(!_requireFinality, "finalizeAndGetAssetBalance: Cannot settle Synth");
}
}
return ERC20(_asset).balanceOf(_target);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `SYNTHETIX_ADDRESS_RESOLVER` variable
/// @return synthetixAddressResolver_ The `SYNTHETIX_ADDRESS_RESOLVER` variable value
function getSynthetixAddressResolver()
external
view
returns (address synthetixAddressResolver_)
{
return SYNTHETIX_ADDRESS_RESOLVER;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../../../../interfaces/ISynthetixAddressResolver.sol";
import "../../../../interfaces/ISynthetixExchangeRates.sol";
import "../../../../interfaces/ISynthetixProxyERC20.sol";
import "../../../../interfaces/ISynthetixSynth.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title SynthetixPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Synthetix oracles as price sources
contract SynthetixPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event SynthAdded(address indexed synth, bytes32 currencyKey);
event SynthCurrencyKeyUpdated(
address indexed synth,
bytes32 prevCurrencyKey,
bytes32 nextCurrencyKey
);
uint256 private constant SYNTH_UNIT = 10**18;
address private immutable ADDRESS_RESOLVER;
address private immutable SUSD;
mapping(address => bytes32) private synthToCurrencyKey;
constructor(
address _dispatcher,
address _addressResolver,
address _sUSD,
address[] memory _synths
) public DispatcherOwnerMixin(_dispatcher) {
ADDRESS_RESOLVER = _addressResolver;
SUSD = _sUSD;
address[] memory sUSDSynths = new address[](1);
sUSDSynths[0] = _sUSD;
__addSynths(sUSDSynths);
__addSynths(_synths);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = SUSD;
underlyingAmounts_ = new uint256[](1);
bytes32 currencyKey = getCurrencyKeyForSynth(_derivative);
require(currencyKey != 0, "calcUnderlyingValues: _derivative is not supported");
address exchangeRates = ISynthetixAddressResolver(ADDRESS_RESOLVER).requireAndGetAddress(
"ExchangeRates",
"calcUnderlyingValues: Missing ExchangeRates"
);
(uint256 rate, bool isInvalid) = ISynthetixExchangeRates(exchangeRates).rateAndInvalid(
currencyKey
);
require(!isInvalid, "calcUnderlyingValues: _derivative rate is not valid");
underlyingAmounts_[0] = _derivativeAmount.mul(rate).div(SYNTH_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return getCurrencyKeyForSynth(_asset) != 0;
}
/////////////////////
// SYNTHS REGISTRY //
/////////////////////
/// @notice Adds Synths to the price feed
/// @param _synths Synths to add
function addSynths(address[] calldata _synths) external onlyDispatcherOwner {
require(_synths.length > 0, "addSynths: Empty _synths");
__addSynths(_synths);
}
/// @notice Updates the cached currencyKey value for specified Synths
/// @param _synths Synths to update
/// @dev Anybody can call this function
function updateSynthCurrencyKeys(address[] calldata _synths) external {
require(_synths.length > 0, "updateSynthCurrencyKeys: Empty _synths");
for (uint256 i; i < _synths.length; i++) {
bytes32 prevCurrencyKey = synthToCurrencyKey[_synths[i]];
require(prevCurrencyKey != 0, "updateSynthCurrencyKeys: Synth not set");
bytes32 nextCurrencyKey = __getCurrencyKey(_synths[i]);
require(
nextCurrencyKey != prevCurrencyKey,
"updateSynthCurrencyKeys: Synth has correct currencyKey"
);
synthToCurrencyKey[_synths[i]] = nextCurrencyKey;
emit SynthCurrencyKeyUpdated(_synths[i], prevCurrencyKey, nextCurrencyKey);
}
}
/// @dev Helper to add Synths
function __addSynths(address[] memory _synths) private {
for (uint256 i; i < _synths.length; i++) {
require(synthToCurrencyKey[_synths[i]] == 0, "__addSynths: Value already set");
bytes32 currencyKey = __getCurrencyKey(_synths[i]);
require(currencyKey != 0, "__addSynths: No currencyKey");
synthToCurrencyKey[_synths[i]] = currencyKey;
emit SynthAdded(_synths[i], currencyKey);
}
}
/// @dev Helper to query a currencyKey from Synthetix
function __getCurrencyKey(address _synthProxy) private view returns (bytes32 currencyKey_) {
return ISynthetixSynth(ISynthetixProxyERC20(_synthProxy).target()).currencyKey();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_RESOLVER` variable
/// @return addressResolver_ The `ADDRESS_RESOLVER` variable value
function getAddressResolver() external view returns (address) {
return ADDRESS_RESOLVER;
}
/// @notice Gets the currencyKey for multiple given Synths
/// @return currencyKeys_ The currencyKey values
function getCurrencyKeysForSynths(address[] calldata _synths)
external
view
returns (bytes32[] memory currencyKeys_)
{
currencyKeys_ = new bytes32[](_synths.length);
for (uint256 i; i < _synths.length; i++) {
currencyKeys_[i] = synthToCurrencyKey[_synths[i]];
}
return currencyKeys_;
}
/// @notice Gets the `SUSD` variable
/// @return susd_ The `SUSD` variable value
function getSUSD() external view returns (address susd_) {
return SUSD;
}
/// @notice Gets the currencyKey for a given Synth
/// @return currencyKey_ The currencyKey value
function getCurrencyKeyForSynth(address _synth) public view returns (bytes32 currencyKey_) {
return synthToCurrencyKey[_synth];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixAddressResolver Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixAddressResolver {
function requireAndGetAddress(bytes32, string calldata) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchanger Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchanger {
function getAmountsForExchange(
uint256,
bytes32,
bytes32
)
external
view
returns (
uint256,
uint256,
uint256
);
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetix Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetix {
function exchangeOnBehalfWithTracking(
address,
bytes32,
uint256,
bytes32,
address,
bytes32
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixExchangeRates Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixExchangeRates {
function rateAndInvalid(bytes32) external view returns (uint256, bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixProxyERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixProxyERC20 {
function target() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ISynthetixSynth Interface
/// @author Enzyme Council <[email protected]>
interface ISynthetixSynth {
function currencyKey() external view returns (bytes32);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../persistent/dispatcher/IDispatcher.sol";
/// @title DispatcherOwnerMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract that defers ownership to the owner of Dispatcher
abstract contract DispatcherOwnerMixin {
address internal immutable DISPATCHER;
modifier onlyDispatcherOwner() {
require(
msg.sender == getOwner(),
"onlyDispatcherOwner: Only the Dispatcher owner can call this function"
);
_;
}
constructor(address _dispatcher) public {
DISPATCHER = _dispatcher;
}
/// @notice Gets the owner of this contract
/// @return owner_ The owner
/// @dev Ownership is deferred to the owner of the Dispatcher contract
function getOwner() public view returns (address owner_) {
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
/// @notice Simple interface for derivative price source oracle implementations
interface IDerivativePriceFeed {
function calcUnderlyingValues(address, uint256)
external
returns (address[] memory, uint256[] memory);
function isSupportedAsset(address) external view returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibBaseCore.sol";
/// @title VaultLibBase1 Contract
/// @author Enzyme Council <[email protected]>
/// @notice The first implementation of VaultLibBaseCore, with additional events and storage
/// @dev All subsequent implementations should inherit the previous implementation,
/// e.g., `VaultLibBase2 is VaultLibBase1`
/// DO NOT EDIT CONTRACT.
abstract contract VaultLibBase1 is VaultLibBaseCore {
event AssetWithdrawn(address indexed asset, address indexed target, uint256 amount);
event TrackedAssetAdded(address asset);
event TrackedAssetRemoved(address asset);
address[] internal trackedAssets;
mapping(address => bool) internal assetToIsTracked;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigratableVault.sol";
import "./utils/ProxiableVaultLib.sol";
import "./utils/SharesTokenBase.sol";
/// @title VaultLibBaseCore Contract
/// @author Enzyme Council <[email protected]>
/// @notice A persistent contract containing all required storage variables and
/// required functions for a VaultLib implementation
/// @dev DO NOT EDIT CONTRACT. If new events or storage are necessary, they should be added to
/// a numbered VaultLibBaseXXX that inherits the previous base. See VaultLibBase1.
abstract contract VaultLibBaseCore is IMigratableVault, ProxiableVaultLib, SharesTokenBase {
event AccessorSet(address prevAccessor, address nextAccessor);
event MigratorSet(address prevMigrator, address nextMigrator);
event OwnerSet(address prevOwner, address nextOwner);
event VaultLibSet(address prevVaultLib, address nextVaultLib);
address internal accessor;
address internal creator;
address internal migrator;
address internal owner;
// EXTERNAL FUNCTIONS
/// @notice Initializes the VaultProxy with core configuration
/// @param _owner The address to set as the fund owner
/// @param _accessor The address to set as the permissioned accessor of the VaultLib
/// @param _fundName The name of the fund
/// @dev Serves as a per-proxy pseudo-constructor
function init(
address _owner,
address _accessor,
string calldata _fundName
) external override {
require(creator == address(0), "init: Proxy already initialized");
creator = msg.sender;
sharesName = _fundName;
__setAccessor(_accessor);
__setOwner(_owner);
emit VaultLibSet(address(0), getVaultLib());
}
/// @notice Sets the permissioned accessor of the VaultLib
/// @param _nextAccessor The address to set as the permissioned accessor of the VaultLib
function setAccessor(address _nextAccessor) external override {
require(msg.sender == creator, "setAccessor: Only callable by the contract creator");
__setAccessor(_nextAccessor);
}
/// @notice Sets the VaultLib target for the VaultProxy
/// @param _nextVaultLib The address to set as the VaultLib
/// @dev This function is absolutely critical. __updateCodeAddress() validates that the
/// target is a valid Proxiable contract instance.
/// Does not block _nextVaultLib from being the same as the current VaultLib
function setVaultLib(address _nextVaultLib) external override {
require(msg.sender == creator, "setVaultLib: Only callable by the contract creator");
address prevVaultLib = getVaultLib();
__updateCodeAddress(_nextVaultLib);
emit VaultLibSet(prevVaultLib, _nextVaultLib);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether an account is allowed to migrate the VaultProxy
/// @param _who The account to check
/// @return canMigrate_ True if the account is allowed to migrate the VaultProxy
function canMigrate(address _who) public view virtual override returns (bool canMigrate_) {
return _who == owner || _who == migrator;
}
/// @notice Gets the VaultLib target for the VaultProxy
/// @return vaultLib_ The address of the VaultLib target
function getVaultLib() public view returns (address vaultLib_) {
assembly {
// solium-disable-line
vaultLib_ := sload(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc)
}
return vaultLib_;
}
// INTERNAL FUNCTIONS
/// @dev Helper to set the permissioned accessor of the VaultProxy.
/// Does not prevent the prevAccessor from being the _nextAccessor.
function __setAccessor(address _nextAccessor) internal {
require(_nextAccessor != address(0), "__setAccessor: _nextAccessor cannot be empty");
address prevAccessor = accessor;
accessor = _nextAccessor;
emit AccessorSet(prevAccessor, _nextAccessor);
}
/// @dev Helper to set the owner of the VaultProxy
function __setOwner(address _nextOwner) internal {
require(_nextOwner != address(0), "__setOwner: _nextOwner cannot be empty");
address prevOwner = owner;
require(_nextOwner != prevOwner, "__setOwner: _nextOwner is the current owner");
owner = _nextOwner;
emit OwnerSet(prevOwner, _nextOwner);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ProxiableVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A contract that defines the upgrade behavior for VaultLib instances
/// @dev The recommended implementation of the target of a proxy according to EIP-1822 and EIP-1967
/// Code position in storage is `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`,
/// which is "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc".
abstract contract ProxiableVaultLib {
/// @dev Updates the target of the proxy to be the contract at _nextVaultLib
function __updateCodeAddress(address _nextVaultLib) internal {
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_nextVaultLib).proxiableUUID(),
"__updateCodeAddress: _nextVaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_nextVaultLib
)
}
}
/// @notice Returns a unique bytes32 hash for VaultLib instances
/// @return uuid_ The bytes32 hash representing the UUID
/// @dev The UUID is `bytes32(keccak256('mln.proxiable.vaultlib'))`
function proxiableUUID() public pure returns (bytes32 uuid_) {
return 0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./VaultLibSafeMath.sol";
/// @title StandardERC20 Contract
/// @author Enzyme Council <[email protected]>
/// @notice Contains the storage, events, and default logic of an ERC20-compliant contract.
/// @dev The logic can be overridden by VaultLib implementations.
/// Adapted from OpenZeppelin 3.2.0.
/// DO NOT EDIT THIS CONTRACT.
abstract contract SharesTokenBase {
using VaultLibSafeMath for uint256;
event Approval(address indexed owner, address indexed spender, uint256 value);
event Transfer(address indexed from, address indexed to, uint256 value);
string internal sharesName;
string internal sharesSymbol;
uint256 internal sharesTotalSupply;
mapping(address => uint256) internal sharesBalances;
mapping(address => mapping(address => uint256)) internal sharesAllowances;
// EXTERNAL FUNCTIONS
/// @dev Standard implementation of ERC20's approve(). Can be overridden.
function approve(address _spender, uint256 _amount) public virtual returns (bool) {
__approve(msg.sender, _spender, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transfer(). Can be overridden.
function transfer(address _recipient, uint256 _amount) public virtual returns (bool) {
__transfer(msg.sender, _recipient, _amount);
return true;
}
/// @dev Standard implementation of ERC20's transferFrom(). Can be overridden.
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
__transfer(_sender, _recipient, _amount);
__approve(
_sender,
msg.sender,
sharesAllowances[_sender][msg.sender].sub(
_amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
// EXTERNAL FUNCTIONS - VIEW
/// @dev Standard implementation of ERC20's allowance(). Can be overridden.
function allowance(address _owner, address _spender) public view virtual returns (uint256) {
return sharesAllowances[_owner][_spender];
}
/// @dev Standard implementation of ERC20's balanceOf(). Can be overridden.
function balanceOf(address _account) public view virtual returns (uint256) {
return sharesBalances[_account];
}
/// @dev Standard implementation of ERC20's decimals(). Can not be overridden.
function decimals() public pure returns (uint8) {
return 18;
}
/// @dev Standard implementation of ERC20's name(). Can be overridden.
function name() public view virtual returns (string memory) {
return sharesName;
}
/// @dev Standard implementation of ERC20's symbol(). Can be overridden.
function symbol() public view virtual returns (string memory) {
return sharesSymbol;
}
/// @dev Standard implementation of ERC20's totalSupply(). Can be overridden.
function totalSupply() public view virtual returns (uint256) {
return sharesTotalSupply;
}
// INTERNAL FUNCTIONS
/// @dev Helper for approve(). Can be overridden.
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");
sharesAllowances[_owner][_spender] = _amount;
emit Approval(_owner, _spender, _amount);
}
/// @dev Helper to burn tokens from an account. Can be overridden.
function __burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
sharesBalances[_account] = sharesBalances[_account].sub(
_amount,
"ERC20: burn amount exceeds balance"
);
sharesTotalSupply = sharesTotalSupply.sub(_amount);
emit Transfer(_account, address(0), _amount);
}
/// @dev Helper to mint tokens to an account. Can be overridden.
function __mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
sharesTotalSupply = sharesTotalSupply.add(_amount);
sharesBalances[_account] = sharesBalances[_account].add(_amount);
emit Transfer(address(0), _account, _amount);
}
/// @dev Helper to transfer tokens between accounts. Can be overridden.
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");
sharesBalances[_sender] = sharesBalances[_sender].sub(
_amount,
"ERC20: transfer amount exceeds balance"
);
sharesBalances[_recipient] = sharesBalances[_recipient].add(_amount);
emit Transfer(_sender, _recipient, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title VaultLibSafeMath library
/// @notice A narrowed, verbatim implementation of OpenZeppelin 3.2.0 SafeMath
/// for use with VaultLib
/// @dev Preferred to importing from npm to guarantee consistent logic and revert reasons
/// between VaultLib implementations
/// DO NOT EDIT THIS CONTRACT
library VaultLibSafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "VaultLibSafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "VaultLibSafeMath: subtraction overflow");
}
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "VaultLibSafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "VaultLibSafeMath: division by zero");
}
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "VaultLibSafeMath: modulo by zero");
}
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IDerivativePriceFeed.sol";
/// @title IDerivativePriceFeed Interface
/// @author Enzyme Council <[email protected]>
interface IAggregatedDerivativePriceFeed is IDerivativePriceFeed {
function getPriceFeedForDerivative(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IUniswapV2Pair.sol";
import "../../../../utils/MathHelpers.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../../../value-interpreter/ValueInterpreter.sol";
import "../../primitives/IPrimitivePriceFeed.sol";
import "../../utils/UniswapV2PoolTokenValueCalculator.sol";
import "../IDerivativePriceFeed.sol";
/// @title UniswapV2PoolPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Uniswap lending pool tokens
contract UniswapV2PoolPriceFeed is
IDerivativePriceFeed,
DispatcherOwnerMixin,
MathHelpers,
UniswapV2PoolTokenValueCalculator
{
event PoolTokenAdded(address indexed poolToken, address token0, address token1);
struct PoolTokenInfo {
address token0;
address token1;
uint8 token0Decimals;
uint8 token1Decimals;
}
uint256 private constant POOL_TOKEN_UNIT = 10**18;
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable FACTORY;
address private immutable PRIMITIVE_PRICE_FEED;
address private immutable VALUE_INTERPRETER;
mapping(address => PoolTokenInfo) private poolTokenToInfo;
constructor(
address _dispatcher,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _valueInterpreter,
address _factory,
address[] memory _poolTokens
) public DispatcherOwnerMixin(_dispatcher) {
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
FACTORY = _factory;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
VALUE_INTERPRETER = _valueInterpreter;
__addPoolTokens(_poolTokens, _derivativePriceFeed, _primitivePriceFeed);
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
PoolTokenInfo memory poolTokenInfo = poolTokenToInfo[_derivative];
underlyings_ = new address[](2);
underlyings_[0] = poolTokenInfo.token0;
underlyings_[1] = poolTokenInfo.token1;
// Calculate the amounts underlying one unit of a pool token,
// taking into account the known, trusted rate between the two underlyings
(uint256 token0TrustedRateAmount, uint256 token1TrustedRateAmount) = __calcTrustedRate(
poolTokenInfo.token0,
poolTokenInfo.token1,
poolTokenInfo.token0Decimals,
poolTokenInfo.token1Decimals
);
(
uint256 token0DenormalizedRate,
uint256 token1DenormalizedRate
) = __calcTrustedPoolTokenValue(
FACTORY,
_derivative,
token0TrustedRateAmount,
token1TrustedRateAmount
);
// Define normalized rates for each underlying
underlyingAmounts_ = new uint256[](2);
underlyingAmounts_[0] = _derivativeAmount.mul(token0DenormalizedRate).div(POOL_TOKEN_UNIT);
underlyingAmounts_[1] = _derivativeAmount.mul(token1DenormalizedRate).div(POOL_TOKEN_UNIT);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return poolTokenToInfo[_asset].token0 != address(0);
}
// PRIVATE FUNCTIONS
/// @dev Calculates the trusted rate of two assets based on our price feeds.
/// Uses the decimals-derived unit for whichever asset is used as the quote asset.
function __calcTrustedRate(
address _token0,
address _token1,
uint256 _token0Decimals,
uint256 _token1Decimals
) private returns (uint256 token0RateAmount_, uint256 token1RateAmount_) {
bool rateIsValid;
// The quote asset of the value lookup must be a supported primitive asset,
// so we cycle through the tokens until reaching a primitive.
// If neither is a primitive, will revert at the ValueInterpreter
if (IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_token0)) {
token1RateAmount_ = 10**_token1Decimals;
(token0RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token1, token1RateAmount_, _token0);
} else {
token0RateAmount_ = 10**_token0Decimals;
(token1RateAmount_, rateIsValid) = ValueInterpreter(VALUE_INTERPRETER)
.calcCanonicalAssetValue(_token0, token0RateAmount_, _token1);
}
require(rateIsValid, "__calcTrustedRate: Invalid rate");
return (token0RateAmount_, token1RateAmount_);
}
//////////////////////////
// POOL TOKENS REGISTRY //
//////////////////////////
/// @notice Adds Uniswap pool tokens to the price feed
/// @param _poolTokens Uniswap pool tokens to add
function addPoolTokens(address[] calldata _poolTokens) external onlyDispatcherOwner {
require(_poolTokens.length > 0, "addPoolTokens: Empty _poolTokens");
__addPoolTokens(_poolTokens, DERIVATIVE_PRICE_FEED, PRIMITIVE_PRICE_FEED);
}
/// @dev Helper to add Uniswap pool tokens
function __addPoolTokens(
address[] memory _poolTokens,
address _derivativePriceFeed,
address _primitivePriceFeed
) private {
for (uint256 i; i < _poolTokens.length; i++) {
require(_poolTokens[i] != address(0), "__addPoolTokens: Empty poolToken");
require(
poolTokenToInfo[_poolTokens[i]].token0 == address(0),
"__addPoolTokens: Value already set"
);
IUniswapV2Pair uniswapV2Pair = IUniswapV2Pair(_poolTokens[i]);
address token0 = uniswapV2Pair.token0();
address token1 = uniswapV2Pair.token1();
require(
__poolTokenIsSupportable(
_derivativePriceFeed,
_primitivePriceFeed,
token0,
token1
),
"__addPoolTokens: Unsupported pool token"
);
poolTokenToInfo[_poolTokens[i]] = PoolTokenInfo({
token0: token0,
token1: token1,
token0Decimals: ERC20(token0).decimals(),
token1Decimals: ERC20(token1).decimals()
});
emit PoolTokenAdded(_poolTokens[i], token0, token1);
}
}
/// @dev Helper to determine if a pool token is supportable, based on whether price feeds are
/// available for its underlying feeds. At least one of the underlying tokens must be
/// a supported primitive asset, and the other must be a primitive or derivative.
function __poolTokenIsSupportable(
address _derivativePriceFeed,
address _primitivePriceFeed,
address _token0,
address _token1
) private view returns (bool isSupportable_) {
IDerivativePriceFeed derivativePriceFeedContract = IDerivativePriceFeed(
_derivativePriceFeed
);
IPrimitivePriceFeed primitivePriceFeedContract = IPrimitivePriceFeed(_primitivePriceFeed);
if (primitivePriceFeedContract.isSupportedAsset(_token0)) {
if (
primitivePriceFeedContract.isSupportedAsset(_token1) ||
derivativePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
} else if (
derivativePriceFeedContract.isSupportedAsset(_token0) &&
primitivePriceFeedContract.isSupportedAsset(_token1)
) {
return true;
}
return false;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable value
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `FACTORY` variable value
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `PoolTokenInfo` for a given pool token
/// @param _poolToken The pool token for which to get the `PoolTokenInfo`
/// @return poolTokenInfo_ The `PoolTokenInfo` value
function getPoolTokenInfo(address _poolToken)
external
view
returns (PoolTokenInfo memory poolTokenInfo_)
{
return poolTokenToInfo[_poolToken];
}
/// @notice Gets the underlyings for a given pool token
/// @param _poolToken The pool token for which to get its underlyings
/// @return token0_ The UniswapV2Pair.token0 value
/// @return token1_ The UniswapV2Pair.token1 value
function getPoolTokenUnderlyings(address _poolToken)
external
view
returns (address token0_, address token1_)
{
return (poolTokenToInfo[_poolToken].token0, poolTokenToInfo[_poolToken].token1);
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable value
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets the `VALUE_INTERPRETER` variable value
/// @return valueInterpreter_ The `VALUE_INTERPRETER` variable value
function getValueInterpreter() external view returns (address valueInterpreter_) {
return VALUE_INTERPRETER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Pair Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Pair contract
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112,
uint112,
uint32
);
function kLast() external view returns (uint256);
function token0() external view returns (address);
function token1() external view returns (address);
function totalSupply() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../interfaces/IUniswapV2Factory.sol";
import "../../../interfaces/IUniswapV2Pair.sol";
/// @title UniswapV2PoolTokenValueCalculator Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract contract for computing the value of Uniswap liquidity pool tokens
/// @dev Unless otherwise noted, these functions are adapted to our needs and style guide from
/// an un-merged Uniswap branch:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/267ba44471f3357071a2fe2573fe4da42d5ad969/contracts/libraries/UniswapV2LiquidityMathLibrary.sol
abstract contract UniswapV2PoolTokenValueCalculator {
using SafeMath for uint256;
uint256 private constant POOL_TOKEN_UNIT = 10**18;
// INTERNAL FUNCTIONS
/// @dev Given a Uniswap pool with token0 and token1 and their trusted rate,
/// returns the value of one pool token unit in terms of token0 and token1.
/// This is the only function used outside of this contract.
function __calcTrustedPoolTokenValue(
address _factory,
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) internal view returns (uint256 token0Amount_, uint256 token1Amount_) {
(uint256 reserve0, uint256 reserve1) = __calcReservesAfterArbitrage(
_pair,
_token0TrustedRateAmount,
_token1TrustedRateAmount
);
return __calcPoolTokenValue(_factory, _pair, reserve0, reserve1);
}
// PRIVATE FUNCTIONS
/// @dev Computes liquidity value given all the parameters of the pair
function __calcPoolTokenValue(
address _factory,
address _pair,
uint256 _reserve0,
uint256 _reserve1
) private view returns (uint256 token0Amount_, uint256 token1Amount_) {
IUniswapV2Pair pairContract = IUniswapV2Pair(_pair);
uint256 totalSupply = pairContract.totalSupply();
if (IUniswapV2Factory(_factory).feeTo() != address(0)) {
uint256 kLast = pairContract.kLast();
if (kLast > 0) {
uint256 rootK = __uniswapSqrt(_reserve0.mul(_reserve1));
uint256 rootKLast = __uniswapSqrt(kLast);
if (rootK > rootKLast) {
uint256 numerator = totalSupply.mul(rootK.sub(rootKLast));
uint256 denominator = rootK.mul(5).add(rootKLast);
uint256 feeLiquidity = numerator.div(denominator);
totalSupply = totalSupply.add(feeLiquidity);
}
}
}
return (
_reserve0.mul(POOL_TOKEN_UNIT).div(totalSupply),
_reserve1.mul(POOL_TOKEN_UNIT).div(totalSupply)
);
}
/// @dev Calculates the direction and magnitude of the profit-maximizing trade
function __calcProfitMaximizingTrade(
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount,
uint256 _reserve0,
uint256 _reserve1
) private pure returns (bool token0ToToken1_, uint256 amountIn_) {
token0ToToken1_ =
_reserve0.mul(_token1TrustedRateAmount).div(_reserve1) < _token0TrustedRateAmount;
uint256 leftSide;
uint256 rightSide;
if (token0ToToken1_) {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token0TrustedRateAmount).mul(1000).div(
_token1TrustedRateAmount.mul(997)
)
);
rightSide = _reserve0.mul(1000).div(997);
} else {
leftSide = __uniswapSqrt(
_reserve0.mul(_reserve1).mul(_token1TrustedRateAmount).mul(1000).div(
_token0TrustedRateAmount.mul(997)
)
);
rightSide = _reserve1.mul(1000).div(997);
}
if (leftSide < rightSide) {
return (false, 0);
}
// Calculate the amount that must be sent to move the price to the profit-maximizing price
amountIn_ = leftSide.sub(rightSide);
return (token0ToToken1_, amountIn_);
}
/// @dev Calculates the pool reserves after an arbitrage moves the price to
/// the profit-maximizing rate, given an externally-observed trusted rate
/// between the two pooled assets
function __calcReservesAfterArbitrage(
address _pair,
uint256 _token0TrustedRateAmount,
uint256 _token1TrustedRateAmount
) private view returns (uint256 reserve0_, uint256 reserve1_) {
(reserve0_, reserve1_, ) = IUniswapV2Pair(_pair).getReserves();
// Skip checking whether the reserve is 0, as this is extremely unlikely given how
// initial pool liquidity is locked, and since we maintain a list of registered pool tokens
// Calculate how much to swap to arb to the trusted price
(bool token0ToToken1, uint256 amountIn) = __calcProfitMaximizingTrade(
_token0TrustedRateAmount,
_token1TrustedRateAmount,
reserve0_,
reserve1_
);
if (amountIn == 0) {
return (reserve0_, reserve1_);
}
// Adjust the reserves to account for the arb trade to the trusted price
if (token0ToToken1) {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve0_, reserve1_);
reserve0_ = reserve0_.add(amountIn);
reserve1_ = reserve1_.sub(amountOut);
} else {
uint256 amountOut = __uniswapV2GetAmountOut(amountIn, reserve1_, reserve0_);
reserve1_ = reserve1_.add(amountIn);
reserve0_ = reserve0_.sub(amountOut);
}
return (reserve0_, reserve1_);
}
/// @dev Uniswap square root function. See:
/// https://github.com/Uniswap/uniswap-lib/blob/6ddfedd5716ba85b905bf34d7f1f3c659101a1bc/contracts/libraries/Babylonian.sol
function __uniswapSqrt(uint256 _y) private pure returns (uint256 z_) {
if (_y > 3) {
z_ = _y;
uint256 x = _y / 2 + 1;
while (x < z_) {
z_ = x;
x = (_y / x + x) / 2;
}
} else if (_y != 0) {
z_ = 1;
}
// else z_ = 0
return z_;
}
/// @dev Simplified version of UniswapV2Library's getAmountOut() function. See:
/// https://github.com/Uniswap/uniswap-v2-periphery/blob/87edfdcaf49ccc52591502993db4c8c08ea9eec0/contracts/libraries/UniswapV2Library.sol#L42-L50
function __uniswapV2GetAmountOut(
uint256 _amountIn,
uint256 _reserveIn,
uint256 _reserveOut
) private pure returns (uint256 amountOut_) {
uint256 amountInWithFee = _amountIn.mul(997);
uint256 numerator = amountInWithFee.mul(_reserveOut);
uint256 denominator = _reserveIn.mul(1000).add(amountInWithFee);
return numerator.div(denominator);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IUniswapV2Factory Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Uniswap V2's Factory contract
interface IUniswapV2Factory {
function feeTo() external view returns (address);
function getPair(address, address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IChainlinkAggregator.sol";
import "../../../../utils/MakerDaoMath.sol";
import "../IDerivativePriceFeed.sol";
/// @title WdgldPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for WDGLD <https://dgld.ch/>
contract WdgldPriceFeed is IDerivativePriceFeed, MakerDaoMath {
using SafeMath for uint256;
address private immutable XAU_AGGREGATOR;
address private immutable ETH_AGGREGATOR;
address private immutable WDGLD;
address private immutable WETH;
// GTR_CONSTANT aggregates all the invariants in the GTR formula to save gas
uint256 private constant GTR_CONSTANT = 999990821653213975346065101;
uint256 private constant GTR_PRECISION = 10**27;
uint256 private constant WDGLD_GENESIS_TIMESTAMP = 1568700000;
constructor(
address _wdgld,
address _weth,
address _ethAggregator,
address _xauAggregator
) public {
WDGLD = _wdgld;
WETH = _weth;
ETH_AGGREGATOR = _ethAggregator;
XAU_AGGREGATOR = _xauAggregator;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only WDGLD is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH;
underlyingAmounts_ = new uint256[](1);
// Get price rates from xau and eth aggregators
int256 xauToUsdRate = IChainlinkAggregator(XAU_AGGREGATOR).latestAnswer();
int256 ethToUsdRate = IChainlinkAggregator(ETH_AGGREGATOR).latestAnswer();
require(xauToUsdRate > 0 && ethToUsdRate > 0, "calcUnderlyingValues: rate invalid");
uint256 wdgldToXauRate = calcWdgldToXauRate();
// 10**17 is a combination of ETH_UNIT / WDGLD_UNIT * GTR_PRECISION
underlyingAmounts_[0] = _derivativeAmount
.mul(wdgldToXauRate)
.mul(uint256(xauToUsdRate))
.div(uint256(ethToUsdRate))
.div(10**17);
return (underlyings_, underlyingAmounts_);
}
/// @notice Calculates the rate of WDGLD to XAU.
/// @return wdgldToXauRate_ The current rate of WDGLD to XAU
/// @dev Full formula available <https://dgld.ch/assets/documents/dgld-whitepaper.pdf>
function calcWdgldToXauRate() public view returns (uint256 wdgldToXauRate_) {
return
__rpow(
GTR_CONSTANT,
((block.timestamp).sub(WDGLD_GENESIS_TIMESTAMP)).div(28800), // 60 * 60 * 8 (8 hour periods)
GTR_PRECISION
)
.div(10);
}
/// @notice Checks if an asset is supported by this price feed
/// @param _asset The asset to check
/// @return isSupported_ True if supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == WDGLD;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ETH_AGGREGATOR` address
/// @return ethAggregatorAddress_ The `ETH_AGGREGATOR` address
function getEthAggregator() external view returns (address ethAggregatorAddress_) {
return ETH_AGGREGATOR;
}
/// @notice Gets the `WDGLD` token address
/// @return wdgld_ The `WDGLD` token address
function getWdgld() external view returns (address wdgld_) {
return WDGLD;
}
/// @notice Gets the `WETH` token address
/// @return weth_ The `WETH` token address
function getWeth() external view returns (address weth_) {
return WETH;
}
/// @notice Gets the `XAU_AGGREGATOR` address
/// @return xauAggregatorAddress_ The `XAU_AGGREGATOR` address
function getXauAggregator() external view returns (address xauAggregatorAddress_) {
return XAU_AGGREGATOR;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IChainlinkAggregator Interface
/// @author Enzyme Council <[email protected]>
interface IChainlinkAggregator {
function latestAnswer() external view returns (int256);
function latestTimestamp() external view returns (uint256);
}
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2018 Rain <[email protected]>
//
// 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.12;
/// @title MakerDaoMath Contract
/// @author Enzyme Council <[email protected]>
/// @notice Helper functions for math operations adapted from MakerDao contracts
abstract contract MakerDaoMath {
/// @dev Performs scaled, fixed-point exponentiation.
/// Verbatim code, adapted to our style guide for variable naming only, see:
/// https://github.com/makerdao/dss/blob/master/src/pot.sol#L83-L105
// prettier-ignore
function __rpow(uint256 _x, uint256 _n, uint256 _base) internal pure returns (uint256 z_) {
assembly {
switch _x case 0 {switch _n case 0 {z_ := _base} default {z_ := 0}}
default {
switch mod(_n, 2) case 0 { z_ := _base } default { z_ := _x }
let half := div(_base, 2)
for { _n := div(_n, 2) } _n { _n := div(_n,2) } {
let xx := mul(_x, _x)
if iszero(eq(div(xx, _x), _x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
_x := div(xxRound, _base)
if mod(_n,2) {
let zx := mul(z_, _x)
if and(iszero(iszero(_x)), iszero(eq(div(zx, _x), z_))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z_ := div(zxRound, _base)
}
}
}
}
return z_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../core/fund/vault/VaultLib.sol";
import "../../../utils/MakerDaoMath.sol";
import "./utils/FeeBase.sol";
/// @title ManagementFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A management fee with a configurable annual rate
contract ManagementFee is FeeBase, MakerDaoMath {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 scaledPerSecondRate);
event Settled(
address indexed comptrollerProxy,
uint256 sharesQuantity,
uint256 secondsSinceSettlement
);
struct FeeInfo {
uint256 scaledPerSecondRate;
uint256 lastSettled;
}
uint256 private constant RATE_SCALE_BASE = 10**27;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyFeeManager
{
// It is only necessary to set `lastSettled` for a migrated fund
if (VaultLib(_vaultProxy).totalSupply() > 0) {
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
}
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the fee for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 scaledPerSecondRate = abi.decode(_settingsData, (uint256));
require(
scaledPerSecondRate > 0,
"addFundSettings: scaledPerSecondRate must be greater than 0"
);
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
scaledPerSecondRate: scaledPerSecondRate,
lastSettled: 0
});
emit FundSettingsAdded(_comptrollerProxy, scaledPerSecondRate);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "MANAGEMENT";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settle the fee and calculate shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// If this fee was settled in the current block, we can return early
uint256 secondsSinceSettlement = block.timestamp.sub(feeInfo.lastSettled);
if (secondsSinceSettlement == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
// If there are shares issued for the fund, calculate the shares due
VaultLib vaultProxyContract = VaultLib(_vaultProxy);
uint256 sharesSupply = vaultProxyContract.totalSupply();
if (sharesSupply > 0) {
// This assumes that all shares in the VaultProxy are shares outstanding,
// which is fine for this release. Even if they are not, they are still shares that
// are only claimable by the fund owner.
uint256 netSharesSupply = sharesSupply.sub(vaultProxyContract.balanceOf(_vaultProxy));
if (netSharesSupply > 0) {
sharesDue_ = netSharesSupply
.mul(
__rpow(feeInfo.scaledPerSecondRate, secondsSinceSettlement, RATE_SCALE_BASE)
.sub(RATE_SCALE_BASE)
)
.div(RATE_SCALE_BASE);
}
}
// Must settle even when no shares are due, for the case that settlement is being
// done when there are no shares in the fund (i.e. at the first investment, or at the
// first investment after all shares have been redeemed)
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSettled = block.timestamp;
emit Settled(_comptrollerProxy, sharesDue_, secondsSinceSettlement);
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
return (IFeeManager.SettlementType.Mint, address(0), sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../IFee.sol";
/// @title FeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Abstract base contract for all fees
abstract contract FeeBase is IFee {
address internal immutable FEE_MANAGER;
modifier onlyFeeManager {
require(msg.sender == FEE_MANAGER, "Only the FeeManger can make this call");
_;
}
constructor(address _feeManager) public {
FEE_MANAGER = _feeManager;
}
/// @notice Allows Fee to run logic during fund activation
/// @dev Unimplemented by default, may be overrode.
function activateForFund(address, address) external virtual override {
return;
}
/// @notice Runs payout logic for a fee that utilizes shares outstanding as its settlement type
/// @dev Returns false by default, can be overridden by fee
function payout(address, address) external virtual override returns (bool) {
return false;
}
/// @notice Update fee state after all settlement has occurred during a given fee hook
/// @dev Unimplemented by default, can be overridden by fee
function update(
address,
address,
IFeeManager.FeeHook,
bytes calldata,
uint256
) external virtual override {
return;
}
/// @notice Helper to parse settlement arguments from encoded data for PreBuyShares fee hook
function __decodePreBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PreRedeemShares fee hook
function __decodePreRedeemSharesSettlementData(bytes memory _settlementData)
internal
pure
returns (address redeemer_, uint256 sharesQuantity_)
{
return abi.decode(_settlementData, (address, uint256));
}
/// @notice Helper to parse settlement arguments from encoded data for PostBuyShares fee hook
function __decodePostBuySharesSettlementData(bytes memory _settlementData)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 sharesBought_
)
{
return abi.decode(_settlementData, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./IFeeManager.sol";
/// @title Fee Interface
/// @author Enzyme Council <[email protected]>
/// @notice Interface for all fees
interface IFee {
function activateForFund(address _comptrollerProxy, address _vaultProxy) external;
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData) external;
function identifier() external pure returns (string memory identifier_);
function implementedHooks()
external
view
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
);
function payout(address _comptrollerProxy, address _vaultProxy)
external
returns (bool isPayable_);
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
)
external
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
);
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/SignedSafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../core/fund/comptroller/ComptrollerLib.sol";
import "../FeeManager.sol";
import "./utils/FeeBase.sol";
/// @title PerformanceFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice A performance-based fee with configurable rate and crystallization period, using
/// a high watermark
/// @dev This contract assumes that all shares in the VaultProxy are shares outstanding,
/// which is fine for this release. Even if they are not, they are still shares that
/// are only claimable by the fund owner.
contract PerformanceFee is FeeBase {
using SafeMath for uint256;
using SignedSafeMath for int256;
event ActivatedForFund(address indexed comptrollerProxy, uint256 highWaterMark);
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate, uint256 period);
event LastSharePriceUpdated(
address indexed comptrollerProxy,
uint256 prevSharePrice,
uint256 nextSharePrice
);
event PaidOut(
address indexed comptrollerProxy,
uint256 prevHighWaterMark,
uint256 nextHighWaterMark,
uint256 aggregateValueDue
);
event PerformanceUpdated(
address indexed comptrollerProxy,
uint256 prevAggregateValueDue,
uint256 nextAggregateValueDue,
int256 sharesOutstandingDiff
);
struct FeeInfo {
uint256 rate;
uint256 period;
uint256 activated;
uint256 lastPaid;
uint256 highWaterMark;
uint256 lastSharePrice;
uint256 aggregateValueDue;
}
uint256 private constant RATE_DIVISOR = 10**18;
uint256 private constant SHARE_UNIT = 10**18;
mapping(address => FeeInfo) private comptrollerProxyToFeeInfo;
constructor(address _feeManager) public FeeBase(_feeManager) {}
// EXTERNAL FUNCTIONS
/// @notice Activates the fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
function activateForFund(address _comptrollerProxy, address) external override onlyFeeManager {
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
// We must not force asset finality, otherwise funds that have Synths as tracked assets
// would be susceptible to a DoS attack when attempting to migrate to a release that uses
// this fee: an attacker trades a negligible amount of a tracked Synth with the VaultProxy
// as the recipient, thus causing `calcGrossShareValue(true)` to fail.
(uint256 grossSharePrice, bool sharePriceIsValid) = ComptrollerLib(_comptrollerProxy)
.calcGrossShareValue(false);
require(sharePriceIsValid, "activateForFund: Invalid share price");
feeInfo.highWaterMark = grossSharePrice;
feeInfo.lastSharePrice = grossSharePrice;
feeInfo.activated = block.timestamp;
emit ActivatedForFund(_comptrollerProxy, grossSharePrice);
}
/// @notice Add the initial fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for the fund
/// @dev `highWaterMark`, `lastSharePrice`, and `activated` are set during activation
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
(uint256 feeRate, uint256 feePeriod) = abi.decode(_settingsData, (uint256, uint256));
require(feeRate > 0, "addFundSettings: feeRate must be greater than 0");
require(feePeriod > 0, "addFundSettings: feePeriod must be greater than 0");
comptrollerProxyToFeeInfo[_comptrollerProxy] = FeeInfo({
rate: feeRate,
period: feePeriod,
activated: 0,
lastPaid: 0,
highWaterMark: 0,
lastSharePrice: 0,
aggregateValueDue: 0
});
emit FundSettingsAdded(_comptrollerProxy, feeRate, feePeriod);
}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PERFORMANCE";
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](3);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForSettle_[1] = IFeeManager.FeeHook.BuySharesSetup;
implementedHooksForSettle_[2] = IFeeManager.FeeHook.PreRedeemShares;
implementedHooksForUpdate_ = new IFeeManager.FeeHook[](3);
implementedHooksForUpdate_[0] = IFeeManager.FeeHook.Continuous;
implementedHooksForUpdate_[1] = IFeeManager.FeeHook.BuySharesCompleted;
implementedHooksForUpdate_[2] = IFeeManager.FeeHook.PreRedeemShares;
return (implementedHooksForSettle_, implementedHooksForUpdate_, true, true);
}
/// @notice Checks whether the shares outstanding for the fee can be paid out, and updates
/// the info for the fee's last payout
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return isPayable_ True if shares outstanding can be paid out
function payout(address _comptrollerProxy, address)
external
override
onlyFeeManager
returns (bool isPayable_)
{
if (!payoutAllowed(_comptrollerProxy)) {
return false;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
feeInfo.lastPaid = block.timestamp;
uint256 prevHighWaterMark = feeInfo.highWaterMark;
uint256 nextHighWaterMark = __calcUint256Max(feeInfo.lastSharePrice, prevHighWaterMark);
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
// Update state as necessary
if (prevAggregateValueDue > 0) {
feeInfo.aggregateValueDue = 0;
}
if (nextHighWaterMark > prevHighWaterMark) {
feeInfo.highWaterMark = nextHighWaterMark;
}
emit PaidOut(
_comptrollerProxy,
prevHighWaterMark,
nextHighWaterMark,
prevAggregateValueDue
);
return true;
}
/// @notice Settles the fee and calculates shares due
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _gav The GAV of the fund
/// @return settlementType_ The type of settlement
/// @return (unused) The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook,
bytes calldata,
uint256 _gav
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address,
uint256 sharesDue_
)
{
if (_gav == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
int256 settlementSharesDue = __settleAndUpdatePerformance(
_comptrollerProxy,
_vaultProxy,
_gav
);
if (settlementSharesDue == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
} else if (settlementSharesDue > 0) {
// Settle by minting shares outstanding for custody
return (
IFeeManager.SettlementType.MintSharesOutstanding,
address(0),
uint256(settlementSharesDue)
);
} else {
// Settle by burning from shares outstanding
return (
IFeeManager.SettlementType.BurnSharesOutstanding,
address(0),
uint256(-settlementSharesDue)
);
}
}
/// @notice Updates the fee state after all fees have finished settle()
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _vaultProxy The VaultProxy of the fund
/// @param _hook The FeeHook being executed
/// @param _settlementData Encoded args to use in calculating the settlement
/// @param _gav The GAV of the fund
function update(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override onlyFeeManager {
uint256 prevSharePrice = comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice;
uint256 nextSharePrice = __calcNextSharePrice(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (nextSharePrice == prevSharePrice) {
return;
}
comptrollerProxyToFeeInfo[_comptrollerProxy].lastSharePrice = nextSharePrice;
emit LastSharePriceUpdated(_comptrollerProxy, prevSharePrice, nextSharePrice);
}
// PUBLIC FUNCTIONS
/// @notice Checks whether the shares outstanding can be paid out
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return payoutAllowed_ True if the fee payment is due
/// @dev Payout is allowed if fees have not yet been settled in a crystallization period,
/// and at least 1 crystallization period has passed since activation
function payoutAllowed(address _comptrollerProxy) public view returns (bool payoutAllowed_) {
FeeInfo memory feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 period = feeInfo.period;
uint256 timeSinceActivated = block.timestamp.sub(feeInfo.activated);
// Check if at least 1 crystallization period has passed since activation
if (timeSinceActivated < period) {
return false;
}
// Check that a full crystallization period has passed since the last payout
uint256 timeSincePeriodStart = timeSinceActivated % period;
uint256 periodStart = block.timestamp.sub(timeSincePeriodStart);
return feeInfo.lastPaid < periodStart;
}
// PRIVATE FUNCTIONS
/// @dev Helper to calculate the aggregated value accumulated to a fund since the last
/// settlement (happening at investment/redemption)
/// Validated:
/// _netSharesSupply > 0
/// _sharePriceWithoutPerformance != _prevSharePrice
function __calcAggregateValueDue(
uint256 _netSharesSupply,
uint256 _sharePriceWithoutPerformance,
uint256 _prevSharePrice,
uint256 _prevAggregateValueDue,
uint256 _feeRate,
uint256 _highWaterMark
) private pure returns (uint256) {
int256 superHWMValueSinceLastSettled = (
int256(__calcUint256Max(_highWaterMark, _sharePriceWithoutPerformance)).sub(
int256(__calcUint256Max(_highWaterMark, _prevSharePrice))
)
)
.mul(int256(_netSharesSupply))
.div(int256(SHARE_UNIT));
int256 valueDueSinceLastSettled = superHWMValueSinceLastSettled.mul(int256(_feeRate)).div(
int256(RATE_DIVISOR)
);
return
uint256(
__calcInt256Max(0, int256(_prevAggregateValueDue).add(valueDueSinceLastSettled))
);
}
/// @dev Helper to calculate the max of two int values
function __calcInt256Max(int256 _a, int256 _b) private pure returns (int256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to calculate the next `lastSharePrice` value
function __calcNextSharePrice(
address _comptrollerProxy,
address _vaultProxy,
IFeeManager.FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private view returns (uint256 nextSharePrice_) {
uint256 denominationAssetUnit = 10 **
uint256(ERC20(ComptrollerLib(_comptrollerProxy).getDenominationAsset()).decimals());
if (_gav == 0) {
return denominationAssetUnit;
}
// Get shares outstanding via VaultProxy balance and calc shares supply to get net shares supply
ERC20 vaultProxyContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = vaultProxyContract.totalSupply();
uint256 nextNetSharesSupply = totalSharesSupply.sub(
vaultProxyContract.balanceOf(_vaultProxy)
);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
uint256 nextGav = _gav;
// For both Continuous and BuySharesCompleted hooks, _gav and shares supply will not change,
// we only need additional calculations for PreRedeemShares
if (_hook == IFeeManager.FeeHook.PreRedeemShares) {
(, uint256 sharesDecrease) = __decodePreRedeemSharesSettlementData(_settlementData);
// Shares have not yet been burned
nextNetSharesSupply = nextNetSharesSupply.sub(sharesDecrease);
if (nextNetSharesSupply == 0) {
return denominationAssetUnit;
}
// Assets have not yet been withdrawn
uint256 gavDecrease = sharesDecrease
.mul(_gav)
.mul(SHARE_UNIT)
.div(totalSharesSupply)
.div(denominationAssetUnit);
nextGav = nextGav.sub(gavDecrease);
if (nextGav == 0) {
return denominationAssetUnit;
}
}
return nextGav.mul(SHARE_UNIT).div(nextNetSharesSupply);
}
/// @dev Helper to calculate the performance metrics for a fund.
/// Validated:
/// _totalSharesSupply > 0
/// _gav > 0
/// _totalSharesSupply != _totalSharesOutstanding
function __calcPerformance(
address _comptrollerProxy,
uint256 _totalSharesSupply,
uint256 _totalSharesOutstanding,
uint256 _prevAggregateValueDue,
FeeInfo memory feeInfo,
uint256 _gav
) private view returns (uint256 nextAggregateValueDue_, int256 sharesDue_) {
// Use the 'shares supply net shares outstanding' for performance calcs.
// Cannot be 0, as _totalSharesSupply != _totalSharesOutstanding
uint256 netSharesSupply = _totalSharesSupply.sub(_totalSharesOutstanding);
uint256 sharePriceWithoutPerformance = _gav.mul(SHARE_UNIT).div(netSharesSupply);
// If gross share price has not changed, can exit early
uint256 prevSharePrice = feeInfo.lastSharePrice;
if (sharePriceWithoutPerformance == prevSharePrice) {
return (_prevAggregateValueDue, 0);
}
nextAggregateValueDue_ = __calcAggregateValueDue(
netSharesSupply,
sharePriceWithoutPerformance,
prevSharePrice,
_prevAggregateValueDue,
feeInfo.rate,
feeInfo.highWaterMark
);
sharesDue_ = __calcSharesDue(
_comptrollerProxy,
netSharesSupply,
_gav,
nextAggregateValueDue_
);
return (nextAggregateValueDue_, sharesDue_);
}
/// @dev Helper to calculate sharesDue during settlement.
/// Validated:
/// _netSharesSupply > 0
/// _gav > 0
function __calcSharesDue(
address _comptrollerProxy,
uint256 _netSharesSupply,
uint256 _gav,
uint256 _nextAggregateValueDue
) private view returns (int256 sharesDue_) {
// If _nextAggregateValueDue > _gav, then no shares can be created.
// This is a known limitation of the model, which is only reached for unrealistically
// high performance fee rates (> 100%). A revert is allowed in such a case.
uint256 sharesDueForAggregateValueDue = _nextAggregateValueDue.mul(_netSharesSupply).div(
_gav.sub(_nextAggregateValueDue)
);
// Shares due is the +/- diff or the total shares outstanding already minted
return
int256(sharesDueForAggregateValueDue).sub(
int256(
FeeManager(FEE_MANAGER).getFeeSharesOutstandingForFund(
_comptrollerProxy,
address(this)
)
)
);
}
/// @dev Helper to calculate the max of two uint values
function __calcUint256Max(uint256 _a, uint256 _b) private pure returns (uint256) {
if (_a >= _b) {
return _a;
}
return _b;
}
/// @dev Helper to settle the fee and update performance state.
/// Validated:
/// _gav > 0
function __settleAndUpdatePerformance(
address _comptrollerProxy,
address _vaultProxy,
uint256 _gav
) private returns (int256 sharesDue_) {
ERC20 sharesTokenContract = ERC20(_vaultProxy);
uint256 totalSharesSupply = sharesTokenContract.totalSupply();
if (totalSharesSupply == 0) {
return 0;
}
uint256 totalSharesOutstanding = sharesTokenContract.balanceOf(_vaultProxy);
if (totalSharesOutstanding == totalSharesSupply) {
return 0;
}
FeeInfo storage feeInfo = comptrollerProxyToFeeInfo[_comptrollerProxy];
uint256 prevAggregateValueDue = feeInfo.aggregateValueDue;
uint256 nextAggregateValueDue;
(nextAggregateValueDue, sharesDue_) = __calcPerformance(
_comptrollerProxy,
totalSharesSupply,
totalSharesOutstanding,
prevAggregateValueDue,
feeInfo,
_gav
);
if (nextAggregateValueDue == prevAggregateValueDue) {
return 0;
}
// Update fee state
feeInfo.aggregateValueDue = nextAggregateValueDue;
emit PerformanceUpdated(
_comptrollerProxy,
prevAggregateValueDue,
nextAggregateValueDue,
sharesDue_
);
return sharesDue_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the feeInfo for a given fund
/// @param _comptrollerProxy The ComptrollerProxy contract of the fund
/// @return feeInfo_ The feeInfo
function getFeeInfoForFund(address _comptrollerProxy)
external
view
returns (FeeInfo memory feeInfo_)
{
return comptrollerProxyToFeeInfo[_comptrollerProxy];
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/comptroller/IComptroller.sol";
import "../../core/fund/vault/IVault.sol";
import "../../utils/AddressArrayLib.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./IFee.sol";
import "./IFeeManager.sol";
/// @title FeeManager Contract
/// @author Enzyme Council <[email protected]>
/// @notice Manages fees for funds
contract FeeManager is
IFeeManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AllSharesOutstandingForcePaidForFund(
address indexed comptrollerProxy,
address payee,
uint256 sharesDue
);
event FeeDeregistered(address indexed fee, string indexed identifier);
event FeeEnabledForFund(
address indexed comptrollerProxy,
address indexed fee,
bytes settingsData
);
event FeeRegistered(
address indexed fee,
string indexed identifier,
FeeHook[] implementedHooksForSettle,
FeeHook[] implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
);
event FeeSettledForFund(
address indexed comptrollerProxy,
address indexed fee,
SettlementType indexed settlementType,
address payer,
address payee,
uint256 sharesDue
);
event SharesOutstandingPaidForFund(
address indexed comptrollerProxy,
address indexed fee,
uint256 sharesDue
);
event FeesRecipientSetForFund(
address indexed comptrollerProxy,
address prevFeesRecipient,
address nextFeesRecipient
);
EnumerableSet.AddressSet private registeredFees;
mapping(address => bool) private feeToUsesGavOnSettle;
mapping(address => bool) private feeToUsesGavOnUpdate;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsSettle;
mapping(address => mapping(FeeHook => bool)) private feeToHookToImplementsUpdate;
mapping(address => address[]) private comptrollerProxyToFees;
mapping(address => mapping(address => uint256))
private comptrollerProxyToFeeToSharesOutstanding;
constructor(address _fundDeployer) public FundDeployerOwnerMixin(_fundDeployer) {}
// EXTERNAL FUNCTIONS
/// @notice Activate already-configured fees for use in the calling fund
function activateForFund(bool) external override {
address vaultProxy = __setValidatedVaultProxy(msg.sender);
address[] memory enabledFees = comptrollerProxyToFees[msg.sender];
for (uint256 i; i < enabledFees.length; i++) {
IFee(enabledFees[i]).activateForFund(msg.sender, vaultProxy);
}
}
/// @notice Deactivate fees for a fund
/// @dev msg.sender is validated during __invokeHook()
function deactivateForFund() external override {
// Settle continuous fees one last time, but without calling Fee.update()
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, false);
// Force payout of remaining shares outstanding
__forcePayoutAllSharesOutstanding(msg.sender);
// Clean up storage
__deleteFundStorage(msg.sender);
}
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _actionId An ID representing the desired action
/// @param _callArgs Encoded arguments specific to the _actionId
/// @dev This is the only way to call a function on this contract that updates VaultProxy state.
/// For both of these actions, any caller is allowed, so we don't use the caller param.
function receiveCallFromComptroller(
address,
uint256 _actionId,
bytes calldata _callArgs
) external override {
if (_actionId == 0) {
// Settle and update all continuous fees
__invokeHook(msg.sender, IFeeManager.FeeHook.Continuous, "", 0, true);
} else if (_actionId == 1) {
__payoutSharesOutstandingForFees(msg.sender, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @notice Enable and configure fees for use in the calling fund
/// @param _configData Encoded config data
/// @dev Caller is expected to be a valid ComptrollerProxy, but there isn't a need to validate.
/// The order of `fees` determines the order in which fees of the same FeeHook will be applied.
/// It is recommended to run ManagementFee before PerformanceFee in order to achieve precise
/// PerformanceFee calcs.
function setConfigForFund(bytes calldata _configData) external override {
(address[] memory fees, bytes[] memory settingsData) = abi.decode(
_configData,
(address[], bytes[])
);
// Sanity checks
require(
fees.length == settingsData.length,
"setConfigForFund: fees and settingsData array lengths unequal"
);
require(fees.isUniqueSet(), "setConfigForFund: fees cannot include duplicates");
// Enable each fee with settings
for (uint256 i; i < fees.length; i++) {
require(isRegisteredFee(fees[i]), "setConfigForFund: Fee is not registered");
// Set fund config on fee
IFee(fees[i]).addFundSettings(msg.sender, settingsData[i]);
// Enable fee for fund
comptrollerProxyToFees[msg.sender].push(fees[i]);
emit FeeEnabledForFund(msg.sender, fees[i], settingsData[i]);
}
}
/// @notice Allows all fees for a particular FeeHook to implement settle() and update() logic
/// @param _hook The FeeHook to invoke
/// @param _settlementData The encoded settlement parameters specific to the FeeHook
/// @param _gav The GAV for a fund if known in the invocating code, otherwise 0
function invokeHook(
FeeHook _hook,
bytes calldata _settlementData,
uint256 _gav
) external override {
__invokeHook(msg.sender, _hook, _settlementData, _gav, true);
}
// PRIVATE FUNCTIONS
/// @dev Helper to destroy local storage to get gas refund,
/// and to prevent further calls to fee manager
function __deleteFundStorage(address _comptrollerProxy) private {
delete comptrollerProxyToFees[_comptrollerProxy];
delete comptrollerProxyToVaultProxy[_comptrollerProxy];
}
/// @dev Helper to force the payout of shares outstanding across all fees.
/// For the current release, all shares in the VaultProxy are assumed to be
/// shares outstanding from fees. If not, then they were sent there by mistake
/// and are otherwise unrecoverable. We can therefore take the VaultProxy's
/// shares balance as the totalSharesOutstanding to payout to the fund owner.
function __forcePayoutAllSharesOutstanding(address _comptrollerProxy) private {
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
uint256 totalSharesOutstanding = ERC20(vaultProxy).balanceOf(vaultProxy);
if (totalSharesOutstanding == 0) {
return;
}
// Destroy any shares outstanding storage
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
for (uint256 i; i < fees.length; i++) {
delete comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
}
// Distribute all shares outstanding to the fees recipient
address payee = IVault(vaultProxy).getOwner();
__transferShares(_comptrollerProxy, vaultProxy, payee, totalSharesOutstanding);
emit AllSharesOutstandingForcePaidForFund(
_comptrollerProxy,
payee,
totalSharesOutstanding
);
}
/// @dev Helper to get the canonical value of GAV if not yet set and required by fee
function __getGavAsNecessary(
address _comptrollerProxy,
address _fee,
uint256 _gavOrZero
) private returns (uint256 gav_) {
if (_gavOrZero == 0 && feeUsesGavOnUpdate(_fee)) {
// Assumes that any fee that requires GAV would need to revert if invalid or not final
bool gavIsValid;
(gav_, gavIsValid) = IComptroller(_comptrollerProxy).calcGav(true);
require(gavIsValid, "__getGavAsNecessary: Invalid GAV");
} else {
gav_ = _gavOrZero;
}
return gav_;
}
/// @dev Helper to run settle() on all enabled fees for a fund that implement a given hook, and then to
/// optionally run update() on the same fees. This order allows fees an opportunity to update
/// their local state after all VaultProxy state transitions (i.e., minting, burning,
/// transferring shares) have finished. To optimize for the expensive operation of calculating
/// GAV, once one fee requires GAV, we recycle that `gav` value for subsequent fees.
/// Assumes that _gav is either 0 or has already been validated.
function __invokeHook(
address _comptrollerProxy,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero,
bool _updateFees
) private {
address[] memory fees = comptrollerProxyToFees[_comptrollerProxy];
if (fees.length == 0) {
return;
}
address vaultProxy = getVaultProxyForFund(_comptrollerProxy);
// This check isn't strictly necessary, but its cost is insignificant,
// and helps to preserve data integrity.
require(vaultProxy != address(0), "__invokeHook: Fund is not active");
// First, allow all fees to implement settle()
uint256 gav = __settleFees(
_comptrollerProxy,
vaultProxy,
fees,
_hook,
_settlementData,
_gavOrZero
);
// Second, allow fees to implement update()
// This function does not allow any further altering of VaultProxy state
// (i.e., burning, minting, or transferring shares)
if (_updateFees) {
__updateFees(_comptrollerProxy, vaultProxy, fees, _hook, _settlementData, gav);
}
}
/// @dev Helper to payout the shares outstanding for the specified fees.
/// Does not call settle() on fees.
/// Only callable via ComptrollerProxy.callOnExtension().
function __payoutSharesOutstandingForFees(address _comptrollerProxy, bytes memory _callArgs)
private
{
address[] memory fees = abi.decode(_callArgs, (address[]));
address vaultProxy = getVaultProxyForFund(msg.sender);
uint256 sharesOutstandingDue;
for (uint256 i; i < fees.length; i++) {
if (!IFee(fees[i]).payout(_comptrollerProxy, vaultProxy)) {
continue;
}
uint256 sharesOutstandingForFee
= comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]];
if (sharesOutstandingForFee == 0) {
continue;
}
sharesOutstandingDue = sharesOutstandingDue.add(sharesOutstandingForFee);
// Delete shares outstanding and distribute from VaultProxy to the fees recipient
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][fees[i]] = 0;
emit SharesOutstandingPaidForFund(_comptrollerProxy, fees[i], sharesOutstandingForFee);
}
if (sharesOutstandingDue > 0) {
__transferShares(
_comptrollerProxy,
vaultProxy,
IVault(vaultProxy).getOwner(),
sharesOutstandingDue
);
}
}
/// @dev Helper to settle a fee
function __settleFee(
address _comptrollerProxy,
address _vaultProxy,
address _fee,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gav
) private {
(SettlementType settlementType, address payer, uint256 sharesDue) = IFee(_fee).settle(
_comptrollerProxy,
_vaultProxy,
_hook,
_settlementData,
_gav
);
if (settlementType == SettlementType.None) {
return;
}
address payee;
if (settlementType == SettlementType.Direct) {
payee = IVault(_vaultProxy).getOwner();
__transferShares(_comptrollerProxy, payer, payee, sharesDue);
} else if (settlementType == SettlementType.Mint) {
payee = IVault(_vaultProxy).getOwner();
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.Burn) {
__burnShares(_comptrollerProxy, payer, sharesDue);
} else if (settlementType == SettlementType.MintSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.add(sharesDue);
payee = _vaultProxy;
__mintShares(_comptrollerProxy, payee, sharesDue);
} else if (settlementType == SettlementType.BurnSharesOutstanding) {
comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee] = comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee]
.sub(sharesDue);
payer = _vaultProxy;
__burnShares(_comptrollerProxy, payer, sharesDue);
} else {
revert("__settleFee: Invalid SettlementType");
}
emit FeeSettledForFund(_comptrollerProxy, _fee, settlementType, payer, payee, sharesDue);
}
/// @dev Helper to settle fees that implement a given fee hook
function __settleFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private returns (uint256 gav_) {
gav_ = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeSettlesOnHook(_fees[i], _hook)) {
continue;
}
gav_ = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav_);
__settleFee(_comptrollerProxy, _vaultProxy, _fees[i], _hook, _settlementData, gav_);
}
return gav_;
}
/// @dev Helper to update fees that implement a given fee hook
function __updateFees(
address _comptrollerProxy,
address _vaultProxy,
address[] memory _fees,
FeeHook _hook,
bytes memory _settlementData,
uint256 _gavOrZero
) private {
uint256 gav = _gavOrZero;
for (uint256 i; i < _fees.length; i++) {
if (!feeUpdatesOnHook(_fees[i], _hook)) {
continue;
}
gav = __getGavAsNecessary(_comptrollerProxy, _fees[i], gav);
IFee(_fees[i]).update(_comptrollerProxy, _vaultProxy, _hook, _settlementData, gav);
}
}
///////////////////
// FEES REGISTRY //
///////////////////
/// @notice Remove fees from the list of registered fees
/// @param _fees Addresses of fees to be deregistered
function deregisterFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "deregisterFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(isRegisteredFee(_fees[i]), "deregisterFees: fee is not registered");
registeredFees.remove(_fees[i]);
emit FeeDeregistered(_fees[i], IFee(_fees[i]).identifier());
}
}
/// @notice Add fees to the list of registered fees
/// @param _fees Addresses of fees to be registered
/// @dev Stores the hooks that a fee implements and whether each implementation uses GAV,
/// which fronts the gas for calls to check if a hook is implemented, and guarantees
/// that these hook implementation return values do not change post-registration.
function registerFees(address[] calldata _fees) external onlyFundDeployerOwner {
require(_fees.length > 0, "registerFees: _fees cannot be empty");
for (uint256 i; i < _fees.length; i++) {
require(!isRegisteredFee(_fees[i]), "registerFees: fee already registered");
registeredFees.add(_fees[i]);
IFee feeContract = IFee(_fees[i]);
(
FeeHook[] memory implementedHooksForSettle,
FeeHook[] memory implementedHooksForUpdate,
bool usesGavOnSettle,
bool usesGavOnUpdate
) = feeContract.implementedHooks();
// Stores the hooks for which each fee implements settle() and update()
for (uint256 j; j < implementedHooksForSettle.length; j++) {
feeToHookToImplementsSettle[_fees[i]][implementedHooksForSettle[j]] = true;
}
for (uint256 j; j < implementedHooksForUpdate.length; j++) {
feeToHookToImplementsUpdate[_fees[i]][implementedHooksForUpdate[j]] = true;
}
// Stores whether each fee requires GAV during its implementations for settle() and update()
if (usesGavOnSettle) {
feeToUsesGavOnSettle[_fees[i]] = true;
}
if (usesGavOnUpdate) {
feeToUsesGavOnUpdate[_fees[i]] = true;
}
emit FeeRegistered(
_fees[i],
feeContract.identifier(),
implementedHooksForSettle,
implementedHooksForUpdate,
usesGavOnSettle,
usesGavOnUpdate
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Get a list of enabled fees for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return enabledFees_ An array of enabled fee addresses
function getEnabledFeesForFund(address _comptrollerProxy)
external
view
returns (address[] memory enabledFees_)
{
return comptrollerProxyToFees[_comptrollerProxy];
}
/// @notice Get the amount of shares outstanding for a particular fee for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fee The fee address
/// @return sharesOutstanding_ The amount of shares outstanding
function getFeeSharesOutstandingForFund(address _comptrollerProxy, address _fee)
external
view
returns (uint256 sharesOutstanding_)
{
return comptrollerProxyToFeeToSharesOutstanding[_comptrollerProxy][_fee];
}
/// @notice Get all registered fees
/// @return registeredFees_ A list of all registered fee addresses
function getRegisteredFees() external view returns (address[] memory registeredFees_) {
registeredFees_ = new address[](registeredFees.length());
for (uint256 i; i < registeredFees_.length; i++) {
registeredFees_[i] = registeredFees.at(i);
}
return registeredFees_;
}
/// @notice Checks if a fee implements settle() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return settlesOnHook_ True if the fee settles on the given hook
function feeSettlesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool settlesOnHook_)
{
return feeToHookToImplementsSettle[_fee][_hook];
}
/// @notice Checks if a fee implements update() on a particular hook
/// @param _fee The address of the fee to check
/// @param _hook The FeeHook to check
/// @return updatesOnHook_ True if the fee updates on the given hook
function feeUpdatesOnHook(address _fee, FeeHook _hook)
public
view
returns (bool updatesOnHook_)
{
return feeToHookToImplementsUpdate[_fee][_hook];
}
/// @notice Checks if a fee uses GAV in its settle() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during settle() implementation
function feeUsesGavOnSettle(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnSettle[_fee];
}
/// @notice Checks if a fee uses GAV in its update() implementation
/// @param _fee The address of the fee to check
/// @return usesGav_ True if the fee uses GAV during update() implementation
function feeUsesGavOnUpdate(address _fee) public view returns (bool usesGav_) {
return feeToUsesGavOnUpdate[_fee];
}
/// @notice Check whether a fee is registered
/// @param _fee The address of the fee to check
/// @return isRegisteredFee_ True if the fee is registered
function isRegisteredFee(address _fee) public view returns (bool isRegisteredFee_) {
return registeredFees.contains(_fee);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/IComptroller.sol";
/// @title PermissionedVaultActionMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for extensions that can make permissioned vault calls
abstract contract PermissionedVaultActionMixin {
/// @notice Adds a tracked asset to the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to add
function __addTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.AddTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Grants an allowance to a spender to use a fund's asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset for which to grant an allowance
/// @param _target The spender of the allowance
/// @param _amount The amount of the allowance
function __approveAssetSpender(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.ApproveAssetSpender,
abi.encode(_asset, _target, _amount)
);
}
/// @notice Burns fund shares for a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account for which to burn shares
/// @param _amount The amount of shares to burn
function __burnShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.BurnShares,
abi.encode(_target, _amount)
);
}
/// @notice Mints fund shares to a particular account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _target The account to which to mint shares
/// @param _amount The amount of shares to mint
function __mintShares(
address _comptrollerProxy,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.MintShares,
abi.encode(_target, _amount)
);
}
/// @notice Removes a tracked asset from the fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to remove
function __removeTrackedAsset(address _comptrollerProxy, address _asset) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.RemoveTrackedAsset,
abi.encode(_asset)
);
}
/// @notice Transfers fund shares from one account to another
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _from The account from which to transfer shares
/// @param _to The account to which to transfer shares
/// @param _amount The amount of shares to transfer
function __transferShares(
address _comptrollerProxy,
address _from,
address _to,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.TransferShares,
abi.encode(_from, _to, _amount)
);
}
/// @notice Withdraws an asset from the VaultProxy to a given account
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _asset The asset to withdraw
/// @param _target The account to which to withdraw the asset
/// @param _amount The amount of asset to withdraw
function __withdrawAssetTo(
address _comptrollerProxy,
address _asset,
address _target,
uint256 _amount
) internal {
IComptroller(_comptrollerProxy).permissionedVaultAction(
IComptroller.VaultAction.WithdrawAssetTo,
abi.encode(_asset, _target, _amount)
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/IWETH.sol";
import "../core/fund/comptroller/ComptrollerLib.sol";
import "../extensions/fee-manager/FeeManager.sol";
/// @title FundActionsWrapper Contract
/// @author Enzyme Council <[email protected]>
/// @notice Logic related to wrapping fund actions, not necessary in the core protocol
contract FundActionsWrapper {
using SafeERC20 for ERC20;
address private immutable FEE_MANAGER;
address private immutable WETH_TOKEN;
mapping(address => bool) private accountToHasMaxWethAllowance;
constructor(address _feeManager, address _weth) public {
FEE_MANAGER = _feeManager;
WETH_TOKEN = _weth;
}
/// @dev Needed in case WETH not fully used during exchangeAndBuyShares,
/// to unwrap into ETH and refund
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Calculates the net value of 1 unit of shares in the fund's denomination asset
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return netShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Accounts for fees outstanding. This is a convenience function for external consumption
/// that can be used to determine the cost of purchasing shares at any given point in time.
/// It essentially just bundles settling all fees that implement the Continuous hook and then
/// looking up the gross share value.
function calcNetShareValueForFund(address _comptrollerProxy)
external
returns (uint256 netShareValue_, bool isValid_)
{
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
return comptrollerProxyContract.calcGrossShareValue(false);
}
/// @notice Exchanges ETH into a fund's denomination asset and then buys shares
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _buyer The account for which to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the sent ETH
/// @param _exchange The exchange on which to execute the swap to the denomination asset
/// @param _exchangeApproveTarget The address that should be given an allowance of WETH
/// for the given _exchange
/// @param _exchangeData The data with which to call the exchange to execute the swap
/// to the denomination asset
/// @param _minInvestmentAmount The minimum amount of the denomination asset
/// to receive in the trade for investment (not necessary for WETH)
/// @return sharesReceivedAmount_ The actual amount of shares received
/// @dev Use a reasonable _minInvestmentAmount always, in case the exchange
/// does not perform as expected (low incoming asset amount, blend of assets, etc).
/// If the fund's denomination asset is WETH, _exchange, _exchangeApproveTarget, _exchangeData,
/// and _minInvestmentAmount will be ignored.
function exchangeAndBuyShares(
address _comptrollerProxy,
address _denominationAsset,
address _buyer,
uint256 _minSharesQuantity,
address _exchange,
address _exchangeApproveTarget,
bytes calldata _exchangeData,
uint256 _minInvestmentAmount
) external payable returns (uint256 sharesReceivedAmount_) {
// Wrap ETH into WETH
IWETH(payable(WETH_TOKEN)).deposit{value: msg.value}();
// If denominationAsset is WETH, can just buy shares directly
if (_denominationAsset == WETH_TOKEN) {
__approveMaxWethAsNeeded(_comptrollerProxy);
return __buyShares(_comptrollerProxy, _buyer, msg.value, _minSharesQuantity);
}
// Exchange ETH to the fund's denomination asset
__approveMaxWethAsNeeded(_exchangeApproveTarget);
(bool success, bytes memory returnData) = _exchange.call(_exchangeData);
require(success, string(returnData));
// Confirm the amount received in the exchange is above the min acceptable amount
uint256 investmentAmount = ERC20(_denominationAsset).balanceOf(address(this));
require(
investmentAmount >= _minInvestmentAmount,
"exchangeAndBuyShares: _minInvestmentAmount not met"
);
// Give the ComptrollerProxy max allowance for its denomination asset as necessary
__approveMaxAsNeeded(_denominationAsset, _comptrollerProxy, investmentAmount);
// Buy fund shares
sharesReceivedAmount_ = __buyShares(
_comptrollerProxy,
_buyer,
investmentAmount,
_minSharesQuantity
);
// Unwrap and refund any remaining WETH not used in the exchange
uint256 remainingWeth = ERC20(WETH_TOKEN).balanceOf(address(this));
if (remainingWeth > 0) {
IWETH(payable(WETH_TOKEN)).withdraw(remainingWeth);
(success, returnData) = msg.sender.call{value: remainingWeth}("");
require(success, string(returnData));
}
return sharesReceivedAmount_;
}
/// @notice Invokes the Continuous fee hook on all specified fees, and then attempts to payout
/// any shares outstanding on those fees
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _fees The fees for which to run these actions
/// @dev This is just a wrapper to execute two callOnExtension() actions atomically, in sequence.
/// The caller must pass in the fees that they want to run this logic on.
function invokeContinuousFeeHookAndPayoutSharesOutstandingForFund(
address _comptrollerProxy,
address[] calldata _fees
) external {
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 0, "");
comptrollerProxyContract.callOnExtension(FEE_MANAGER, 1, abi.encode(_fees));
}
// PUBLIC FUNCTIONS
/// @notice Gets all fees that implement the `Continuous` fee hook for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return continuousFees_ The fees that implement the `Continuous` fee hook
function getContinuousFeesForFund(address _comptrollerProxy)
public
view
returns (address[] memory continuousFees_)
{
FeeManager feeManagerContract = FeeManager(FEE_MANAGER);
address[] memory fees = feeManagerContract.getEnabledFeesForFund(_comptrollerProxy);
// Count the continuous fees
uint256 continuousFeesCount;
bool[] memory implementsContinuousHook = new bool[](fees.length);
for (uint256 i; i < fees.length; i++) {
if (feeManagerContract.feeSettlesOnHook(fees[i], IFeeManager.FeeHook.Continuous)) {
continuousFeesCount++;
implementsContinuousHook[i] = true;
}
}
// Return early if no continuous fees
if (continuousFeesCount == 0) {
return new address[](0);
}
// Create continuous fees array
continuousFees_ = new address[](continuousFeesCount);
uint256 continuousFeesIndex;
for (uint256 i; i < fees.length; i++) {
if (implementsContinuousHook[i]) {
continuousFees_[continuousFeesIndex] = fees[i];
continuousFeesIndex++;
}
}
return continuousFees_;
}
// PRIVATE FUNCTIONS
/// @dev Helper to approve a target with the max amount of an asset, only when necessary
function __approveMaxAsNeeded(
address _asset,
address _target,
uint256 _neededAmount
) internal {
if (ERC20(_asset).allowance(address(this), _target) < _neededAmount) {
ERC20(_asset).safeApprove(_target, type(uint256).max);
}
}
/// @dev Helper to approve a target with the max amount of weth, only when necessary.
/// Since WETH does not decrease the allowance if it uint256(-1), only ever need to do this
/// once per target.
function __approveMaxWethAsNeeded(address _target) internal {
if (!accountHasMaxWethAllowance(_target)) {
ERC20(WETH_TOKEN).safeApprove(_target, type(uint256).max);
accountToHasMaxWethAllowance[_target] = true;
}
}
/// @dev Helper for buying shares
function __buyShares(
address _comptrollerProxy,
address _buyer,
uint256 _investmentAmount,
uint256 _minSharesQuantity
) private returns (uint256 sharesReceivedAmount_) {
address[] memory buyers = new address[](1);
buyers[0] = _buyer;
uint256[] memory investmentAmounts = new uint256[](1);
investmentAmounts[0] = _investmentAmount;
uint256[] memory minSharesQuantities = new uint256[](1);
minSharesQuantities[0] = _minSharesQuantity;
return
ComptrollerLib(_comptrollerProxy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
)[0];
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FEE_MANAGER` variable
/// @return feeManager_ The `FEE_MANAGER` variable value
function getFeeManager() external view returns (address feeManager_) {
return FEE_MANAGER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Checks whether an account has the max allowance for WETH
/// @param _who The account to check
/// @return hasMaxWethAllowance_ True if the account has the max allowance
function accountHasMaxWethAllowance(address _who)
public
view
returns (bool hasMaxWethAllowance_)
{
return accountToHasMaxWethAllowance[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title WETH Interface
/// @author Enzyme Council <[email protected]>
interface IWETH {
function deposit() external payable;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice Provides the logic for AuthUserExecutedSharesRequestorProxy instances,
/// in which shares requests are manually executed by a permissioned user
/// @dev This will not work with a `denominationAsset` that does not transfer
/// the exact expected amount or has an elastic supply.
contract AuthUserExecutedSharesRequestorLib is IAuthUserExecutedSharesRequestor {
using SafeERC20 for ERC20;
using SafeMath for uint256;
event RequestCanceled(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestCreated(
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecuted(
address indexed caller,
address indexed requestOwner,
uint256 investmentAmount,
uint256 minSharesQuantity
);
event RequestExecutorAdded(address indexed account);
event RequestExecutorRemoved(address indexed account);
struct RequestInfo {
uint256 investmentAmount;
uint256 minSharesQuantity;
}
uint256 private constant CANCELLATION_COOLDOWN_TIMELOCK = 10 minutes;
address private comptrollerProxy;
address private denominationAsset;
address private fundOwner;
mapping(address => RequestInfo) private ownerToRequestInfo;
mapping(address => bool) private acctToIsRequestExecutor;
mapping(address => uint256) private ownerToLastRequestCancellation;
modifier onlyFundOwner() {
require(msg.sender == fundOwner, "Only fund owner callable");
_;
}
/// @notice Initializes a proxy instance that uses this library
/// @dev Serves as a per-proxy pseudo-constructor
function init(address _comptrollerProxy) external override {
require(comptrollerProxy == address(0), "init: Already initialized");
comptrollerProxy = _comptrollerProxy;
// Cache frequently-used values that require external calls
ComptrollerLib comptrollerProxyContract = ComptrollerLib(_comptrollerProxy);
denominationAsset = comptrollerProxyContract.getDenominationAsset();
fundOwner = VaultLib(comptrollerProxyContract.getVaultProxy()).getOwner();
}
/// @notice Cancels the shares request of the caller
function cancelRequest() external {
RequestInfo memory request = ownerToRequestInfo[msg.sender];
require(request.investmentAmount > 0, "cancelRequest: Request does not exist");
// Delete the request, start the cooldown period, and return the investment asset
delete ownerToRequestInfo[msg.sender];
ownerToLastRequestCancellation[msg.sender] = block.timestamp;
ERC20(denominationAsset).safeTransfer(msg.sender, request.investmentAmount);
emit RequestCanceled(msg.sender, request.investmentAmount, request.minSharesQuantity);
}
/// @notice Creates a shares request for the caller
/// @param _investmentAmount The amount of the fund's denomination asset to use to buy shares
/// @param _minSharesQuantity The minimum quantity of shares to buy with the _investmentAmount
function createRequest(uint256 _investmentAmount, uint256 _minSharesQuantity) external {
require(_investmentAmount > 0, "createRequest: _investmentAmount must be > 0");
require(
ownerToRequestInfo[msg.sender].investmentAmount == 0,
"createRequest: The request owner can only create one request before executed or canceled"
);
require(
ownerToLastRequestCancellation[msg.sender] <
block.timestamp.sub(CANCELLATION_COOLDOWN_TIMELOCK),
"createRequest: Cannot create request during cancellation cooldown period"
);
// Create the Request and take custody of investment asset
ownerToRequestInfo[msg.sender] = RequestInfo({
investmentAmount: _investmentAmount,
minSharesQuantity: _minSharesQuantity
});
ERC20(denominationAsset).safeTransferFrom(msg.sender, address(this), _investmentAmount);
emit RequestCreated(msg.sender, _investmentAmount, _minSharesQuantity);
}
/// @notice Executes multiple shares requests
/// @param _requestOwners The owners of the pending shares requests
function executeRequests(address[] calldata _requestOwners) external {
require(
msg.sender == fundOwner || isRequestExecutor(msg.sender),
"executeRequests: Invalid caller"
);
require(_requestOwners.length > 0, "executeRequests: _requestOwners can not be empty");
(
address[] memory buyers,
uint256[] memory investmentAmounts,
uint256[] memory minSharesQuantities,
uint256 totalInvestmentAmount
) = __convertRequestsToBuySharesParams(_requestOwners);
// Since ComptrollerProxy instances are fully trusted,
// we can approve them with the max amount of the denomination asset,
// and only top the approval back to max if ever necessary.
address comptrollerProxyCopy = comptrollerProxy;
ERC20 denominationAssetContract = ERC20(denominationAsset);
if (
denominationAssetContract.allowance(address(this), comptrollerProxyCopy) <
totalInvestmentAmount
) {
denominationAssetContract.safeApprove(comptrollerProxyCopy, type(uint256).max);
}
ComptrollerLib(comptrollerProxyCopy).buyShares(
buyers,
investmentAmounts,
minSharesQuantities
);
}
/// @dev Helper to convert raw shares requests into the format required by buyShares().
/// It also removes any empty requests, which is necessary to prevent a DoS attack where a user
/// cancels their request earlier in the same block (can be repeated from multiple accounts).
/// This function also removes shares requests and fires success events as it loops through them.
function __convertRequestsToBuySharesParams(address[] memory _requestOwners)
private
returns (
address[] memory buyers_,
uint256[] memory investmentAmounts_,
uint256[] memory minSharesQuantities_,
uint256 totalInvestmentAmount_
)
{
uint256 existingRequestsCount = _requestOwners.length;
uint256[] memory allInvestmentAmounts = new uint256[](_requestOwners.length);
// Loop through once to get the count of existing requests
for (uint256 i; i < _requestOwners.length; i++) {
allInvestmentAmounts[i] = ownerToRequestInfo[_requestOwners[i]].investmentAmount;
if (allInvestmentAmounts[i] == 0) {
existingRequestsCount--;
}
}
// Loop through a second time to format requests for buyShares(),
// and to delete the requests and emit events early so no further looping is needed.
buyers_ = new address[](existingRequestsCount);
investmentAmounts_ = new uint256[](existingRequestsCount);
minSharesQuantities_ = new uint256[](existingRequestsCount);
uint256 existingRequestsIndex;
for (uint256 i; i < _requestOwners.length; i++) {
if (allInvestmentAmounts[i] == 0) {
continue;
}
buyers_[existingRequestsIndex] = _requestOwners[i];
investmentAmounts_[existingRequestsIndex] = allInvestmentAmounts[i];
minSharesQuantities_[existingRequestsIndex] = ownerToRequestInfo[_requestOwners[i]]
.minSharesQuantity;
totalInvestmentAmount_ = totalInvestmentAmount_.add(allInvestmentAmounts[i]);
delete ownerToRequestInfo[_requestOwners[i]];
emit RequestExecuted(
msg.sender,
buyers_[existingRequestsIndex],
investmentAmounts_[existingRequestsIndex],
minSharesQuantities_[existingRequestsIndex]
);
existingRequestsIndex++;
}
return (buyers_, investmentAmounts_, minSharesQuantities_, totalInvestmentAmount_);
}
///////////////////////////////
// REQUEST EXECUTOR REGISTRY //
///////////////////////////////
/// @notice Adds accounts to request executors
/// @param _requestExecutors Accounts to add
function addRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "addRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
!isRequestExecutor(_requestExecutors[i]),
"addRequestExecutors: Value already set"
);
require(
_requestExecutors[i] != fundOwner,
"addRequestExecutors: The fund owner cannot be added"
);
acctToIsRequestExecutor[_requestExecutors[i]] = true;
emit RequestExecutorAdded(_requestExecutors[i]);
}
}
/// @notice Removes accounts from request executors
/// @param _requestExecutors Accounts to remove
function removeRequestExecutors(address[] calldata _requestExecutors) external onlyFundOwner {
require(_requestExecutors.length > 0, "removeRequestExecutors: Empty _requestExecutors");
for (uint256 i; i < _requestExecutors.length; i++) {
require(
isRequestExecutor(_requestExecutors[i]),
"removeRequestExecutors: Account is not a request executor"
);
acctToIsRequestExecutor[_requestExecutors[i]] = false;
emit RequestExecutorRemoved(_requestExecutors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of `comptrollerProxy` variable
/// @return comptrollerProxy_ The `comptrollerProxy` variable value
function getComptrollerProxy() external view returns (address comptrollerProxy_) {
return comptrollerProxy;
}
/// @notice Gets the value of `denominationAsset` variable
/// @return denominationAsset_ The `denominationAsset` variable value
function getDenominationAsset() external view returns (address denominationAsset_) {
return denominationAsset;
}
/// @notice Gets the value of `fundOwner` variable
/// @return fundOwner_ The `fundOwner` variable value
function getFundOwner() external view returns (address fundOwner_) {
return fundOwner;
}
/// @notice Gets the request info of a user
/// @param _requestOwner The address of the user that creates the request
/// @return requestInfo_ The request info created by the user
function getSharesRequestInfoForOwner(address _requestOwner)
external
view
returns (RequestInfo memory requestInfo_)
{
return ownerToRequestInfo[_requestOwner];
}
/// @notice Checks whether an account is a request executor
/// @param _who The account to check
/// @return isRequestExecutor_ True if _who is a request executor
function isRequestExecutor(address _who) public view returns (bool isRequestExecutor_) {
return acctToIsRequestExecutor[_who];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAuthUserExecutedSharesRequestor Interface
/// @author Enzyme Council <[email protected]>
interface IAuthUserExecutedSharesRequestor {
function init(address) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../core/fund/comptroller/ComptrollerLib.sol";
import "../../core/fund/vault/VaultLib.sol";
import "./AuthUserExecutedSharesRequestorProxy.sol";
import "./IAuthUserExecutedSharesRequestor.sol";
/// @title AuthUserExecutedSharesRequestorFactory Contract
/// @author Enzyme Council <[email protected]>
/// @notice Deploys and maintains a record of AuthUserExecutedSharesRequestorProxy instances
contract AuthUserExecutedSharesRequestorFactory {
event SharesRequestorProxyDeployed(
address indexed comptrollerProxy,
address sharesRequestorProxy
);
address private immutable AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
address private immutable DISPATCHER;
mapping(address => address) private comptrollerProxyToSharesRequestorProxy;
constructor(address _dispatcher, address _authUserExecutedSharesRequestorLib) public {
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB = _authUserExecutedSharesRequestorLib;
DISPATCHER = _dispatcher;
}
/// @notice Deploys a shares requestor proxy instance for a given ComptrollerProxy instance
/// @param _comptrollerProxy The ComptrollerProxy for which to deploy the shares requestor proxy
/// @return sharesRequestorProxy_ The address of the newly-deployed shares requestor proxy
function deploySharesRequestorProxy(address _comptrollerProxy)
external
returns (address sharesRequestorProxy_)
{
// Confirm fund is genuine
VaultLib vaultProxyContract = VaultLib(ComptrollerLib(_comptrollerProxy).getVaultProxy());
require(
vaultProxyContract.getAccessor() == _comptrollerProxy,
"deploySharesRequestorProxy: Invalid VaultProxy for ComptrollerProxy"
);
require(
IDispatcher(DISPATCHER).getFundDeployerForVaultProxy(address(vaultProxyContract)) !=
address(0),
"deploySharesRequestorProxy: Not a genuine fund"
);
// Validate that the caller is the fund owner
require(
msg.sender == vaultProxyContract.getOwner(),
"deploySharesRequestorProxy: Only fund owner callable"
);
// Validate that a proxy does not already exist
require(
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] == address(0),
"deploySharesRequestorProxy: Proxy already exists"
);
// Deploy the proxy
bytes memory constructData = abi.encodeWithSelector(
IAuthUserExecutedSharesRequestor.init.selector,
_comptrollerProxy
);
sharesRequestorProxy_ = address(
new AuthUserExecutedSharesRequestorProxy(
constructData,
AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB
)
);
comptrollerProxyToSharesRequestorProxy[_comptrollerProxy] = sharesRequestorProxy_;
emit SharesRequestorProxyDeployed(_comptrollerProxy, sharesRequestorProxy_);
return sharesRequestorProxy_;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the value of the `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable
/// @return authUserExecutedSharesRequestorLib_ The `AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB` variable value
function getAuthUserExecutedSharesRequestorLib()
external
view
returns (address authUserExecutedSharesRequestorLib_)
{
return AUTH_USER_EXECUTED_SHARES_REQUESTOR_LIB;
}
/// @notice Gets the value of the `DISPATCHER` variable
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the AuthUserExecutedSharesRequestorProxy associated with the given ComptrollerProxy
/// @param _comptrollerProxy The ComptrollerProxy for which to get the associated AuthUserExecutedSharesRequestorProxy
/// @return sharesRequestorProxy_ The associated AuthUserExecutedSharesRequestorProxy address
function getSharesRequestorProxyForComptrollerProxy(address _comptrollerProxy)
external
view
returns (address sharesRequestorProxy_)
{
return comptrollerProxyToSharesRequestorProxy[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/Proxy.sol";
contract AuthUserExecutedSharesRequestorProxy is Proxy {
constructor(bytes memory _constructData, address _authUserExecutedSharesRequestorLib)
public
Proxy(_constructData, _authUserExecutedSharesRequestorLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Proxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all Proxy instances
/// @dev The recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract Proxy {
constructor(bytes memory _constructData, address _contractLogic) public {
assembly {
sstore(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc,
_contractLogic
)
}
(bool success, bytes memory returnData) = _contractLogic.delegatecall(_constructData);
require(success, string(returnData));
}
fallback() external payable {
assembly {
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../utils/Proxy.sol";
/// @title ComptrollerProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all ComptrollerProxy instances
contract ComptrollerProxy is Proxy {
constructor(bytes memory _constructData, address _comptrollerLib)
public
Proxy(_constructData, _comptrollerLib)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../../persistent/dispatcher/IDispatcher.sol";
import "../../../persistent/utils/IMigrationHookHandler.sol";
import "../fund/comptroller/IComptroller.sol";
import "../fund/comptroller/ComptrollerProxy.sol";
import "../fund/vault/IVault.sol";
import "./IFundDeployer.sol";
/// @title FundDeployer Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract of the release.
/// It primarily coordinates fund deployment and fund migration, but
/// it is also deferred to for contract access control and for allowed calls
/// that can be made with a fund's VaultProxy as the msg.sender.
contract FundDeployer is IFundDeployer, IMigrationHookHandler {
event ComptrollerLibSet(address comptrollerLib);
event ComptrollerProxyDeployed(
address indexed creator,
address comptrollerProxy,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData,
bool indexed forMigration
);
event NewFundCreated(
address indexed creator,
address comptrollerProxy,
address vaultProxy,
address indexed fundOwner,
string fundName,
address indexed denominationAsset,
uint256 sharesActionTimelock,
bytes feeManagerConfigData,
bytes policyManagerConfigData
);
event ReleaseStatusSet(ReleaseStatus indexed prevStatus, ReleaseStatus indexed nextStatus);
event VaultCallDeregistered(address indexed contractAddress, bytes4 selector);
event VaultCallRegistered(address indexed contractAddress, bytes4 selector);
// Constants
address private immutable CREATOR;
address private immutable DISPATCHER;
address private immutable VAULT_LIB;
// Pseudo-constants (can only be set once)
address private comptrollerLib;
// Storage
ReleaseStatus private releaseStatus;
mapping(address => mapping(bytes4 => bool)) private contractToSelectorToIsRegisteredVaultCall;
mapping(address => address) private pendingComptrollerProxyToCreator;
modifier onlyLiveRelease() {
require(releaseStatus == ReleaseStatus.Live, "Release is not Live");
_;
}
modifier onlyMigrator(address _vaultProxy) {
require(
IVault(_vaultProxy).canMigrate(msg.sender),
"Only a permissioned migrator can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == getOwner(), "Only the contract owner can call this function");
_;
}
modifier onlyPendingComptrollerProxyCreator(address _comptrollerProxy) {
require(
msg.sender == pendingComptrollerProxyToCreator[_comptrollerProxy],
"Only the ComptrollerProxy creator can call this function"
);
_;
}
constructor(
address _dispatcher,
address _vaultLib,
address[] memory _vaultCallContracts,
bytes4[] memory _vaultCallSelectors
) public {
if (_vaultCallContracts.length > 0) {
__registerVaultCalls(_vaultCallContracts, _vaultCallSelectors);
}
CREATOR = msg.sender;
DISPATCHER = _dispatcher;
VAULT_LIB = _vaultLib;
}
/////////////
// GENERAL //
/////////////
/// @notice Sets the comptrollerLib
/// @param _comptrollerLib The ComptrollerLib contract address
/// @dev Can only be set once
function setComptrollerLib(address _comptrollerLib) external onlyOwner {
require(
comptrollerLib == address(0),
"setComptrollerLib: This value can only be set once"
);
comptrollerLib = _comptrollerLib;
emit ComptrollerLibSet(_comptrollerLib);
}
/// @notice Sets the status of the protocol to a new state
/// @param _nextStatus The next status state to set
function setReleaseStatus(ReleaseStatus _nextStatus) external {
require(
msg.sender == IDispatcher(DISPATCHER).getOwner(),
"setReleaseStatus: Only the Dispatcher owner can call this function"
);
require(
_nextStatus != ReleaseStatus.PreLaunch,
"setReleaseStatus: Cannot return to PreLaunch status"
);
require(
comptrollerLib != address(0),
"setReleaseStatus: Can only set the release status when comptrollerLib is set"
);
ReleaseStatus prevStatus = releaseStatus;
require(_nextStatus != prevStatus, "setReleaseStatus: _nextStatus is the current status");
releaseStatus = _nextStatus;
emit ReleaseStatusSet(prevStatus, _nextStatus);
}
/// @notice Gets the current owner of the contract
/// @return owner_ The contract owner address
/// @dev Dynamically gets the owner based on the Protocol status. The owner is initially the
/// contract's deployer, for convenience in setting up configuration.
/// Ownership is claimed when the owner of the Dispatcher contract (the Enzyme Council)
/// sets the releaseStatus to `Live`.
function getOwner() public view override returns (address owner_) {
if (releaseStatus == ReleaseStatus.PreLaunch) {
return CREATOR;
}
return IDispatcher(DISPATCHER).getOwner();
}
///////////////////
// FUND CREATION //
///////////////////
/// @notice Creates a fully-configured ComptrollerProxy, to which a fund from a previous
/// release can migrate in a subsequent step
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createMigratedFundConfig(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_) {
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
true
);
pendingComptrollerProxyToCreator[comptrollerProxy_] = msg.sender;
return comptrollerProxy_;
}
/// @notice Creates a new fund
/// @param _fundOwner The address of the owner for the fund
/// @param _fundName The name of the fund
/// @param _denominationAsset The contract address of the denomination asset for the fund
/// @param _sharesActionTimelock The minimum number of seconds between any two "shares actions"
/// (buying or selling shares) by the same user
/// @param _feeManagerConfigData Bytes data for the fees to be enabled for the fund
/// @param _policyManagerConfigData Bytes data for the policies to be enabled for the fund
/// @return comptrollerProxy_ The address of the ComptrollerProxy deployed during this action
function createNewFund(
address _fundOwner,
string calldata _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes calldata _feeManagerConfigData,
bytes calldata _policyManagerConfigData
) external onlyLiveRelease returns (address comptrollerProxy_, address vaultProxy_) {
return
__createNewFund(
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
}
/// @dev Helper to avoid the stack-too-deep error during createNewFund
function __createNewFund(
address _fundOwner,
string memory _fundName,
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData
) private returns (address comptrollerProxy_, address vaultProxy_) {
require(_fundOwner != address(0), "__createNewFund: _owner cannot be empty");
comptrollerProxy_ = __deployComptrollerProxy(
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
false
);
vaultProxy_ = IDispatcher(DISPATCHER).deployVaultProxy(
VAULT_LIB,
_fundOwner,
comptrollerProxy_,
_fundName
);
IComptroller(comptrollerProxy_).activate(vaultProxy_, false);
emit NewFundCreated(
msg.sender,
comptrollerProxy_,
vaultProxy_,
_fundOwner,
_fundName,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData
);
return (comptrollerProxy_, vaultProxy_);
}
/// @dev Helper function to deploy a configured ComptrollerProxy
function __deployComptrollerProxy(
address _denominationAsset,
uint256 _sharesActionTimelock,
bytes memory _feeManagerConfigData,
bytes memory _policyManagerConfigData,
bool _forMigration
) private returns (address comptrollerProxy_) {
require(
_denominationAsset != address(0),
"__deployComptrollerProxy: _denominationAsset cannot be empty"
);
bytes memory constructData = abi.encodeWithSelector(
IComptroller.init.selector,
_denominationAsset,
_sharesActionTimelock
);
comptrollerProxy_ = address(new ComptrollerProxy(constructData, comptrollerLib));
if (_feeManagerConfigData.length > 0 || _policyManagerConfigData.length > 0) {
IComptroller(comptrollerProxy_).configureExtensions(
_feeManagerConfigData,
_policyManagerConfigData
);
}
emit ComptrollerProxyDeployed(
msg.sender,
comptrollerProxy_,
_denominationAsset,
_sharesActionTimelock,
_feeManagerConfigData,
_policyManagerConfigData,
_forMigration
);
return comptrollerProxy_;
}
//////////////////
// MIGRATION IN //
//////////////////
/// @notice Cancels fund migration
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigration(address _vaultProxy) external {
__cancelMigration(_vaultProxy, false);
}
/// @notice Cancels fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to cancel migration
function cancelMigrationEmergency(address _vaultProxy) external {
__cancelMigration(_vaultProxy, true);
}
/// @notice Executes fund migration
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigration(address _vaultProxy) external {
__executeMigration(_vaultProxy, false);
}
/// @notice Executes fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to execute the migration
function executeMigrationEmergency(address _vaultProxy) external {
__executeMigration(_vaultProxy, true);
}
/// @dev Unimplemented
function invokeMigrationInCancelHook(
address,
address,
address,
address
) external virtual override {
return;
}
/// @notice Signal a fund migration
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigration(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, false);
}
/// @notice Signal a fund migration, bypassing any failures.
/// Should be used in an emergency only.
/// @param _vaultProxy The VaultProxy for which to signal the migration
/// @param _comptrollerProxy The ComptrollerProxy for which to signal the migration
function signalMigrationEmergency(address _vaultProxy, address _comptrollerProxy) external {
__signalMigration(_vaultProxy, _comptrollerProxy, true);
}
/// @dev Helper to cancel a migration
function __cancelMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).cancelMigration(_vaultProxy, _bypassFailure);
}
/// @dev Helper to execute a migration
function __executeMigration(address _vaultProxy, bool _bypassFailure)
private
onlyLiveRelease
onlyMigrator(_vaultProxy)
{
IDispatcher dispatcherContract = IDispatcher(DISPATCHER);
(, address comptrollerProxy, , ) = dispatcherContract
.getMigrationRequestDetailsForVaultProxy(_vaultProxy);
dispatcherContract.executeMigration(_vaultProxy, _bypassFailure);
IComptroller(comptrollerProxy).activate(_vaultProxy, true);
delete pendingComptrollerProxyToCreator[comptrollerProxy];
}
/// @dev Helper to signal a migration
function __signalMigration(
address _vaultProxy,
address _comptrollerProxy,
bool _bypassFailure
)
private
onlyLiveRelease
onlyPendingComptrollerProxyCreator(_comptrollerProxy)
onlyMigrator(_vaultProxy)
{
IDispatcher(DISPATCHER).signalMigration(
_vaultProxy,
_comptrollerProxy,
VAULT_LIB,
_bypassFailure
);
}
///////////////////
// MIGRATION OUT //
///////////////////
/// @notice Allows "hooking into" specific moments in the migration pipeline
/// to execute arbitrary logic during a migration out of this release
/// @param _vaultProxy The VaultProxy being migrated
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address,
address,
address
) external override {
if (_hook != MigrationOutHook.PreMigrate) {
return;
}
require(
msg.sender == DISPATCHER,
"postMigrateOriginHook: Only Dispatcher can call this function"
);
// Must use PreMigrate hook to get the ComptrollerProxy from the VaultProxy
address comptrollerProxy = IVault(_vaultProxy).getAccessor();
// Wind down fund and destroy its config
IComptroller(comptrollerProxy).destruct();
}
//////////////
// REGISTRY //
//////////////
/// @notice De-registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to de-register
/// @param _selectors The selectors of the calls to de-register
function deregisterVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "deregisterVaultCalls: Empty _contracts");
require(
_contracts.length == _selectors.length,
"deregisterVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
isRegisteredVaultCall(_contracts[i], _selectors[i]),
"deregisterVaultCalls: Call not registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = false;
emit VaultCallDeregistered(_contracts[i], _selectors[i]);
}
}
/// @notice Registers allowed arbitrary contract calls that can be sent from the VaultProxy
/// @param _contracts The contracts of the calls to register
/// @param _selectors The selectors of the calls to register
function registerVaultCalls(address[] calldata _contracts, bytes4[] calldata _selectors)
external
onlyOwner
{
require(_contracts.length > 0, "registerVaultCalls: Empty _contracts");
__registerVaultCalls(_contracts, _selectors);
}
/// @dev Helper to register allowed vault calls
function __registerVaultCalls(address[] memory _contracts, bytes4[] memory _selectors)
private
{
require(
_contracts.length == _selectors.length,
"__registerVaultCalls: Uneven input arrays"
);
for (uint256 i; i < _contracts.length; i++) {
require(
!isRegisteredVaultCall(_contracts[i], _selectors[i]),
"__registerVaultCalls: Call already registered"
);
contractToSelectorToIsRegisteredVaultCall[_contracts[i]][_selectors[i]] = true;
emit VaultCallRegistered(_contracts[i], _selectors[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `comptrollerLib` variable value
/// @return comptrollerLib_ The `comptrollerLib` variable value
function getComptrollerLib() external view returns (address comptrollerLib_) {
return comptrollerLib;
}
/// @notice Gets the `CREATOR` variable value
/// @return creator_ The `CREATOR` variable value
function getCreator() external view returns (address creator_) {
return CREATOR;
}
/// @notice Gets the `DISPATCHER` variable value
/// @return dispatcher_ The `DISPATCHER` variable value
function getDispatcher() external view returns (address dispatcher_) {
return DISPATCHER;
}
/// @notice Gets the creator of a pending ComptrollerProxy
/// @return pendingComptrollerProxyCreator_ The pending ComptrollerProxy creator
function getPendingComptrollerProxyCreator(address _comptrollerProxy)
external
view
returns (address pendingComptrollerProxyCreator_)
{
return pendingComptrollerProxyToCreator[_comptrollerProxy];
}
/// @notice Gets the `releaseStatus` variable value
/// @return status_ The `releaseStatus` variable value
function getReleaseStatus() external view override returns (ReleaseStatus status_) {
return releaseStatus;
}
/// @notice Gets the `VAULT_LIB` variable value
/// @return vaultLib_ The `VAULT_LIB` variable value
function getVaultLib() external view returns (address vaultLib_) {
return VAULT_LIB;
}
/// @notice Checks if a contract call is registered
/// @param _contract The contract of the call to check
/// @param _selector The selector of the call to check
/// @return isRegistered_ True if the call is registered
function isRegisteredVaultCall(address _contract, bytes4 _selector)
public
view
override
returns (bool isRegistered_)
{
return contractToSelectorToIsRegisteredVaultCall[_contract][_selector];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IMigrationHookHandler Interface
/// @author Enzyme Council <[email protected]>
interface IMigrationHookHandler {
enum MigrationOutHook {PreSignal, PostSignal, PreMigrate, PostMigrate, PostCancel}
function invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
function invokeMigrationOutHook(
MigrationOutHook _hook,
address _vaultProxy,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib
) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "../../core/fund/vault/IVault.sol";
import "../../infrastructure/price-feeds/derivatives/IDerivativePriceFeed.sol";
import "../../infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
import "../../utils/AddressArrayLib.sol";
import "../../utils/AssetFinalityResolver.sol";
import "../policy-manager/IPolicyManager.sol";
import "../utils/ExtensionBase.sol";
import "../utils/FundDeployerOwnerMixin.sol";
import "../utils/PermissionedVaultActionMixin.sol";
import "./integrations/IIntegrationAdapter.sol";
import "./IIntegrationManager.sol";
/// @title IntegrationManager
/// @author Enzyme Council <[email protected]>
/// @notice Extension to handle DeFi integration actions for funds
contract IntegrationManager is
IIntegrationManager,
ExtensionBase,
FundDeployerOwnerMixin,
PermissionedVaultActionMixin,
AssetFinalityResolver
{
using AddressArrayLib for address[];
using EnumerableSet for EnumerableSet.AddressSet;
using SafeMath for uint256;
event AdapterDeregistered(address indexed adapter, string indexed identifier);
event AdapterRegistered(address indexed adapter, string indexed identifier);
event AuthUserAddedForFund(address indexed comptrollerProxy, address indexed account);
event AuthUserRemovedForFund(address indexed comptrollerProxy, address indexed account);
event CallOnIntegrationExecutedForFund(
address indexed comptrollerProxy,
address vaultProxy,
address caller,
address indexed adapter,
bytes4 indexed selector,
bytes integrationData,
address[] incomingAssets,
uint256[] incomingAssetAmounts,
address[] outgoingAssets,
uint256[] outgoingAssetAmounts
);
address private immutable DERIVATIVE_PRICE_FEED;
address private immutable POLICY_MANAGER;
address private immutable PRIMITIVE_PRICE_FEED;
EnumerableSet.AddressSet private registeredAdapters;
mapping(address => mapping(address => bool)) private comptrollerProxyToAcctToIsAuthUser;
constructor(
address _fundDeployer,
address _policyManager,
address _derivativePriceFeed,
address _primitivePriceFeed,
address _synthetixPriceFeed,
address _synthetixAddressResolver
)
public
FundDeployerOwnerMixin(_fundDeployer)
AssetFinalityResolver(_synthetixPriceFeed, _synthetixAddressResolver)
{
DERIVATIVE_PRICE_FEED = _derivativePriceFeed;
POLICY_MANAGER = _policyManager;
PRIMITIVE_PRICE_FEED = _primitivePriceFeed;
}
/////////////
// GENERAL //
/////////////
/// @notice Activates the extension by storing the VaultProxy
function activateForFund(bool) external override {
__setValidatedVaultProxy(msg.sender);
}
/// @notice Authorizes a user to act on behalf of a fund via the IntegrationManager
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The user to authorize
function addAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, true);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = true;
emit AuthUserAddedForFund(_comptrollerProxy, _who);
}
/// @notice Deactivate the extension by destroying storage
function deactivateForFund() external override {
delete comptrollerProxyToVaultProxy[msg.sender];
}
/// @notice Removes an authorized user from the IntegrationManager for the given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The authorized user to remove
function removeAuthUserForFund(address _comptrollerProxy, address _who) external {
__validateSetAuthUser(_comptrollerProxy, _who, false);
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] = false;
emit AuthUserRemovedForFund(_comptrollerProxy, _who);
}
/// @notice Checks whether an account is an authorized IntegrationManager user for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _who The account to check
/// @return isAuthUser_ True if the account is an authorized user or the fund owner
function isAuthUserForFund(address _comptrollerProxy, address _who)
public
view
returns (bool isAuthUser_)
{
return
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who] ||
_who == IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
}
/// @dev Helper to validate calls to update comptrollerProxyToAcctToIsAuthUser
function __validateSetAuthUser(
address _comptrollerProxy,
address _who,
bool _nextIsAuthUser
) private view {
require(
comptrollerProxyToVaultProxy[_comptrollerProxy] != address(0),
"__validateSetAuthUser: Fund has not been activated"
);
address fundOwner = IVault(comptrollerProxyToVaultProxy[_comptrollerProxy]).getOwner();
require(
msg.sender == fundOwner,
"__validateSetAuthUser: Only the fund owner can call this function"
);
require(_who != fundOwner, "__validateSetAuthUser: Cannot set for the fund owner");
if (_nextIsAuthUser) {
require(
!comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is already an authorized user"
);
} else {
require(
comptrollerProxyToAcctToIsAuthUser[_comptrollerProxy][_who],
"__validateSetAuthUser: Account is not an authorized user"
);
}
}
///////////////////////////////
// CALL-ON-EXTENSION ACTIONS //
///////////////////////////////
/// @notice Receives a dispatched `callOnExtension` from a fund's ComptrollerProxy
/// @param _caller The user who called for this action
/// @param _actionId An ID representing the desired action
/// @param _callArgs The encoded args for the action
function receiveCallFromComptroller(
address _caller,
uint256 _actionId,
bytes calldata _callArgs
) external override {
// Since we validate and store the ComptrollerProxy-VaultProxy pairing during
// activateForFund(), this function does not require further validation of the
// sending ComptrollerProxy
address vaultProxy = comptrollerProxyToVaultProxy[msg.sender];
require(vaultProxy != address(0), "receiveCallFromComptroller: Fund is not active");
require(
isAuthUserForFund(msg.sender, _caller),
"receiveCallFromComptroller: Not an authorized user"
);
// Dispatch the action
if (_actionId == 0) {
__callOnIntegration(_caller, vaultProxy, _callArgs);
} else if (_actionId == 1) {
__addZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else if (_actionId == 2) {
__removeZeroBalanceTrackedAssets(vaultProxy, _callArgs);
} else {
revert("receiveCallFromComptroller: Invalid _actionId");
}
}
/// @dev Adds assets with a zero balance as tracked assets of the fund
function __addZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs) private {
address[] memory assets = abi.decode(_callArgs, (address[]));
for (uint256 i; i < assets.length; i++) {
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__addZeroBalanceTrackedAssets: Balance is not zero"
);
__addTrackedAsset(msg.sender, assets[i]);
}
}
/// @dev Removes assets with a zero balance from tracked assets of the fund
function __removeZeroBalanceTrackedAssets(address _vaultProxy, bytes memory _callArgs)
private
{
address[] memory assets = abi.decode(_callArgs, (address[]));
address denominationAsset = IComptroller(msg.sender).getDenominationAsset();
for (uint256 i; i < assets.length; i++) {
require(
assets[i] != denominationAsset,
"__removeZeroBalanceTrackedAssets: Cannot remove denomination asset"
);
require(
__finalizeIfSynthAndGetAssetBalance(_vaultProxy, assets[i], true) == 0,
"__removeZeroBalanceTrackedAssets: Balance is not zero"
);
__removeTrackedAsset(msg.sender, assets[i]);
}
}
/////////////////////////
// CALL ON INTEGRATION //
/////////////////////////
/// @notice Universal method for calling third party contract functions through adapters
/// @param _caller The caller of this function via the ComptrollerProxy
/// @param _vaultProxy The VaultProxy of the fund
/// @param _callArgs The encoded args for this function
/// - _adapter Adapter of the integration on which to execute a call
/// - _selector Method selector of the adapter method to execute
/// - _integrationData Encoded arguments specific to the adapter
/// @dev msg.sender is the ComptrollerProxy.
/// Refer to specific adapter to see how to encode its arguments.
function __callOnIntegration(
address _caller,
address _vaultProxy,
bytes memory _callArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
__preCoIHook(adapter, selector);
/// Passing decoded _callArgs leads to stack-too-deep error
(
address[] memory incomingAssets,
uint256[] memory incomingAssetAmounts,
address[] memory outgoingAssets,
uint256[] memory outgoingAssetAmounts
) = __callOnIntegrationInner(_vaultProxy, _callArgs);
__postCoIHook(
adapter,
selector,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
__emitCoIEvent(
_vaultProxy,
_caller,
adapter,
selector,
integrationData,
incomingAssets,
incomingAssetAmounts,
outgoingAssets,
outgoingAssetAmounts
);
}
/// @dev Helper to execute the bulk of logic of callOnIntegration.
/// Avoids the stack-too-deep-error.
function __callOnIntegrationInner(address vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
(
address[] memory expectedIncomingAssets,
uint256[] memory preCallIncomingAssetBalances,
uint256[] memory minIncomingAssetAmounts,
SpendAssetsHandleType spendAssetsHandleType,
address[] memory spendAssets,
uint256[] memory maxSpendAssetAmounts,
uint256[] memory preCallSpendAssetBalances
) = __preProcessCoI(vaultProxy, _callArgs);
__executeCoI(
vaultProxy,
_callArgs,
abi.encode(
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
expectedIncomingAssets
)
);
(
incomingAssets_,
incomingAssetAmounts_,
outgoingAssets_,
outgoingAssetAmounts_
) = __postProcessCoI(
vaultProxy,
expectedIncomingAssets,
preCallIncomingAssetBalances,
minIncomingAssetAmounts,
spendAssetsHandleType,
spendAssets,
maxSpendAssetAmounts,
preCallSpendAssetBalances
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to decode CoI args
function __decodeCallOnIntegrationArgs(bytes memory _callArgs)
private
pure
returns (
address adapter_,
bytes4 selector_,
bytes memory integrationData_
)
{
return abi.decode(_callArgs, (address, bytes4, bytes));
}
/// @dev Helper to emit the CallOnIntegrationExecuted event.
/// Avoids stack-too-deep error.
function __emitCoIEvent(
address _vaultProxy,
address _caller,
address _adapter,
bytes4 _selector,
bytes memory _integrationData,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
emit CallOnIntegrationExecutedForFund(
msg.sender,
_vaultProxy,
_caller,
_adapter,
_selector,
_integrationData,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
);
}
/// @dev Helper to execute a call to an integration
/// @dev Avoids stack-too-deep error
function __executeCoI(
address _vaultProxy,
bytes memory _callArgs,
bytes memory _encodedAssetTransferArgs
) private {
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
(bool success, bytes memory returnData) = adapter.call(
abi.encodeWithSelector(
selector,
_vaultProxy,
integrationData,
_encodedAssetTransferArgs
)
);
require(success, string(returnData));
}
/// @dev Helper to get the vault's balance of a particular asset
function __getVaultAssetBalance(address _vaultProxy, address _asset)
private
view
returns (uint256)
{
return ERC20(_asset).balanceOf(_vaultProxy);
}
/// @dev Helper to check if an asset is supported
function __isSupportedAsset(address _asset) private view returns (bool isSupported_) {
return
IPrimitivePriceFeed(PRIMITIVE_PRICE_FEED).isSupportedAsset(_asset) ||
IDerivativePriceFeed(DERIVATIVE_PRICE_FEED).isSupportedAsset(_asset);
}
/// @dev Helper for the actions to take on external contracts prior to executing CoI
function __preCoIHook(address _adapter, bytes4 _selector) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PreCallOnIntegration,
abi.encode(_adapter, _selector)
);
}
/// @dev Helper for the internal actions to take prior to executing CoI
function __preProcessCoI(address _vaultProxy, bytes memory _callArgs)
private
returns (
address[] memory expectedIncomingAssets_,
uint256[] memory preCallIncomingAssetBalances_,
uint256[] memory minIncomingAssetAmounts_,
SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory maxSpendAssetAmounts_,
uint256[] memory preCallSpendAssetBalances_
)
{
(
address adapter,
bytes4 selector,
bytes memory integrationData
) = __decodeCallOnIntegrationArgs(_callArgs);
require(adapterIsRegistered(adapter), "callOnIntegration: Adapter is not registered");
// Note that expected incoming and spend assets are allowed to overlap
// (e.g., a fee for the incomingAsset charged in a spend asset)
(
spendAssetsHandleType_,
spendAssets_,
maxSpendAssetAmounts_,
expectedIncomingAssets_,
minIncomingAssetAmounts_
) = IIntegrationAdapter(adapter).parseAssetsForMethod(selector, integrationData);
require(
spendAssets_.length == maxSpendAssetAmounts_.length,
"__preProcessCoI: Spend assets arrays unequal"
);
require(
expectedIncomingAssets_.length == minIncomingAssetAmounts_.length,
"__preProcessCoI: Incoming assets arrays unequal"
);
require(spendAssets_.isUniqueSet(), "__preProcessCoI: Duplicate spend asset");
require(
expectedIncomingAssets_.isUniqueSet(),
"__preProcessCoI: Duplicate incoming asset"
);
IVault vaultProxyContract = IVault(_vaultProxy);
preCallIncomingAssetBalances_ = new uint256[](expectedIncomingAssets_.length);
for (uint256 i = 0; i < expectedIncomingAssets_.length; i++) {
require(
expectedIncomingAssets_[i] != address(0),
"__preProcessCoI: Empty incoming asset address"
);
require(
minIncomingAssetAmounts_[i] > 0,
"__preProcessCoI: minIncomingAssetAmount must be >0"
);
require(
__isSupportedAsset(expectedIncomingAssets_[i]),
"__preProcessCoI: Non-receivable incoming asset"
);
// Get pre-call balance of each incoming asset.
// If the asset is not tracked by the fund, allow the balance to default to 0.
if (vaultProxyContract.isTrackedAsset(expectedIncomingAssets_[i])) {
// We do not require incoming asset finality, but we attempt to finalize so that
// the final incoming asset amount is more accurate. There is no need to finalize
// post-tx.
preCallIncomingAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
expectedIncomingAssets_[i],
false
);
}
}
// Get pre-call balances of spend assets and grant approvals to adapter
preCallSpendAssetBalances_ = new uint256[](spendAssets_.length);
for (uint256 i = 0; i < spendAssets_.length; i++) {
require(spendAssets_[i] != address(0), "__preProcessCoI: Empty spend asset");
require(maxSpendAssetAmounts_[i] > 0, "__preProcessCoI: Empty max spend asset amount");
// A spend asset must either be a tracked asset of the fund or a supported asset,
// in order to prevent seeding the fund with a malicious token and performing arbitrary
// actions within an adapter.
require(
vaultProxyContract.isTrackedAsset(spendAssets_[i]) ||
__isSupportedAsset(spendAssets_[i]),
"__preProcessCoI: Non-spendable spend asset"
);
// If spend asset is also an incoming asset, no need to record its balance
if (!expectedIncomingAssets_.contains(spendAssets_[i])) {
// By requiring spend asset finality before CoI, we will know whether or
// not the asset balance was entirely spent during the call. There is no need
// to finalize post-tx.
preCallSpendAssetBalances_[i] = __finalizeIfSynthAndGetAssetBalance(
_vaultProxy,
spendAssets_[i],
true
);
}
// Grant spend assets access to the adapter.
// Note that spendAssets_ is already asserted to a unique set.
if (spendAssetsHandleType_ == SpendAssetsHandleType.Approve) {
// Use exact approve amount rather than increasing allowances,
// because all adapters finish their actions atomically.
__approveAssetSpender(
msg.sender,
spendAssets_[i],
adapter,
maxSpendAssetAmounts_[i]
);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Transfer) {
__withdrawAssetTo(msg.sender, spendAssets_[i], adapter, maxSpendAssetAmounts_[i]);
} else if (spendAssetsHandleType_ == SpendAssetsHandleType.Remove) {
__removeTrackedAsset(msg.sender, spendAssets_[i]);
}
}
}
/// @dev Helper for the actions to take on external contracts after executing CoI
function __postCoIHook(
address _adapter,
bytes4 _selector,
address[] memory _incomingAssets,
uint256[] memory _incomingAssetAmounts,
address[] memory _outgoingAssets,
uint256[] memory _outgoingAssetAmounts
) private {
IPolicyManager(POLICY_MANAGER).validatePolicies(
msg.sender,
IPolicyManager.PolicyHook.PostCallOnIntegration,
abi.encode(
_adapter,
_selector,
_incomingAssets,
_incomingAssetAmounts,
_outgoingAssets,
_outgoingAssetAmounts
)
);
}
/// @dev Helper to reconcile and format incoming and outgoing assets after executing CoI
function __postProcessCoI(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory incomingAssets_,
uint256[] memory incomingAssetAmounts_,
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_
)
{
address[] memory increasedSpendAssets;
uint256[] memory increasedSpendAssetAmounts;
(
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets,
increasedSpendAssetAmounts
) = __reconcileCoISpendAssets(
_vaultProxy,
_spendAssetsHandleType,
_spendAssets,
_maxSpendAssetAmounts,
_preCallSpendAssetBalances
);
(incomingAssets_, incomingAssetAmounts_) = __reconcileCoIIncomingAssets(
_vaultProxy,
_expectedIncomingAssets,
_preCallIncomingAssetBalances,
_minIncomingAssetAmounts,
increasedSpendAssets,
increasedSpendAssetAmounts
);
return (incomingAssets_, incomingAssetAmounts_, outgoingAssets_, outgoingAssetAmounts_);
}
/// @dev Helper to process incoming asset balance changes.
/// See __reconcileCoISpendAssets() for explanation on "increasedSpendAssets".
function __reconcileCoIIncomingAssets(
address _vaultProxy,
address[] memory _expectedIncomingAssets,
uint256[] memory _preCallIncomingAssetBalances,
uint256[] memory _minIncomingAssetAmounts,
address[] memory _increasedSpendAssets,
uint256[] memory _increasedSpendAssetAmounts
) private returns (address[] memory incomingAssets_, uint256[] memory incomingAssetAmounts_) {
// Incoming assets = expected incoming assets + spend assets with increased balances
uint256 incomingAssetsCount = _expectedIncomingAssets.length.add(
_increasedSpendAssets.length
);
// Calculate and validate incoming asset amounts
incomingAssets_ = new address[](incomingAssetsCount);
incomingAssetAmounts_ = new uint256[](incomingAssetsCount);
for (uint256 i = 0; i < _expectedIncomingAssets.length; i++) {
uint256 balanceDiff = __getVaultAssetBalance(_vaultProxy, _expectedIncomingAssets[i])
.sub(_preCallIncomingAssetBalances[i]);
require(
balanceDiff >= _minIncomingAssetAmounts[i],
"__reconcileCoIAssets: Received incoming asset less than expected"
);
// Even if the asset's previous balance was >0, it might not have been tracked
__addTrackedAsset(msg.sender, _expectedIncomingAssets[i]);
incomingAssets_[i] = _expectedIncomingAssets[i];
incomingAssetAmounts_[i] = balanceDiff;
}
// Append increaseSpendAssets to incomingAsset vars
if (_increasedSpendAssets.length > 0) {
uint256 incomingAssetIndex = _expectedIncomingAssets.length;
for (uint256 i = 0; i < _increasedSpendAssets.length; i++) {
incomingAssets_[incomingAssetIndex] = _increasedSpendAssets[i];
incomingAssetAmounts_[incomingAssetIndex] = _increasedSpendAssetAmounts[i];
incomingAssetIndex++;
}
}
return (incomingAssets_, incomingAssetAmounts_);
}
/// @dev Helper to process spend asset balance changes.
/// "outgoingAssets" are the spend assets with a decrease in balance.
/// "increasedSpendAssets" are the spend assets with an unexpected increase in balance.
/// For example, "increasedSpendAssets" can occur if an adapter has a pre-balance of
/// the spendAsset, which would be transferred to the fund at the end of the tx.
function __reconcileCoISpendAssets(
address _vaultProxy,
SpendAssetsHandleType _spendAssetsHandleType,
address[] memory _spendAssets,
uint256[] memory _maxSpendAssetAmounts,
uint256[] memory _preCallSpendAssetBalances
)
private
returns (
address[] memory outgoingAssets_,
uint256[] memory outgoingAssetAmounts_,
address[] memory increasedSpendAssets_,
uint256[] memory increasedSpendAssetAmounts_
)
{
// Determine spend asset balance changes
uint256[] memory postCallSpendAssetBalances = new uint256[](_spendAssets.length);
uint256 outgoingAssetsCount;
uint256 increasedSpendAssetsCount;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssetsCount++;
continue;
}
// Determine if the asset is outgoing or incoming, and store the post-balance for later use
postCallSpendAssetBalances[i] = __getVaultAssetBalance(_vaultProxy, _spendAssets[i]);
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
outgoingAssetsCount++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetsCount++;
}
}
// Format outgoingAssets and increasedSpendAssets (spend assets with unexpected increase in balance)
outgoingAssets_ = new address[](outgoingAssetsCount);
outgoingAssetAmounts_ = new uint256[](outgoingAssetsCount);
increasedSpendAssets_ = new address[](increasedSpendAssetsCount);
increasedSpendAssetAmounts_ = new uint256[](increasedSpendAssetsCount);
uint256 outgoingAssetsIndex;
uint256 increasedSpendAssetsIndex;
for (uint256 i = 0; i < _spendAssets.length; i++) {
// If spend asset's initial balance is 0, then it is an incoming asset.
if (_preCallSpendAssetBalances[i] == 0) {
continue;
}
// Handle SpendAssetsHandleType.Remove separately.
// No need to validate the max spend asset amount.
if (_spendAssetsHandleType == SpendAssetsHandleType.Remove) {
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
outgoingAssetsIndex++;
continue;
}
// If the pre- and post- balances are equal, then the asset is neither incoming nor outgoing
if (postCallSpendAssetBalances[i] < _preCallSpendAssetBalances[i]) {
if (postCallSpendAssetBalances[i] == 0) {
__removeTrackedAsset(msg.sender, _spendAssets[i]);
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i];
} else {
outgoingAssetAmounts_[outgoingAssetsIndex] = _preCallSpendAssetBalances[i].sub(
postCallSpendAssetBalances[i]
);
}
require(
outgoingAssetAmounts_[outgoingAssetsIndex] <= _maxSpendAssetAmounts[i],
"__reconcileCoISpendAssets: Spent amount greater than expected"
);
outgoingAssets_[outgoingAssetsIndex] = _spendAssets[i];
outgoingAssetsIndex++;
} else if (postCallSpendAssetBalances[i] > _preCallSpendAssetBalances[i]) {
increasedSpendAssetAmounts_[increasedSpendAssetsIndex] = postCallSpendAssetBalances[i]
.sub(_preCallSpendAssetBalances[i]);
increasedSpendAssets_[increasedSpendAssetsIndex] = _spendAssets[i];
increasedSpendAssetsIndex++;
}
}
return (
outgoingAssets_,
outgoingAssetAmounts_,
increasedSpendAssets_,
increasedSpendAssetAmounts_
);
}
///////////////////////////
// INTEGRATIONS REGISTRY //
///////////////////////////
/// @notice Remove integration adapters from the list of registered adapters
/// @param _adapters Addresses of adapters to be deregistered
function deregisterAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "deregisterAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(
adapterIsRegistered(_adapters[i]),
"deregisterAdapters: Adapter is not registered"
);
registeredAdapters.remove(_adapters[i]);
emit AdapterDeregistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
/// @notice Add integration adapters to the list of registered adapters
/// @param _adapters Addresses of adapters to be registered
function registerAdapters(address[] calldata _adapters) external onlyFundDeployerOwner {
require(_adapters.length > 0, "registerAdapters: _adapters cannot be empty");
for (uint256 i; i < _adapters.length; i++) {
require(_adapters[i] != address(0), "registerAdapters: Adapter cannot be empty");
require(
!adapterIsRegistered(_adapters[i]),
"registerAdapters: Adapter already registered"
);
registeredAdapters.add(_adapters[i]);
emit AdapterRegistered(_adapters[i], IIntegrationAdapter(_adapters[i]).identifier());
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Checks if an integration adapter is registered
/// @param _adapter The adapter to check
/// @return isRegistered_ True if the adapter is registered
function adapterIsRegistered(address _adapter) public view returns (bool isRegistered_) {
return registeredAdapters.contains(_adapter);
}
/// @notice Gets the `DERIVATIVE_PRICE_FEED` variable
/// @return derivativePriceFeed_ The `DERIVATIVE_PRICE_FEED` variable value
function getDerivativePriceFeed() external view returns (address derivativePriceFeed_) {
return DERIVATIVE_PRICE_FEED;
}
/// @notice Gets the `POLICY_MANAGER` variable
/// @return policyManager_ The `POLICY_MANAGER` variable value
function getPolicyManager() external view returns (address policyManager_) {
return POLICY_MANAGER;
}
/// @notice Gets the `PRIMITIVE_PRICE_FEED` variable
/// @return primitivePriceFeed_ The `PRIMITIVE_PRICE_FEED` variable value
function getPrimitivePriceFeed() external view returns (address primitivePriceFeed_) {
return PRIMITIVE_PRICE_FEED;
}
/// @notice Gets all registered integration adapters
/// @return registeredAdaptersArray_ A list of all registered integration adapters
function getRegisteredAdapters()
external
view
returns (address[] memory registeredAdaptersArray_)
{
registeredAdaptersArray_ = new address[](registeredAdapters.length());
for (uint256 i = 0; i < registeredAdaptersArray_.length; i++) {
registeredAdaptersArray_[i] = registeredAdapters.at(i);
}
return registeredAdaptersArray_;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/SynthetixPriceFeed.sol";
import "../../../../interfaces/ISynthetix.sol";
import "../utils/AdapterBase.sol";
/// @title SynthetixAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Synthetix
contract SynthetixAdapter is AdapterBase {
address private immutable ORIGINATOR;
address private immutable SYNTHETIX;
address private immutable SYNTHETIX_PRICE_FEED;
bytes32 private immutable TRACKING_CODE;
constructor(
address _integrationManager,
address _synthetixPriceFeed,
address _originator,
address _synthetix,
bytes32 _trackingCode
) public AdapterBase(_integrationManager) {
ORIGINATOR = _originator;
SYNTHETIX = _synthetix;
SYNTHETIX_PRICE_FEED = _synthetixPriceFeed;
TRACKING_CODE = _trackingCode;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "SYNTHETIX";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.None,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Synthetix
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address incomingAsset,
,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address[] memory synths = new address[](2);
synths[0] = outgoingAsset;
synths[1] = incomingAsset;
bytes32[] memory currencyKeys = SynthetixPriceFeed(SYNTHETIX_PRICE_FEED)
.getCurrencyKeysForSynths(synths);
ISynthetix(SYNTHETIX).exchangeOnBehalfWithTracking(
_vaultProxy,
currencyKeys[0],
outgoingAssetAmount,
currencyKeys[1],
ORIGINATOR,
TRACKING_CODE
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ORIGINATOR` variable
/// @return originator_ The `ORIGINATOR` variable value
function getOriginator() external view returns (address originator_) {
return ORIGINATOR;
}
/// @notice Gets the `SYNTHETIX` variable
/// @return synthetix_ The `SYNTHETIX` variable value
function getSynthetix() external view returns (address synthetix_) {
return SYNTHETIX;
}
/// @notice Gets the `SYNTHETIX_PRICE_FEED` variable
/// @return synthetixPriceFeed_ The `SYNTHETIX_PRICE_FEED` variable value
function getSynthetixPriceFeed() external view returns (address synthetixPriceFeed_) {
return SYNTHETIX_PRICE_FEED;
}
/// @notice Gets the `TRACKING_CODE` variable
/// @return trackingCode_ The `TRACKING_CODE` variable value
function getTrackingCode() external view returns (bytes32 trackingCode_) {
return TRACKING_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../interfaces/IChainlinkAggregator.sol";
import "../../utils/DispatcherOwnerMixin.sol";
import "./IPrimitivePriceFeed.sol";
/// @title ChainlinkPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice A price feed that uses Chainlink oracles as price sources
contract ChainlinkPriceFeed is IPrimitivePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event EthUsdAggregatorSet(address prevEthUsdAggregator, address nextEthUsdAggregator);
event PrimitiveAdded(
address indexed primitive,
address aggregator,
RateAsset rateAsset,
uint256 unit
);
event PrimitiveRemoved(address indexed primitive);
event PrimitiveUpdated(
address indexed primitive,
address prevAggregator,
address nextAggregator
);
event StalePrimitiveRemoved(address indexed primitive);
event StaleRateThresholdSet(uint256 prevStaleRateThreshold, uint256 nextStaleRateThreshold);
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
uint256 private constant ETH_UNIT = 10**18;
address private immutable WETH_TOKEN;
address private ethUsdAggregator;
uint256 private staleRateThreshold;
mapping(address => AggregatorInfo) private primitiveToAggregatorInfo;
mapping(address => uint256) private primitiveToUnit;
constructor(
address _dispatcher,
address _wethToken,
address _ethUsdAggregator,
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) public DispatcherOwnerMixin(_dispatcher) {
WETH_TOKEN = _wethToken;
staleRateThreshold = 25 hours; // 24 hour heartbeat + 1hr buffer
__setEthUsdAggregator(_ethUsdAggregator);
if (_primitives.length > 0) {
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
}
// EXTERNAL FUNCTIONS
/// @notice Calculates the value of a base asset in terms of a quote asset (using a canonical rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
function calcCanonicalValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) public view override returns (uint256 quoteAssetAmount_, bool isValid_) {
// Case where _baseAsset == _quoteAsset is handled by ValueInterpreter
int256 baseAssetRate = __getLatestRateData(_baseAsset);
if (baseAssetRate <= 0) {
return (0, false);
}
int256 quoteAssetRate = __getLatestRateData(_quoteAsset);
if (quoteAssetRate <= 0) {
return (0, false);
}
(quoteAssetAmount_, isValid_) = __calcConversionAmount(
_baseAsset,
_baseAssetAmount,
uint256(baseAssetRate),
_quoteAsset,
uint256(quoteAssetRate)
);
return (quoteAssetAmount_, isValid_);
}
/// @notice Calculates the value of a base asset in terms of a quote asset (using a live rate)
/// @param _baseAsset The base asset
/// @param _baseAssetAmount The base asset amount to convert
/// @param _quoteAsset The quote asset
/// @return quoteAssetAmount_ The equivalent quote asset amount
/// @return isValid_ True if the rates used in calculations are deemed valid
/// @dev Live and canonical values are the same for Chainlink
function calcLiveValue(
address _baseAsset,
uint256 _baseAssetAmount,
address _quoteAsset
) external view override returns (uint256 quoteAssetAmount_, bool isValid_) {
return calcCanonicalValue(_baseAsset, _baseAssetAmount, _quoteAsset);
}
/// @notice Checks whether an asset is a supported primitive of the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported primitive
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return _asset == WETH_TOKEN || primitiveToAggregatorInfo[_asset].aggregator != address(0);
}
/// @notice Sets the `ehUsdAggregator` variable value
/// @param _nextEthUsdAggregator The `ehUsdAggregator` value to set
function setEthUsdAggregator(address _nextEthUsdAggregator) external onlyDispatcherOwner {
__setEthUsdAggregator(_nextEthUsdAggregator);
}
// PRIVATE FUNCTIONS
/// @dev Helper to convert an amount from a _baseAsset to a _quoteAsset
function __calcConversionAmount(
address _baseAsset,
uint256 _baseAssetAmount,
uint256 _baseAssetRate,
address _quoteAsset,
uint256 _quoteAssetRate
) private view returns (uint256 quoteAssetAmount_, bool isValid_) {
RateAsset baseAssetRateAsset = getRateAssetForPrimitive(_baseAsset);
RateAsset quoteAssetRateAsset = getRateAssetForPrimitive(_quoteAsset);
uint256 baseAssetUnit = getUnitForPrimitive(_baseAsset);
uint256 quoteAssetUnit = getUnitForPrimitive(_quoteAsset);
// If rates are both in ETH or both in USD
if (baseAssetRateAsset == quoteAssetRateAsset) {
return (
__calcConversionAmountSameRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate
),
true
);
}
int256 ethPerUsdRate = IChainlinkAggregator(ethUsdAggregator).latestAnswer();
if (ethPerUsdRate <= 0) {
return (0, false);
}
// If _baseAsset's rate is in ETH and _quoteAsset's rate is in USD
if (baseAssetRateAsset == RateAsset.ETH) {
return (
__calcConversionAmountEthRateAssetToUsdRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
// If _baseAsset's rate is in USD and _quoteAsset's rate is in ETH
return (
__calcConversionAmountUsdRateAssetToEthRateAsset(
_baseAssetAmount,
baseAssetUnit,
_baseAssetRate,
quoteAssetUnit,
_quoteAssetRate,
uint256(ethPerUsdRate)
),
true
);
}
/// @dev Helper to convert amounts where the base asset has an ETH rate and the quote asset has a USD rate
function __calcConversionAmountEthRateAssetToUsdRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow.
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_ethPerUsdRate).div(
ETH_UNIT
);
return intermediateStep.mul(_quoteAssetUnit).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to convert amounts where base and quote assets both have ETH rates or both have USD rates
function __calcConversionAmountSameRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
return
_baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_baseAssetUnit.mul(_quoteAssetRate)
);
}
/// @dev Helper to convert amounts where the base asset has a USD rate and the quote asset has an ETH rate
function __calcConversionAmountUsdRateAssetToEthRateAsset(
uint256 _baseAssetAmount,
uint256 _baseAssetUnit,
uint256 _baseAssetRate,
uint256 _quoteAssetUnit,
uint256 _quoteAssetRate,
uint256 _ethPerUsdRate
) private pure returns (uint256 quoteAssetAmount_) {
// Only allows two consecutive multiplication operations to avoid potential overflow
// Intermediate step needed to resolve stack-too-deep error.
uint256 intermediateStep = _baseAssetAmount.mul(_baseAssetRate).mul(_quoteAssetUnit).div(
_ethPerUsdRate
);
return intermediateStep.mul(ETH_UNIT).div(_baseAssetUnit).div(_quoteAssetRate);
}
/// @dev Helper to get the latest rate for a given primitive
function __getLatestRateData(address _primitive) private view returns (int256 rate_) {
if (_primitive == WETH_TOKEN) {
return int256(ETH_UNIT);
}
address aggregator = primitiveToAggregatorInfo[_primitive].aggregator;
require(aggregator != address(0), "__getLatestRateData: Primitive does not exist");
return IChainlinkAggregator(aggregator).latestAnswer();
}
/// @dev Helper to set the `ethUsdAggregator` value
function __setEthUsdAggregator(address _nextEthUsdAggregator) private {
address prevEthUsdAggregator = ethUsdAggregator;
require(
_nextEthUsdAggregator != prevEthUsdAggregator,
"__setEthUsdAggregator: Value already set"
);
__validateAggregator(_nextEthUsdAggregator);
ethUsdAggregator = _nextEthUsdAggregator;
emit EthUsdAggregatorSet(prevEthUsdAggregator, _nextEthUsdAggregator);
}
/////////////////////////
// PRIMITIVES REGISTRY //
/////////////////////////
/// @notice Adds a list of primitives with the given aggregator and rateAsset values
/// @param _primitives The primitives to add
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
/// @param _rateAssets The ordered rate assets corresponding to the list of _primitives
function addPrimitives(
address[] calldata _primitives,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyDispatcherOwner {
require(_primitives.length > 0, "addPrimitives: _primitives cannot be empty");
__addPrimitives(_primitives, _aggregators, _rateAssets);
}
/// @notice Removes a list of primitives from the feed
/// @param _primitives The primitives to remove
function removePrimitives(address[] calldata _primitives) external onlyDispatcherOwner {
require(_primitives.length > 0, "removePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator != address(0),
"removePrimitives: Primitive not yet added"
);
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit PrimitiveRemoved(_primitives[i]);
}
}
/// @notice Removes stale primitives from the feed
/// @param _primitives The stale primitives to remove
/// @dev Callable by anybody
function removeStalePrimitives(address[] calldata _primitives) external {
require(_primitives.length > 0, "removeStalePrimitives: _primitives cannot be empty");
for (uint256 i; i < _primitives.length; i++) {
address aggregatorAddress = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(aggregatorAddress != address(0), "removeStalePrimitives: Invalid primitive");
require(rateIsStale(aggregatorAddress), "removeStalePrimitives: Rate is not stale");
delete primitiveToAggregatorInfo[_primitives[i]];
delete primitiveToUnit[_primitives[i]];
emit StalePrimitiveRemoved(_primitives[i]);
}
}
/// @notice Sets the `staleRateThreshold` variable
/// @param _nextStaleRateThreshold The next `staleRateThreshold` value
function setStaleRateThreshold(uint256 _nextStaleRateThreshold) external onlyDispatcherOwner {
uint256 prevStaleRateThreshold = staleRateThreshold;
require(
_nextStaleRateThreshold != prevStaleRateThreshold,
"__setStaleRateThreshold: Value already set"
);
staleRateThreshold = _nextStaleRateThreshold;
emit StaleRateThresholdSet(prevStaleRateThreshold, _nextStaleRateThreshold);
}
/// @notice Updates the aggregators for given primitives
/// @param _primitives The primitives to update
/// @param _aggregators The ordered aggregators corresponding to the list of _primitives
function updatePrimitives(address[] calldata _primitives, address[] calldata _aggregators)
external
onlyDispatcherOwner
{
require(_primitives.length > 0, "updatePrimitives: _primitives cannot be empty");
require(
_primitives.length == _aggregators.length,
"updatePrimitives: Unequal _primitives and _aggregators array lengths"
);
for (uint256 i; i < _primitives.length; i++) {
address prevAggregator = primitiveToAggregatorInfo[_primitives[i]].aggregator;
require(prevAggregator != address(0), "updatePrimitives: Primitive not yet added");
require(_aggregators[i] != prevAggregator, "updatePrimitives: Value already set");
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]].aggregator = _aggregators[i];
emit PrimitiveUpdated(_primitives[i], prevAggregator, _aggregators[i]);
}
}
/// @notice Checks whether the current rate is considered stale for the specified aggregator
/// @param _aggregator The Chainlink aggregator of which to check staleness
/// @return rateIsStale_ True if the rate is considered stale
function rateIsStale(address _aggregator) public view returns (bool rateIsStale_) {
return
IChainlinkAggregator(_aggregator).latestTimestamp() <
block.timestamp.sub(staleRateThreshold);
}
/// @dev Helper to add primitives to the feed
function __addPrimitives(
address[] memory _primitives,
address[] memory _aggregators,
RateAsset[] memory _rateAssets
) private {
require(
_primitives.length == _aggregators.length,
"__addPrimitives: Unequal _primitives and _aggregators array lengths"
);
require(
_primitives.length == _rateAssets.length,
"__addPrimitives: Unequal _primitives and _rateAssets array lengths"
);
for (uint256 i = 0; i < _primitives.length; i++) {
require(
primitiveToAggregatorInfo[_primitives[i]].aggregator == address(0),
"__addPrimitives: Value already set"
);
__validateAggregator(_aggregators[i]);
primitiveToAggregatorInfo[_primitives[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
// Store the amount that makes up 1 unit given the asset's decimals
uint256 unit = 10**uint256(ERC20(_primitives[i]).decimals());
primitiveToUnit[_primitives[i]] = unit;
emit PrimitiveAdded(_primitives[i], _aggregators[i], _rateAssets[i], unit);
}
}
/// @dev Helper to validate an aggregator by checking its return values for the expected interface
function __validateAggregator(address _aggregator) private view {
require(_aggregator != address(0), "__validateAggregator: Empty _aggregator");
require(
IChainlinkAggregator(_aggregator).latestAnswer() > 0,
"__validateAggregator: No rate detected"
);
require(!rateIsStale(_aggregator), "__validateAggregator: Stale rate detected");
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the aggregatorInfo variable value for a primitive
/// @param _primitive The primitive asset for which to get the aggregatorInfo value
/// @return aggregatorInfo_ The aggregatorInfo value
function getAggregatorInfoForPrimitive(address _primitive)
external
view
returns (AggregatorInfo memory aggregatorInfo_)
{
return primitiveToAggregatorInfo[_primitive];
}
/// @notice Gets the `ethUsdAggregator` variable value
/// @return ethUsdAggregator_ The `ethUsdAggregator` variable value
function getEthUsdAggregator() external view returns (address ethUsdAggregator_) {
return ethUsdAggregator;
}
/// @notice Gets the `staleRateThreshold` variable value
/// @return staleRateThreshold_ The `staleRateThreshold` variable value
function getStaleRateThreshold() external view returns (uint256 staleRateThreshold_) {
return staleRateThreshold;
}
/// @notice Gets the `WETH_TOKEN` variable value
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
/// @notice Gets the rateAsset variable value for a primitive
/// @return rateAsset_ The rateAsset variable value
/// @dev This isn't strictly necessary as WETH_TOKEN will be undefined and thus
/// the RateAsset will be the 0-position of the enum (i.e. ETH), but it makes the
/// behavior more explicit
function getRateAssetForPrimitive(address _primitive)
public
view
returns (RateAsset rateAsset_)
{
if (_primitive == WETH_TOKEN) {
return RateAsset.ETH;
}
return primitiveToAggregatorInfo[_primitive].rateAsset;
}
/// @notice Gets the unit variable value for a primitive
/// @return unit_ The unit variable value
function getUnitForPrimitive(address _primitive) public view returns (uint256 unit_) {
if (_primitive == WETH_TOKEN) {
return ETH_UNIT;
}
return primitiveToUnit[_primitive];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../release/infrastructure/value-interpreter/IValueInterpreter.sol";
import "../../release/infrastructure/price-feeds/derivatives/IAggregatedDerivativePriceFeed.sol";
import "../../release/infrastructure/price-feeds/primitives/IPrimitivePriceFeed.sol";
/// @dev This contract acts as a centralized rate provider for mocks.
/// Suited for a dev environment, it doesn't take into account gas costs.
contract CentralizedRateProvider is Ownable {
using SafeMath for uint256;
address private immutable WETH;
uint256 private maxDeviationPerSender;
// Addresses are not immutable to facilitate lazy load (they're are not accessible at the mock env).
address private valueInterpreter;
address private aggregateDerivativePriceFeed;
address private primitivePriceFeed;
constructor(address _weth, uint256 _maxDeviationPerSender) public {
maxDeviationPerSender = _maxDeviationPerSender;
WETH = _weth;
}
/// @dev Calculates the value of a _baseAsset relative to a _quoteAsset.
/// Label to ValueInterprete's calcLiveAssetValue
function calcLiveAssetValue(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) public returns (uint256 value_) {
uint256 baseDecimalsRate = 10**uint256(ERC20(_baseAsset).decimals());
uint256 quoteDecimalsRate = 10**uint256(ERC20(_quoteAsset).decimals());
// 1. Check if quote asset is a primitive. If it is, use ValueInterpreter normally.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_quoteAsset)) {
(value_, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
_amount,
_quoteAsset
);
return value_;
}
// 2. Otherwise, check if base asset is a primitive, and use inverse rate from Value Interpreter.
if (IPrimitivePriceFeed(primitivePriceFeed).isSupportedAsset(_baseAsset)) {
(uint256 inverseRate, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
10**uint256(ERC20(_quoteAsset).decimals()),
_baseAsset
);
uint256 rate = uint256(baseDecimalsRate).mul(quoteDecimalsRate).div(inverseRate);
value_ = _amount.mul(rate).div(baseDecimalsRate);
return value_;
}
// 3. If both assets are derivatives, calculate the rate against ETH.
(uint256 baseToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_baseAsset,
baseDecimalsRate,
WETH
);
(uint256 quoteToWeth, ) = IValueInterpreter(valueInterpreter).calcLiveAssetValue(
_quoteAsset,
quoteDecimalsRate,
WETH
);
value_ = _amount.mul(baseToWeth).mul(quoteDecimalsRate).div(quoteToWeth).div(
baseDecimalsRate
);
return value_;
}
/// @dev Calculates a randomized live value of an asset
/// Aggregation of two randomization seeds: msg.sender, and by block.number.
function calcLiveAssetValueRandomized(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
// Range [liveAssetValue * (1 - _blockNumberDeviation), liveAssetValue * (1 + _blockNumberDeviation)]
uint256 senderRandomizedValue_ = __calcValueRandomizedByAddress(
liveAssetValue,
msg.sender,
maxDeviationPerSender
);
// Range [liveAssetValue * (1 - _maxDeviationPerBlock - maxDeviationPerSender), liveAssetValue * (1 + _maxDeviationPerBlock + maxDeviationPerSender)]
value_ = __calcValueRandomizedByUint(
senderRandomizedValue_,
block.number,
_maxDeviationPerBlock
);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo randomization, using msg.sender as the source of randomness
function calcLiveAssetValueRandomizedByBlockNumber(
address _baseAsset,
uint256 _amount,
address _quoteAsset,
uint256 _maxDeviationPerBlock
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByUint(liveAssetValue, block.number, _maxDeviationPerBlock);
return value_;
}
/// @dev Calculates the live value of an asset including a grade of pseudo-randomization, using `block.number` as the source of randomness
function calcLiveAssetValueRandomizedBySender(
address _baseAsset,
uint256 _amount,
address _quoteAsset
) external returns (uint256 value_) {
uint256 liveAssetValue = calcLiveAssetValue(_baseAsset, _amount, _quoteAsset);
value_ = __calcValueRandomizedByAddress(liveAssetValue, msg.sender, maxDeviationPerSender);
return value_;
}
function setMaxDeviationPerSender(uint256 _maxDeviationPerSender) external onlyOwner {
maxDeviationPerSender = _maxDeviationPerSender;
}
/// @dev Connector from release environment, inject price variables into the provider.
function setReleasePriceAddresses(
address _valueInterpreter,
address _aggregateDerivativePriceFeed,
address _primitivePriceFeed
) external onlyOwner {
valueInterpreter = _valueInterpreter;
aggregateDerivativePriceFeed = _aggregateDerivativePriceFeed;
primitivePriceFeed = _primitivePriceFeed;
}
// PRIVATE FUNCTIONS
/// @dev Calculates a a pseudo-randomized value as a seed an address
function __calcValueRandomizedByAddress(
uint256 _meanValue,
address _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Value between [0, 100]
uint256 senderRandomFactor = uint256(uint8(_seed))
.mul(100)
.div(256)
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, senderRandomFactor, _maxDeviation);
return value_;
}
/// @dev Calculates a a pseudo-randomized value as a seed an uint256
function __calcValueRandomizedByUint(
uint256 _meanValue,
uint256 _seed,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
// Depending on the _seed number, it will be one of {20, 40, 60, 80, 100}
uint256 randomFactor = (_seed.mod(2).mul(20))
.add((_seed.mod(3).mul(40)))
.mul(_maxDeviation)
.div(100);
value_ = __calcDeviatedValue(_meanValue, randomFactor, _maxDeviation);
return value_;
}
/// @dev Given a mean value and a max deviation, returns a value in the spectrum between 0 (_meanValue - maxDeviation) and 100 (_mean + maxDeviation)
/// TODO: Refactor to use 18 decimal precision
function __calcDeviatedValue(
uint256 _meanValue,
uint256 _offset,
uint256 _maxDeviation
) private pure returns (uint256 value_) {
return
_meanValue.add((_meanValue.mul((uint256(2)).mul(_offset)).div(uint256(100)))).sub(
_meanValue.mul(_maxDeviation).div(uint256(100))
);
}
///////////////////
// STATE GETTERS //
///////////////////
function getMaxDeviationPerSender() public view returns (uint256 maxDeviationPerSender_) {
return maxDeviationPerSender;
}
function getValueInterpreter() public view returns (address valueInterpreter_) {
return valueInterpreter;
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IUniswapV2Pair.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
/// @dev This price source mocks the integration with Uniswap Pair
/// Docs of Uniswap Pair implementation: <https://uniswap.org/docs/v2/smart-contracts/pair/>
contract MockUniswapV2PriceSource is MockToken("Uniswap V2", "UNI-V2", 18) {
using SafeMath for uint256;
address private immutable TOKEN_0;
address private immutable TOKEN_1;
address private immutable CENTRALIZED_RATE_PROVIDER;
constructor(
address _centralizedRateProvider,
address _token0,
address _token1
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
TOKEN_0 = _token0;
TOKEN_1 = _token1;
}
/// @dev returns reserves for each token on the Uniswap Pair
/// Reserves will be used to calculate the pair price
/// Inherited from IUniswapV2Pair
function getReserves()
external
returns (
uint112 reserve0_,
uint112 reserve1_,
uint32 blockTimestampLast_
)
{
uint256 baseAmount = ERC20(TOKEN_0).balanceOf(address(this));
reserve0_ = uint112(baseAmount);
reserve1_ = uint112(
CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN_0,
baseAmount,
TOKEN_1
)
);
return (reserve0_, reserve1_, blockTimestampLast_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Inherited from IUniswapV2Pair
function token0() public view returns (address) {
return TOKEN_0;
}
/// @dev Inherited from IUniswapV2Pair
function token1() public view returns (address) {
return TOKEN_1;
}
/// @dev Inherited from IUniswapV2Pair
function kLast() public pure returns (uint256) {
return 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract MockToken is ERC20Burnable, Ownable {
using SafeMath for uint256;
mapping(address => bool) private addressToIsMinter;
modifier onlyMinter() {
require(
addressToIsMinter[msg.sender] || owner() == msg.sender,
"msg.sender is not owner or minter"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
_mint(msg.sender, uint256(100000000).mul(10**uint256(_decimals)));
}
function mintFor(address _who, uint256 _amount) external onlyMinter {
_mint(_who, _amount);
}
function mint(uint256 _amount) external onlyMinter {
_mint(msg.sender, _amount);
}
function addMinters(address[] memory _minters) public onlyOwner {
for (uint256 i = 0; i < _minters.length; i++) {
addressToIsMinter[_minters[i]] = true;
}
}
}
// 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: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../release/core/fund/comptroller/ComptrollerLib.sol";
import "./MockToken.sol";
/// @title MockReentrancyToken Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock ERC20 token implementation that is able to re-entrance redeemShares and buyShares functions
contract MockReentrancyToken is MockToken("Mock Reentrancy Token", "MRT", 18) {
bool public bad;
address public comptrollerProxy;
function makeItReentracyToken(address _comptrollerProxy) external {
bad = true;
comptrollerProxy = _comptrollerProxy;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).redeemShares();
} else {
_transfer(_msgSender(), recipient, amount);
}
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
if (bad) {
ComptrollerLib(comptrollerProxy).buyShares(
new address[](0),
new uint256[](0),
new uint256[](0)
);
} else {
_transfer(sender, recipient, amount);
}
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixProxyERC20.sol";
import "./../../release/interfaces/ISynthetixSynth.sol";
import "./MockToken.sol";
contract MockSynthetixToken is ISynthetixProxyERC20, ISynthetixSynth, MockToken {
using SafeMath for uint256;
bytes32 public override currencyKey;
uint256 public constant WAITING_PERIOD_SECS = 3 * 60;
mapping(address => uint256) public timelockByAccount;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
bytes32 _currencyKey
) public MockToken(_name, _symbol, _decimals) {
currencyKey = _currencyKey;
}
function setCurrencyKey(bytes32 _currencyKey) external onlyOwner {
currencyKey = _currencyKey;
}
function _isLocked(address account) internal view returns (bool) {
return timelockByAccount[account] >= now;
}
function _beforeTokenTransfer(
address from,
address,
uint256
) internal override {
require(!_isLocked(from), "Cannot settle during waiting period");
}
function target() external view override returns (address) {
return address(this);
}
function isLocked(address account) external view returns (bool) {
return _isLocked(account);
}
function burnFrom(address account, uint256 amount) public override {
_burn(account, amount);
}
function lock(address account) public {
timelockByAccount[account] = now.add(WAITING_PERIOD_SECS);
}
function unlock(address account) public {
timelockByAccount[account] = 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IUniswapV2Factory.sol";
import "../../../../interfaces/IUniswapV2Router2.sol";
import "../utils/AdapterBase.sol";
/// @title UniswapV2Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Uniswap v2
contract UniswapV2Adapter is AdapterBase {
using SafeMath for uint256;
address private immutable FACTORY;
address private immutable ROUTER;
constructor(
address _integrationManager,
address _router,
address _factory
) public AdapterBase(_integrationManager) {
FACTORY = _factory;
ROUTER = _router;
}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "UNISWAP_V2";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAssets[0];
spendAssets_[1] = outgoingAssets[1];
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = maxOutgoingAssetAmounts[0];
spendAssetAmounts_[1] = maxOutgoingAssetAmounts[1];
incomingAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
incomingAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
outgoingAssets[0],
outgoingAssets[1]
);
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
// No need to validate not address(0), this will be caught in IntegrationManager
spendAssets_[0] = IUniswapV2Factory(FACTORY).getPair(
incomingAssets[0],
incomingAssets[1]
);
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](2);
incomingAssets_[0] = incomingAssets[0];
incomingAssets_[1] = incomingAssets[1];
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingAssetAmounts[0];
minIncomingAssetAmounts_[1] = minIncomingAssetAmounts[1];
} else if (_selector == TAKE_ORDER_SELECTOR) {
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
require(path.length >= 2, "parseAssetsForMethod: _path must be >= 2");
spendAssets_ = new address[](1);
spendAssets_[0] = path[0];
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = path[path.length - 1];
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[2] memory outgoingAssets,
uint256[2] memory maxOutgoingAssetAmounts,
uint256[2] memory minOutgoingAssetAmounts,
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(
_vaultProxy,
outgoingAssets[0],
outgoingAssets[1],
maxOutgoingAssetAmounts[0],
maxOutgoingAssetAmounts[1],
minOutgoingAssetAmounts[0],
minOutgoingAssetAmounts[1]
);
}
/// @notice Redeems pool tokens on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingAssetAmount,
address[2] memory incomingAssets,
uint256[2] memory minIncomingAssetAmounts
) = __decodeRedeemCallArgs(_encodedCallArgs);
// More efficient to parse pool token from _encodedAssetTransferArgs than external call
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__redeem(
_vaultProxy,
spendAssets[0],
outgoingAssetAmount,
incomingAssets[0],
incomingAssets[1],
minIncomingAssetAmounts[0],
minIncomingAssetAmounts[1]
);
}
/// @notice Trades assets on Uniswap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address[] memory path,
uint256 outgoingAssetAmount,
uint256 minIncomingAssetAmount
) = __decodeTakeOrderCallArgs(_encodedCallArgs);
__takeOrder(_vaultProxy, outgoingAssetAmount, minIncomingAssetAmount, path);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the lend encoded call arguments
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[2] memory outgoingAssets_,
uint256[2] memory maxOutgoingAssetAmounts_,
uint256[2] memory minOutgoingAssetAmounts_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[2], uint256[2], uint256[2], uint256));
}
/// @dev Helper to decode the redeem encoded call arguments
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
address[2] memory incomingAssets_,
uint256[2] memory minIncomingAssetAmounts_
)
{
return abi.decode(_encodedCallArgs, (uint256, address[2], uint256[2]));
}
/// @dev Helper to decode the take order encoded call arguments
function __decodeTakeOrderCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address[] memory path_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address[], uint256, uint256));
}
/// @dev Helper to execute lend. Avoids stack-too-deep error.
function __lend(
address _vaultProxy,
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_tokenA, ROUTER, _amountADesired);
__approveMaxAsNeeded(_tokenB, ROUTER, _amountBDesired);
// Execute lend on Uniswap
IUniswapV2Router2(ROUTER).addLiquidity(
_tokenA,
_tokenB,
_amountADesired,
_amountBDesired,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute redeem. Avoids stack-too-deep error.
function __redeem(
address _vaultProxy,
address _poolToken,
uint256 _poolTokenAmount,
address _tokenA,
address _tokenB,
uint256 _amountAMin,
uint256 _amountBMin
) private {
__approveMaxAsNeeded(_poolToken, ROUTER, _poolTokenAmount);
// Execute redeem on Uniswap
IUniswapV2Router2(ROUTER).removeLiquidity(
_tokenA,
_tokenB,
_poolTokenAmount,
_amountAMin,
_amountBMin,
_vaultProxy,
block.timestamp.add(1)
);
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
uint256 _outgoingAssetAmount,
uint256 _minIncomingAssetAmount,
address[] memory _path
) private {
__approveMaxAsNeeded(_path[0], ROUTER, _outgoingAssetAmount);
// Execute fill
IUniswapV2Router2(ROUTER).swapExactTokensForTokens(
_outgoingAssetAmount,
_minIncomingAssetAmount,
_path,
_vaultProxy,
block.timestamp.add(1)
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `FACTORY` variable
/// @return factory_ The `FACTORY` variable value
function getFactory() external view returns (address factory_) {
return FACTORY;
}
/// @notice Gets the `ROUTER` variable
/// @return router_ The `ROUTER` variable value
function getRouter() external view returns (address router_) {
return ROUTER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title UniswapV2Router2 Interface
/// @author Enzyme Council <[email protected]>
/// @dev Minimal interface for our interactions with Uniswap V2's Router2
interface IUniswapV2Router2 {
function addLiquidity(
address,
address,
uint256,
uint256,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
);
function removeLiquidity(
address,
address,
uint256,
uint256,
uint256,
address,
uint256
) external returns (uint256, uint256);
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeToken.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CurvePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed for Curve pool tokens
contract CurvePriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event DerivativeAdded(
address indexed derivative,
address indexed pool,
address indexed invariantProxyAsset,
uint256 invariantProxyAssetDecimals
);
event DerivativeRemoved(address indexed derivative);
// Both pool tokens and liquidity gauge tokens are treated the same for pricing purposes.
// We take one asset as representative of the pool's invariant, e.g., WETH for ETH-based pools.
struct DerivativeInfo {
address pool;
address invariantProxyAsset;
uint256 invariantProxyAssetDecimals;
}
uint256 private constant VIRTUAL_PRICE_UNIT = 10**18;
address private immutable ADDRESS_PROVIDER;
mapping(address => DerivativeInfo) private derivativeToInfo;
constructor(address _dispatcher, address _addressProvider)
public
DispatcherOwnerMixin(_dispatcher)
{
ADDRESS_PROVIDER = _addressProvider;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
public
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
DerivativeInfo memory derivativeInfo = derivativeToInfo[_derivative];
require(
derivativeInfo.pool != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
underlyings_ = new address[](1);
underlyings_[0] = derivativeInfo.invariantProxyAsset;
underlyingAmounts_ = new uint256[](1);
if (derivativeInfo.invariantProxyAssetDecimals == 18) {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.div(VIRTUAL_PRICE_UNIT);
} else {
underlyingAmounts_[0] = _derivativeAmount
.mul(ICurveLiquidityPool(derivativeInfo.pool).get_virtual_price())
.mul(10**derivativeInfo.invariantProxyAssetDecimals)
.div(VIRTUAL_PRICE_UNIT.mul(2));
}
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return derivativeToInfo[_asset].pool != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds Curve LP and/or liquidity gauge tokens to the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
/// @param _invariantProxyAssets The ordered assets that act as proxies to the pool invariants,
/// corresponding to each item in _derivatives, e.g., WETH for ETH-based pools
function addDerivatives(
address[] calldata _derivatives,
address[] calldata _invariantProxyAssets
) external onlyDispatcherOwner {
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(
_derivatives.length == _invariantProxyAssets.length,
"addDerivatives: Unequal arrays"
);
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(
_invariantProxyAssets[i] != address(0),
"addDerivatives: Empty invariantProxyAsset"
);
require(!isSupportedAsset(_derivatives[i]), "addDerivatives: Value already set");
// First, try assuming that the derivative is an LP token
ICurveRegistry curveRegistryContract = ICurveRegistry(
ICurveAddressProvider(ADDRESS_PROVIDER).get_registry()
);
address pool = curveRegistryContract.get_pool_from_lp_token(_derivatives[i]);
// If the derivative is not a valid LP token, try to treat it as a liquidity gauge token
if (pool == address(0)) {
// We cannot confirm whether a liquidity gauge token is a valid token
// for a particular liquidity gauge, due to some pools using
// old liquidity gauge contracts that did not incorporate a token
pool = curveRegistryContract.get_pool_from_lp_token(
ICurveLiquidityGaugeToken(_derivatives[i]).lp_token()
);
// Likely unreachable as above calls will revert on Curve, but doesn't hurt
require(
pool != address(0),
"addDerivatives: Not a valid LP token or liquidity gauge token"
);
}
uint256 invariantProxyAssetDecimals = ERC20(_invariantProxyAssets[i]).decimals();
derivativeToInfo[_derivatives[i]] = DerivativeInfo({
pool: pool,
invariantProxyAsset: _invariantProxyAssets[i],
invariantProxyAssetDecimals: invariantProxyAssetDecimals
});
// Confirm that a non-zero price can be returned for the registered derivative
(, uint256[] memory underlyingAmounts) = calcUnderlyingValues(
_derivatives[i],
1 ether
);
require(underlyingAmounts[0] > 0, "addDerivatives: could not calculate valid price");
emit DerivativeAdded(
_derivatives[i],
pool,
_invariantProxyAssets[i],
invariantProxyAssetDecimals
);
}
}
/// @notice Removes Curve LP and/or liquidity gauge tokens from the price feed
/// @param _derivatives Curve LP and/or liquidity gauge tokens to add
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "removeDerivatives: Empty derivative");
require(isSupportedAsset(_derivatives[i]), "removeDerivatives: Value is not set");
delete derivativeToInfo[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `DerivativeInfo` for a given derivative
/// @param _derivative The derivative for which to get the `DerivativeInfo`
/// @return derivativeInfo_ The `DerivativeInfo` value
function getDerivativeInfo(address _derivative)
external
view
returns (DerivativeInfo memory derivativeInfo_)
{
return derivativeToInfo[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface ICurveAddressProvider {
function get_address(uint256) external view returns (address);
function get_registry() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeToken interface
/// @author Enzyme Council <[email protected]>
/// @notice Common interface functions for all Curve liquidity gauge token contracts
interface ICurveLiquidityGaugeToken {
function lp_token() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityPool interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityPool {
function coins(uint256) external view returns (address);
function get_virtual_price() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveRegistry interface
/// @author Enzyme Council <[email protected]>
interface ICurveRegistry {
function get_gauges(address) external view returns (address[10] memory, int128[10] memory);
function get_lp_token(address) external view returns (address);
function get_pool_from_lp_token(address) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveLiquidityGaugeV2.sol";
import "../../../../interfaces/ICurveLiquidityPool.sol";
import "../../../../interfaces/ICurveRegistry.sol";
import "../../../../interfaces/ICurveStableSwapSteth.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase2.sol";
/// @title CurveLiquidityStethAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for liquidity provision in Curve's steth pool (https://www.curve.fi/steth)
contract CurveLiquidityStethAdapter is AdapterBase2 {
int128 private constant POOL_INDEX_ETH = 0;
int128 private constant POOL_INDEX_STETH = 1;
address private immutable LIQUIDITY_GAUGE_TOKEN;
address private immutable LP_TOKEN;
address private immutable POOL;
address private immutable STETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _liquidityGaugeToken,
address _lpToken,
address _pool,
address _stethToken,
address _wethToken
) public AdapterBase2(_integrationManager) {
LIQUIDITY_GAUGE_TOKEN = _liquidityGaugeToken;
LP_TOKEN = _lpToken;
POOL = _pool;
STETH_TOKEN = _stethToken;
WETH_TOKEN = _wethToken;
// Max approve contracts to spend relevant tokens
ERC20(_lpToken).safeApprove(_liquidityGaugeToken, type(uint256).max);
ERC20(_stethToken).safeApprove(_pool, type(uint256).max);
}
/// @dev Needed to receive ETH from redemption and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_LIQUIDITY_STETH";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR || _selector == LEND_AND_STAKE_SELECTOR) {
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingAssetAmount
) = __decodeLendCallArgs(_encodedCallArgs);
if (outgoingWethAmount > 0 && outgoingStethAmount > 0) {
spendAssets_ = new address[](2);
spendAssets_[0] = WETH_TOKEN;
spendAssets_[1] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingWethAmount;
spendAssetAmounts_[1] = outgoingStethAmount;
} else if (outgoingWethAmount > 0) {
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingWethAmount;
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = STETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingStethAmount;
}
incomingAssets_ = new address[](1);
if (_selector == LEND_SELECTOR) {
incomingAssets_[0] = LP_TOKEN;
} else {
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
} else if (_selector == REDEEM_SELECTOR || _selector == UNSTAKE_AND_REDEEM_SELECTOR) {
(
uint256 outgoingAssetAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool receiveSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
if (_selector == REDEEM_SELECTOR) {
spendAssets_[0] = LP_TOKEN;
} else {
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
}
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
if (receiveSingleAsset) {
incomingAssets_ = new address[](1);
minIncomingAssetAmounts_ = new uint256[](1);
if (minIncomingWethAmount == 0) {
require(
minIncomingStethAmount > 0,
"parseAssetsForMethod: No min asset amount specified for receiveSingleAsset"
);
incomingAssets_[0] = STETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingStethAmount;
} else {
require(
minIncomingStethAmount == 0,
"parseAssetsForMethod: Too many min asset amounts specified for receiveSingleAsset"
);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
}
} else {
incomingAssets_ = new address[](2);
incomingAssets_[0] = WETH_TOKEN;
incomingAssets_[1] = STETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](2);
minIncomingAssetAmounts_[0] = minIncomingWethAmount;
minIncomingAssetAmounts_[1] = minIncomingStethAmount;
}
} else if (_selector == STAKE_SELECTOR) {
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LP_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLPTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLPTokenAmount;
} else if (_selector == UNSTAKE_SELECTOR) {
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = LIQUIDITY_GAUGE_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = LP_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = outgoingLiquidityGaugeTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends assets for steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
}
/// @notice Lends assets for steth LP tokens, then stakes the received LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lendAndStake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingWethAmount,
uint256 outgoingStethAmount,
uint256 minIncomingLiquidityGaugeTokenAmount
) = __decodeLendCallArgs(_encodedCallArgs);
__lend(outgoingWethAmount, outgoingStethAmount, minIncomingLiquidityGaugeTokenAmount);
__stake(ERC20(LP_TOKEN).balanceOf(address(this)));
}
/// @notice Redeems steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLPTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__redeem(
outgoingLPTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
/// @notice Stakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function stake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLPTokenAmount = __decodeStakeCallArgs(_encodedCallArgs);
__stake(outgoingLPTokenAmount);
}
/// @notice Unstakes steth LP tokens
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstake(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
uint256 outgoingLiquidityGaugeTokenAmount = __decodeUnstakeCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
}
/// @notice Unstakes steth LP tokens, then redeems them
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function unstakeAndRedeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
postActionIncomingAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
uint256 outgoingLiquidityGaugeTokenAmount,
uint256 minIncomingWethAmount,
uint256 minIncomingStethAmount,
bool redeemSingleAsset
) = __decodeRedeemCallArgs(_encodedCallArgs);
__unstake(outgoingLiquidityGaugeTokenAmount);
__redeem(
outgoingLiquidityGaugeTokenAmount,
minIncomingWethAmount,
minIncomingStethAmount,
redeemSingleAsset
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to execute lend
function __lend(
uint256 _outgoingWethAmount,
uint256 _outgoingStethAmount,
uint256 _minIncomingLPTokenAmount
) private {
if (_outgoingWethAmount > 0) {
IWETH((WETH_TOKEN)).withdraw(_outgoingWethAmount);
}
ICurveStableSwapSteth(POOL).add_liquidity{value: _outgoingWethAmount}(
[_outgoingWethAmount, _outgoingStethAmount],
_minIncomingLPTokenAmount
);
}
/// @dev Helper to execute redeem
function __redeem(
uint256 _outgoingLPTokenAmount,
uint256 _minIncomingWethAmount,
uint256 _minIncomingStethAmount,
bool _redeemSingleAsset
) private {
if (_redeemSingleAsset) {
// "_minIncomingWethAmount > 0 XOR _minIncomingStethAmount > 0" has already been
// validated in parseAssetsForMethod()
if (_minIncomingWethAmount > 0) {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_ETH,
_minIncomingWethAmount
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
} else {
ICurveStableSwapSteth(POOL).remove_liquidity_one_coin(
_outgoingLPTokenAmount,
POOL_INDEX_STETH,
_minIncomingStethAmount
);
}
} else {
ICurveStableSwapSteth(POOL).remove_liquidity(
_outgoingLPTokenAmount,
[_minIncomingWethAmount, _minIncomingStethAmount]
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
/// @dev Helper to execute stake
function __stake(uint256 _lpTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).deposit(_lpTokenAmount, address(this));
}
/// @dev Helper to execute unstake
function __unstake(uint256 _liquidityGaugeTokenAmount) private {
ICurveLiquidityGaugeV2(LIQUIDITY_GAUGE_TOKEN).withdraw(_liquidityGaugeTokenAmount);
}
///////////////////////
// ENCODED CALL ARGS //
///////////////////////
/// @dev Helper to decode the encoded call arguments for lending
function __decodeLendCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingWethAmount_,
uint256 outgoingStethAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256));
}
/// @dev Helper to decode the encoded call arguments for redeeming.
/// If `receiveSingleAsset_` is `true`, then one (and only one) of
/// `minIncomingWethAmount_` and `minIncomingStethAmount_` must be >0
/// to indicate which asset is to be received.
function __decodeRedeemCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
uint256 outgoingAssetAmount_,
uint256 minIncomingWethAmount_,
uint256 minIncomingStethAmount_,
bool receiveSingleAsset_
)
{
return abi.decode(_encodedCallArgs, (uint256, uint256, uint256, bool));
}
/// @dev Helper to decode the encoded call arguments for staking
function __decodeStakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLPTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
/// @dev Helper to decode the encoded call arguments for unstaking
function __decodeUnstakeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingLiquidityGaugeTokenAmount_)
{
return abi.decode(_encodedCallArgs, (uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `LIQUIDITY_GAUGE_TOKEN` variable
/// @return liquidityGaugeToken_ The `LIQUIDITY_GAUGE_TOKEN` variable value
function getLiquidityGaugeToken() external view returns (address liquidityGaugeToken_) {
return LIQUIDITY_GAUGE_TOKEN;
}
/// @notice Gets the `LP_TOKEN` variable
/// @return lpToken_ The `LP_TOKEN` variable value
function getLPToken() external view returns (address lpToken_) {
return LP_TOKEN;
}
/// @notice Gets the `POOL` variable
/// @return pool_ The `POOL` variable value
function getPool() external view returns (address pool_) {
return POOL;
}
/// @notice Gets the `STETH_TOKEN` variable
/// @return stethToken_ The `STETH_TOKEN` variable value
function getStethToken() external view returns (address stethToken_) {
return STETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveLiquidityGaugeV2 interface
/// @author Enzyme Council <[email protected]>
interface ICurveLiquidityGaugeV2 {
function deposit(uint256, address) external;
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveStableSwapSteth interface
/// @author Enzyme Council <[email protected]>
interface ICurveStableSwapSteth {
function add_liquidity(uint256[2] calldata, uint256) external payable returns (uint256);
function remove_liquidity(uint256, uint256[2] calldata) external returns (uint256[2] memory);
function remove_liquidity_one_coin(
uint256,
int128,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./AdapterBase.sol";
/// @title AdapterBase2 Contract
/// @author Enzyme Council <[email protected]>
/// @notice A base contract for integration adapters that extends AdapterBase
/// @dev This is a temporary contract that will be merged into AdapterBase with the next release
abstract contract AdapterBase2 is AdapterBase {
/// @dev Provides a standard implementation for transferring incoming assets and
/// unspent spend assets from an adapter to a VaultProxy at the end of an adapter action
modifier postActionAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(
,
address[] memory spendAssets,
,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
/// @dev Provides a standard implementation for transferring incoming assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionIncomingAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, , , address[] memory incomingAssets) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, incomingAssets);
}
/// @dev Provides a standard implementation for transferring unspent spend assets
/// from an adapter to a VaultProxy at the end of an adapter action
modifier postActionSpendAssetsTransferHandler(
address _vaultProxy,
bytes memory _encodedAssetTransferArgs
) {
_;
(, address[] memory spendAssets, , ) = __decodeEncodedAssetTransferArgs(
_encodedAssetTransferArgs
);
__transferFullAssetBalances(_vaultProxy, spendAssets);
}
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @dev Helper to transfer full asset balances of current contract to the specified target
function __transferFullAssetBalances(address _target, address[] memory _assets) internal {
for (uint256 i = 0; i < _assets.length; i++) {
uint256 balance = ERC20(_assets[i]).balanceOf(address(this));
if (balance > 0) {
ERC20(_assets[i]).safeTransfer(_target, balance);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IParaSwapAugustusSwapper.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title ParaSwapAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with ParaSwap
contract ParaSwapAdapter is AdapterBase {
using SafeMath for uint256;
string private constant REFERRER = "enzyme";
address private immutable EXCHANGE;
address private immutable TOKEN_TRANSFER_PROXY;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _tokenTransferProxy,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
TOKEN_TRANSFER_PROXY = _tokenTransferProxy;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH refund from sent network fees
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "PARASWAP";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
// Format incoming assets
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
// Format outgoing assets depending on if there are network fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
// We are not performing special logic if the incomingAsset is the fee asset
if (outgoingAsset == WETH_TOKEN) {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount.add(totalNetworkFees);
} else {
spendAssets_ = new address[](2);
spendAssets_[0] = outgoingAsset;
spendAssets_[1] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](2);
spendAssetAmounts_[0] = outgoingAssetAmount;
spendAssetAmounts_[1] = totalNetworkFees;
}
} else {
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on ParaSwap
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
__takeOrder(_vaultProxy, _encodedCallArgs);
}
// PRIVATE FUNCTIONS
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to decode the encoded callOnIntegration call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
uint256 expectedIncomingAssetAmount_, // Passed as a courtesy to ParaSwap for analytics
address outgoingAsset_,
uint256 outgoingAssetAmount_,
IParaSwapAugustusSwapper.Path[] memory paths_
)
{
return
abi.decode(
_encodedCallArgs,
(address, uint256, uint256, address, uint256, IParaSwapAugustusSwapper.Path[])
);
}
/// @dev Helper to encode the call to ParaSwap multiSwap() as low-level calldata.
/// Avoids the stack-too-deep error.
function __encodeMultiSwapCallData(
address _vaultProxy,
address _incomingAsset,
uint256 _minIncomingAssetAmount,
uint256 _expectedIncomingAssetAmount, // Passed as a courtesy to ParaSwap for analytics
address _outgoingAsset,
uint256 _outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private pure returns (bytes memory multiSwapCallData) {
return
abi.encodeWithSelector(
IParaSwapAugustusSwapper.multiSwap.selector,
_outgoingAsset, // fromToken
_incomingAsset, // toToken
_outgoingAssetAmount, // fromAmount
_minIncomingAssetAmount, // toAmount
_expectedIncomingAssetAmount, // expectedAmount
_paths, // path
0, // mintPrice
payable(_vaultProxy), // beneficiary
0, // donationPercentage
REFERRER // referrer
);
}
/// @dev Helper to execute ParaSwapAugustusSwapper.multiSwap() via a low-level call.
/// Avoids the stack-too-deep error.
function __executeMultiSwap(bytes memory _multiSwapCallData, uint256 _totalNetworkFees)
private
{
(bool success, bytes memory returnData) = EXCHANGE.call{value: _totalNetworkFees}(
_multiSwapCallData
);
require(success, string(returnData));
}
/// @dev Helper for the inner takeOrder() logic.
/// Avoids the stack-too-deep error.
function __takeOrder(address _vaultProxy, bytes memory _encodedCallArgs) private {
(
address incomingAsset,
uint256 minIncomingAssetAmount,
uint256 expectedIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount,
IParaSwapAugustusSwapper.Path[] memory paths
) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(outgoingAsset, TOKEN_TRANSFER_PROXY, outgoingAssetAmount);
// If there are network fees, unwrap enough WETH to cover the fees
uint256 totalNetworkFees = __calcTotalNetworkFees(paths);
if (totalNetworkFees > 0) {
__unwrapWeth(totalNetworkFees);
}
// Get the callData for the low-level multiSwap() call
bytes memory multiSwapCallData = __encodeMultiSwapCallData(
_vaultProxy,
incomingAsset,
minIncomingAssetAmount,
expectedIncomingAssetAmount,
outgoingAsset,
outgoingAssetAmount,
paths
);
// Execute the trade on ParaSwap
__executeMultiSwap(multiSwapCallData, totalNetworkFees);
// If fees were paid and ETH remains in the contract, wrap it as WETH so it can be returned
if (totalNetworkFees > 0) {
__wrapEth();
}
}
/// @dev Helper to unwrap specified amount of WETH into ETH.
/// Avoids the stack-too-deep error.
function __unwrapWeth(uint256 _amount) private {
IWETH(payable(WETH_TOKEN)).withdraw(_amount);
}
/// @dev Helper to wrap all ETH in contract as WETH.
/// Avoids the stack-too-deep error.
function __wrapEth() private {
uint256 ethBalance = payable(address(this)).balance;
if (ethBalance > 0) {
IWETH(payable(WETH_TOKEN)).deposit{value: ethBalance}();
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `TOKEN_TRANSFER_PROXY` variable
/// @return tokenTransferProxy_ The `TOKEN_TRANSFER_PROXY` variable value
function getTokenTransferProxy() external view returns (address tokenTransferProxy_) {
return TOKEN_TRANSFER_PROXY;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/// @title ParaSwap IAugustusSwapper interface
interface IParaSwapAugustusSwapper {
struct Route {
address payable exchange;
address targetExchange;
uint256 percent;
bytes payload;
uint256 networkFee;
}
struct Path {
address to;
uint256 totalNetworkFee;
Route[] routes;
}
function multiSwap(
address,
address,
uint256,
uint256,
uint256,
Path[] calldata,
uint256,
address payable,
uint256,
string calldata
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/interfaces/IParaSwapAugustusSwapper.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockParaSwapIntegratee is SwapperBase {
using SafeMath for uint256;
address private immutable MOCK_CENTRALIZED_RATE_PROVIDER;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(address _mockCentralizedRateProvider, uint256 _blockNumberDeviation) public {
MOCK_CENTRALIZED_RATE_PROVIDER = _mockCentralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Must be `public` to avoid error
function multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
uint256, // toAmount (min received amount)
uint256, // expectedAmount
IParaSwapAugustusSwapper.Path[] memory _paths,
uint256, // mintPrice
address, // beneficiary
uint256, // donationPercentage
string memory // referrer
) public payable returns (uint256) {
return __multiSwap(_fromToken, _toToken, _fromAmount, _paths);
}
/// @dev Helper to parse the total amount of network fees (in ETH) for the multiSwap() call
function __calcTotalNetworkFees(IParaSwapAugustusSwapper.Path[] memory _paths)
private
pure
returns (uint256 totalNetworkFees_)
{
for (uint256 i; i < _paths.length; i++) {
totalNetworkFees_ = totalNetworkFees_.add(_paths[i].totalNetworkFee);
}
return totalNetworkFees_;
}
/// @dev Helper to avoid the stack-too-deep error
function __multiSwap(
address _fromToken,
address _toToken,
uint256 _fromAmount,
IParaSwapAugustusSwapper.Path[] memory _paths
) private returns (uint256) {
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _toToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = CentralizedRateProvider(MOCK_CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_fromToken, _fromAmount, _toToken, blockNumberDeviation);
uint256 totalNetworkFees = __calcTotalNetworkFees(_paths);
address[] memory assetsToIntegratee;
uint256[] memory assetsToIntegrateeAmounts;
if (totalNetworkFees > 0) {
assetsToIntegratee = new address[](2);
assetsToIntegratee[1] = ETH_ADDRESS;
assetsToIntegrateeAmounts = new uint256[](2);
assetsToIntegrateeAmounts[1] = totalNetworkFees;
} else {
assetsToIntegratee = new address[](1);
assetsToIntegrateeAmounts = new uint256[](1);
}
assetsToIntegratee[0] = _fromToken;
assetsToIntegrateeAmounts[0] = _fromAmount;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
///////////////////
// STATE GETTERS //
///////////////////
function getBlockNumberDeviation() external view returns (uint256 blockNumberDeviation_) {
return blockNumberDeviation;
}
function getCentralizedRateProvider()
external
view
returns (address centralizedRateProvider_)
{
return MOCK_CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract SwapperBase is EthConstantMixin {
receive() external payable {}
function __swapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256 _actualRate
) internal returns (uint256 destAmount_) {
address[] memory assetsToIntegratee = new address[](1);
assetsToIntegratee[0] = _srcToken;
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
assetsToIntegrateeAmounts[0] = _srcAmount;
address[] memory assetsFromIntegratee = new address[](1);
assetsFromIntegratee[0] = _destToken;
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsFromIntegrateeAmounts[0] = _actualRate;
__swap(
_trader,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
return assetsFromIntegrateeAmounts[0];
}
function __swap(
address payable _trader,
address[] memory _assetsToIntegratee,
uint256[] memory _assetsToIntegrateeAmounts,
address[] memory _assetsFromIntegratee,
uint256[] memory _assetsFromIntegrateeAmounts
) internal {
// Take custody of incoming assets
for (uint256 i = 0; i < _assetsToIntegratee.length; i++) {
address asset = _assetsToIntegratee[i];
uint256 amount = _assetsToIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsToIntegratee");
require(amount > 0, "__swap: empty value in _assetsToIntegrateeAmounts");
// Incoming ETH amounts can be ignored
if (asset == ETH_ADDRESS) {
continue;
}
ERC20(asset).transferFrom(_trader, address(this), amount);
}
// Distribute outgoing assets
for (uint256 i = 0; i < _assetsFromIntegratee.length; i++) {
address asset = _assetsFromIntegratee[i];
uint256 amount = _assetsFromIntegrateeAmounts[i];
require(asset != address(0), "__swap: empty value in _assetsFromIntegratee");
require(amount > 0, "__swap: empty value in _assetsFromIntegrateeAmounts");
if (asset == ETH_ADDRESS) {
_trader.transfer(amount);
} else {
ERC20(asset).transfer(_trader, amount);
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
abstract contract EthConstantMixin {
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/NormalizedRateProviderBase.sol";
import "../../utils/SwapperBase.sol";
abstract contract MockIntegrateeBase is NormalizedRateProviderBase, SwapperBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
NormalizedRateProviderBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
override
returns (uint256)
{
// 1. Return constant if base asset is quote asset
if (_baseAsset == _quoteAsset) {
return 10**RATE_PRECISION;
}
// 2. Check for a direct rate
uint256 directRate = assetToAssetRate[_baseAsset][_quoteAsset];
if (directRate > 0) {
return directRate;
}
// 3. Check for inverse direct rate
uint256 iDirectRate = assetToAssetRate[_quoteAsset][_baseAsset];
if (iDirectRate > 0) {
return 10**(RATE_PRECISION.mul(2)).div(iDirectRate);
}
// 4. Else return 1
return 10**RATE_PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./RateProviderBase.sol";
abstract contract NormalizedRateProviderBase is RateProviderBase {
using SafeMath for uint256;
uint256 public immutable RATE_PRECISION;
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
) public RateProviderBase(_specialAssets, _specialAssetDecimals) {
RATE_PRECISION = _ratePrecision;
for (uint256 i = 0; i < _defaultRateAssets.length; i++) {
for (uint256 j = i + 1; j < _defaultRateAssets.length; j++) {
assetToAssetRate[_defaultRateAssets[i]][_defaultRateAssets[j]] =
10**_ratePrecision;
assetToAssetRate[_defaultRateAssets[j]][_defaultRateAssets[i]] =
10**_ratePrecision;
}
}
}
// TODO: move to main contracts' utils for use with prices
function __calcDenormalizedQuoteAssetAmount(
uint256 _baseAssetDecimals,
uint256 _baseAssetAmount,
uint256 _quoteAssetDecimals,
uint256 _rate
) internal view returns (uint256) {
return
_rate.mul(_baseAssetAmount).mul(10**_quoteAssetDecimals).div(
10**(RATE_PRECISION.add(_baseAssetDecimals))
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "./EthConstantMixin.sol";
abstract contract RateProviderBase is EthConstantMixin {
mapping(address => mapping(address => uint256)) public assetToAssetRate;
// Handles non-ERC20 compliant assets like ETH and USD
mapping(address => uint8) public specialAssetToDecimals;
constructor(address[] memory _specialAssets, uint8[] memory _specialAssetDecimals) public {
require(
_specialAssets.length == _specialAssetDecimals.length,
"constructor: _specialAssets and _specialAssetDecimals are uneven lengths"
);
for (uint256 i = 0; i < _specialAssets.length; i++) {
specialAssetToDecimals[_specialAssets[i]] = _specialAssetDecimals[i];
}
specialAssetToDecimals[ETH_ADDRESS] = 18;
}
function __getDecimalsForAsset(address _asset) internal view returns (uint256) {
uint256 decimals = specialAssetToDecimals[_asset];
if (decimals == 0) {
decimals = uint256(ERC20(_asset).decimals());
}
return decimals;
}
function __getRate(address _baseAsset, address _quoteAsset)
internal
view
virtual
returns (uint256)
{
return assetToAssetRate[_baseAsset][_quoteAsset];
}
function setRates(
address[] calldata _baseAssets,
address[] calldata _quoteAssets,
uint256[] calldata _rates
) external {
require(
_baseAssets.length == _quoteAssets.length,
"setRates: _baseAssets and _quoteAssets are uneven lengths"
);
require(
_baseAssets.length == _rates.length,
"setRates: _baseAssets and _rates are uneven lengths"
);
for (uint256 i = 0; i < _baseAssets.length; i++) {
assetToAssetRate[_baseAssets[i]][_quoteAssets[i]] = _rates[i];
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @title AssetUnitCacheMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin to store a cache of asset units
abstract contract AssetUnitCacheMixin {
event AssetUnitCached(address indexed asset, uint256 prevUnit, uint256 nextUnit);
mapping(address => uint256) private assetToUnit;
/// @notice Caches the decimal-relative unit for a given asset
/// @param _asset The asset for which to cache the decimal-relative unit
/// @dev Callable by any account
function cacheAssetUnit(address _asset) public {
uint256 prevUnit = getCachedUnitForAsset(_asset);
uint256 nextUnit = 10**uint256(ERC20(_asset).decimals());
if (nextUnit != prevUnit) {
assetToUnit[_asset] = nextUnit;
emit AssetUnitCached(_asset, prevUnit, nextUnit);
}
}
/// @notice Caches the decimal-relative units for multiple given assets
/// @param _assets The assets for which to cache the decimal-relative units
/// @dev Callable by any account
function cacheAssetUnits(address[] memory _assets) public {
for (uint256 i; i < _assets.length; i++) {
cacheAssetUnit(_assets[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the cached decimal-relative unit for a given asset
/// @param _asset The asset for which to get the cached decimal-relative unit
/// @return unit_ The cached decimal-relative unit
function getCachedUnitForAsset(address _asset) public view returns (uint256 unit_) {
return assetToUnit[_asset];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
/// @title SinglePeggedDerivativePriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for any single derivative that is pegged 1:1 to its underlying
abstract contract SinglePeggedDerivativePriceFeedBase is IDerivativePriceFeed {
address private immutable DERIVATIVE;
address private immutable UNDERLYING;
constructor(address _derivative, address _underlying) public {
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"constructor: Unequal decimals"
);
DERIVATIVE = _derivative;
UNDERLYING = _underlying;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = UNDERLYING;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == DERIVATIVE;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `DERIVATIVE` variable value
/// @return derivative_ The `DERIVATIVE` variable value
function getDerivative() external view returns (address derivative_) {
return DERIVATIVE;
}
/// @notice Gets the `UNDERLYING` variable value
/// @return underlying_ The `UNDERLYING` variable value
function getUnderlying() external view returns (address underlying_) {
return UNDERLYING;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SinglePeggedDerivativePriceFeedBase
contract TestSinglePeggedDerivativePriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _derivative, address _underlying)
public
SinglePeggedDerivativePriceFeedBase(_derivative, _underlying)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title StakehoundEthPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Stakehound stETH, which maps 1:1 with ETH
contract StakehoundEthPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]yme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/SinglePeggedDerivativePriceFeedBase.sol";
/// @title LidoStethPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Lido stETH, which maps 1:1 with ETH (https://lido.fi/)
contract LidoStethPriceFeed is SinglePeggedDerivativePriceFeedBase {
constructor(address _steth, address _weth)
public
SinglePeggedDerivativePriceFeedBase(_steth, _weth)
{}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/IKyberNetworkProxy.sol";
import "../../../../interfaces/IWETH.sol";
import "../../../../utils/MathHelpers.sol";
import "../utils/AdapterBase.sol";
/// @title KyberAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for interacting with Kyber Network
contract KyberAdapter is AdapterBase, MathHelpers {
address private immutable EXCHANGE;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _exchange,
address _wethToken
) public AdapterBase(_integrationManager) {
EXCHANGE = _exchange;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "KYBER_NETWORK";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(
incomingAsset != outgoingAsset,
"parseAssetsForMethod: incomingAsset and outgoingAsset asset cannot be the same"
);
require(outgoingAssetAmount > 0, "parseAssetsForMethod: outgoingAssetAmount must be >0");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Kyber
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(
address incomingAsset,
uint256 minIncomingAssetAmount,
address outgoingAsset,
uint256 outgoingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
uint256 minExpectedRate = __calcNormalizedRate(
ERC20(outgoingAsset).decimals(),
outgoingAssetAmount,
ERC20(incomingAsset).decimals(),
minIncomingAssetAmount
);
if (outgoingAsset == WETH_TOKEN) {
__swapNativeAssetToToken(incomingAsset, outgoingAssetAmount, minExpectedRate);
} else if (incomingAsset == WETH_TOKEN) {
__swapTokenToNativeAsset(outgoingAsset, outgoingAssetAmount, minExpectedRate);
} else {
__swapTokenToToken(incomingAsset, outgoingAsset, outgoingAssetAmount, minExpectedRate);
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address incomingAsset_,
uint256 minIncomingAssetAmount_,
address outgoingAsset_,
uint256 outgoingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, address, uint256));
}
/// @dev Executes a swap of ETH to ERC20
function __swapNativeAssetToToken(
address _incomingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
IWETH(payable(WETH_TOKEN)).withdraw(_outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapEtherToToken{value: _outgoingAssetAmount}(
_incomingAsset,
_minExpectedRate
);
}
/// @dev Executes a swap of ERC20 to ETH
function __swapTokenToNativeAsset(
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToEther(
_outgoingAsset,
_outgoingAssetAmount,
_minExpectedRate
);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
/// @dev Executes a swap of ERC20 to ERC20
function __swapTokenToToken(
address _incomingAsset,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
uint256 _minExpectedRate
) private {
__approveMaxAsNeeded(_outgoingAsset, EXCHANGE, _outgoingAssetAmount);
IKyberNetworkProxy(EXCHANGE).swapTokenToToken(
_outgoingAsset,
_outgoingAssetAmount,
_incomingAsset,
_minExpectedRate
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `EXCHANGE` variable
/// @return exchange_ The `EXCHANGE` variable value
function getExchange() external view returns (address exchange_) {
return EXCHANGE;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title Kyber Network interface
interface IKyberNetworkProxy {
function swapEtherToToken(address, uint256) external payable returns (uint256);
function swapTokenToEther(
address,
uint256,
uint256
) external returns (uint256);
function swapTokenToToken(
address,
uint256,
address,
uint256
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../release/utils/MathHelpers.sol";
import "../prices/CentralizedRateProvider.sol";
import "../utils/SwapperBase.sol";
contract MockKyberIntegratee is SwapperBase, Ownable, MathHelpers {
using SafeMath for uint256;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable WETH;
uint256 private constant PRECISION = 18;
// Deviation set in % defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address _centralizedRateProvider,
address _weth,
uint256 _blockNumberDeviation
) public {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
WETH = _weth;
blockNumberDeviation = _blockNumberDeviation;
}
function swapEtherToToken(address _destToken, uint256) external payable returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(WETH, msg.value, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, ETH_ADDRESS, msg.value, _destToken, destAmount);
return msg.value;
}
function swapTokenToEther(
address _srcToken,
uint256 _srcAmount,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, WETH, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, ETH_ADDRESS, destAmount);
return _srcAmount;
}
function swapTokenToToken(
address _srcToken,
uint256 _srcAmount,
address _destToken,
uint256
) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(_srcToken, _srcAmount, _destToken, blockNumberDeviation);
__swapAssets(msg.sender, _srcToken, _srcAmount, _destToken, destAmount);
return _srcAmount;
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
function getExpectedRate(
address _srcToken,
address _destToken,
uint256 _amount
) external returns (uint256 rate_, uint256 worstRate_) {
if (_srcToken == ETH_ADDRESS) {
_srcToken = WETH;
}
if (_destToken == ETH_ADDRESS) {
_destToken = WETH;
}
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(_srcToken, _amount, _destToken);
rate_ = __calcNormalizedRate(
ERC20(_srcToken).decimals(),
_amount,
ERC20(_destToken).decimals(),
destAmount
);
worstRate_ = rate_.mul(uint256(100).sub(blockNumberDeviation)).div(100);
}
///////////////////
// STATE GETTERS //
///////////////////
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getWeth() public view returns (address) {
return WETH;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/MockChainlinkPriceSource.sol";
/// @dev This price source offers two different options getting prices
/// The first one is getting a fixed rate, which can be useful for tests
/// The second approach calculates dinamically the rate making use of a chainlink price source
/// Mocks the functionality of the folllowing Synthetix contracts: { Exchanger, ExchangeRates }
contract MockSynthetixPriceSource is Ownable, ISynthetixExchangeRates {
using SafeMath for uint256;
mapping(bytes32 => uint256) private fixedRate;
mapping(bytes32 => AggregatorInfo) private currencyKeyToAggregator;
enum RateAsset {ETH, USD}
struct AggregatorInfo {
address aggregator;
RateAsset rateAsset;
}
constructor(address _ethUsdAggregator) public {
currencyKeyToAggregator[bytes32("ETH")] = AggregatorInfo({
aggregator: _ethUsdAggregator,
rateAsset: RateAsset.USD
});
}
function setPriceSourcesForCurrencyKeys(
bytes32[] calldata _currencyKeys,
address[] calldata _aggregators,
RateAsset[] calldata _rateAssets
) external onlyOwner {
require(
_currencyKeys.length == _aggregators.length &&
_rateAssets.length == _aggregators.length
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToAggregator[_currencyKeys[i]] = AggregatorInfo({
aggregator: _aggregators[i],
rateAsset: _rateAssets[i]
});
}
}
function setRate(bytes32 _currencyKey, uint256 _rate) external onlyOwner {
fixedRate[_currencyKey] = _rate;
}
/// @dev Calculates the rate from a currency key against USD
function rateAndInvalid(bytes32 _currencyKey)
external
view
override
returns (uint256 rate_, bool isInvalid_)
{
uint256 storedRate = getFixedRate(_currencyKey);
if (storedRate != 0) {
rate_ = storedRate;
} else {
AggregatorInfo memory aggregatorInfo = getAggregatorFromCurrencyKey(_currencyKey);
address aggregator = aggregatorInfo.aggregator;
if (aggregator == address(0)) {
rate_ = 0;
isInvalid_ = true;
return (rate_, isInvalid_);
}
uint256 decimals = MockChainlinkPriceSource(aggregator).decimals();
rate_ = uint256(MockChainlinkPriceSource(aggregator).latestAnswer()).mul(
10**(uint256(18).sub(decimals))
);
if (aggregatorInfo.rateAsset == RateAsset.ETH) {
uint256 ethToUsd = uint256(
MockChainlinkPriceSource(
getAggregatorFromCurrencyKey(bytes32("ETH"))
.aggregator
)
.latestAnswer()
);
rate_ = rate_.mul(ethToUsd).div(10**8);
}
}
isInvalid_ = (rate_ == 0);
return (rate_, isInvalid_);
}
///////////////////
// STATE GETTERS //
///////////////////
function getAggregatorFromCurrencyKey(bytes32 _currencyKey)
public
view
returns (AggregatorInfo memory _aggregator)
{
return currencyKeyToAggregator[_currencyKey];
}
function getFixedRate(bytes32 _currencyKey) public view returns (uint256) {
return fixedRate[_currencyKey];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
contract MockChainlinkPriceSource {
event AnswerUpdated(int256 indexed current, uint256 indexed roundId, uint256 timestamp);
uint256 public DECIMALS;
int256 public latestAnswer;
uint256 public latestTimestamp;
uint256 public roundId;
address public aggregator;
constructor(uint256 _decimals) public {
DECIMALS = _decimals;
latestAnswer = int256(10**_decimals);
latestTimestamp = now;
roundId = 1;
aggregator = address(this);
}
function setLatestAnswer(int256 _nextAnswer, uint256 _nextTimestamp) external {
latestAnswer = _nextAnswer;
latestTimestamp = _nextTimestamp;
roundId = roundId + 1;
emit AnswerUpdated(latestAnswer, roundId, latestTimestamp);
}
function setAggregator(address _nextAggregator) external {
aggregator = _nextAggregator;
}
function decimals() public view returns (uint256) {
return DECIMALS;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./../../release/interfaces/ISynthetixExchangeRates.sol";
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockSynthetixToken.sol";
/// @dev Synthetix Integratee. Mocks functionalities from the folllowing synthetix contracts
/// Synthetix, SynthetixAddressResolver, SynthetixDelegateApprovals
/// Link to contracts: <https://github.com/Synthetixio/synthetix/tree/develop/contracts>
contract MockSynthetixIntegratee is Ownable, MockToken {
using SafeMath for uint256;
mapping(address => mapping(address => bool)) private authorizerToDelegateToApproval;
mapping(bytes32 => address) private currencyKeyToSynth;
address private immutable CENTRALIZED_RATE_PROVIDER;
address private immutable EXCHANGE_RATES;
uint256 private immutable FEE;
uint256 private constant UNIT_FEE = 1000;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _centralizedRateProvider,
address _exchangeRates,
uint256 _fee
) public MockToken(_name, _symbol, _decimals) {
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
EXCHANGE_RATES = address(_exchangeRates);
FEE = _fee;
}
receive() external payable {}
function exchangeOnBehalfWithTracking(
address _exchangeForAddress,
bytes32 _srcCurrencyKey,
uint256 _srcAmount,
bytes32 _destinationCurrencyKey,
address,
bytes32
) external returns (uint256 amountReceived_) {
require(
canExchangeFor(_exchangeForAddress, msg.sender),
"exchangeOnBehalfWithTracking: Not approved to act on behalf"
);
amountReceived_ = __calculateAndSwap(
_exchangeForAddress,
_srcAmount,
_srcCurrencyKey,
_destinationCurrencyKey
);
return amountReceived_;
}
function getAmountsForExchange(
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
)
public
returns (
uint256 amountReceived_,
uint256 fee_,
uint256 exchangeFeeRate_
)
{
address srcToken = currencyKeyToSynth[_srcCurrencyKey];
address destToken = currencyKeyToSynth[_destCurrencyKey];
require(
currencyKeyToSynth[_srcCurrencyKey] != address(0) &&
currencyKeyToSynth[_destCurrencyKey] != address(0),
"getAmountsForExchange: Currency key doesn't have an associated synth"
);
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(srcToken, _srcAmount, destToken);
exchangeFeeRate_ = FEE;
amountReceived_ = destAmount.mul(UNIT_FEE.sub(exchangeFeeRate_)).div(UNIT_FEE);
fee_ = destAmount.sub(amountReceived_);
return (amountReceived_, fee_, exchangeFeeRate_);
}
function setSynthFromCurrencyKeys(bytes32[] calldata _currencyKeys, address[] calldata _synths)
external
{
require(
_currencyKeys.length == _synths.length,
"setSynthFromCurrencyKey: Unequal _currencyKeys and _synths lengths"
);
for (uint256 i = 0; i < _currencyKeys.length; i++) {
currencyKeyToSynth[_currencyKeys[i]] = _synths[i];
}
}
function approveExchangeOnBehalf(address _delegate) external {
authorizerToDelegateToApproval[msg.sender][_delegate] = true;
}
function __calculateAndSwap(
address _exchangeForAddress,
uint256 _srcAmount,
bytes32 _srcCurrencyKey,
bytes32 _destCurrencyKey
) private returns (uint256 amountReceived_) {
MockSynthetixToken srcSynth = MockSynthetixToken(currencyKeyToSynth[_srcCurrencyKey]);
MockSynthetixToken destSynth = MockSynthetixToken(currencyKeyToSynth[_destCurrencyKey]);
require(address(srcSynth) != address(0), "__calculateAndSwap: Source synth is not listed");
require(
address(destSynth) != address(0),
"__calculateAndSwap: Destination synth is not listed"
);
require(
!srcSynth.isLocked(_exchangeForAddress),
"__calculateAndSwap: Cannot settle during waiting period"
);
(amountReceived_, , ) = getAmountsForExchange(
_srcAmount,
_srcCurrencyKey,
_destCurrencyKey
);
srcSynth.burnFrom(_exchangeForAddress, _srcAmount);
destSynth.mintFor(_exchangeForAddress, amountReceived_);
destSynth.lock(_exchangeForAddress);
return amountReceived_;
}
function requireAndGetAddress(bytes32 _name, string calldata)
external
view
returns (address resolvedAddress_)
{
if (_name == "ExchangeRates") {
return EXCHANGE_RATES;
}
return address(this);
}
function settle(address, bytes32)
external
returns (
uint256,
uint256,
uint256
)
{}
///////////////////
// STATE GETTERS //
///////////////////
function canExchangeFor(address _authorizer, address _delegate)
public
view
returns (bool canExchange_)
{
return authorizerToDelegateToApproval[_authorizer][_delegate];
}
function getExchangeRates() public view returns (address exchangeRates_) {
return EXCHANGE_RATES;
}
function getFee() public view returns (uint256 fee_) {
return FEE;
}
function getSynthFromCurrencyKey(bytes32 _currencyKey) public view returns (address synth_) {
return currencyKeyToSynth[_currencyKey];
}
function getUnitFee() public pure returns (uint256 fee_) {
return UNIT_FEE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../prices/CentralizedRateProvider.sol";
import "./utils/SimpleMockIntegrateeBase.sol";
/// @dev Mocks the integration with `UniswapV2Router02` <https://uniswap.org/docs/v2/smart-contracts/router02/>
/// Additionally mocks the integration with `UniswapV2Factory` <https://uniswap.org/docs/v2/smart-contracts/factory/>
contract MockUniswapV2Integratee is SwapperBase, Ownable {
using SafeMath for uint256;
mapping(address => mapping(address => address)) private assetToAssetToPair;
address private immutable CENTRALIZED_RATE_PROVIDER;
uint256 private constant PRECISION = 18;
// Set in %, defines the MAX deviation per block from the mean rate
uint256 private blockNumberDeviation;
constructor(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair,
address _centralizedRateProvider,
uint256 _blockNumberDeviation
) public {
addPair(_listOfToken0, _listOfToken1, _listOfPair);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
blockNumberDeviation = _blockNumberDeviation;
}
/// @dev Adds the maximum possible value from {_amountADesired _amountBDesired}
/// Makes use of the value interpreter to perform those calculations
function addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired,
uint256,
uint256,
address,
uint256
)
external
returns (
uint256,
uint256,
uint256
)
{
__addLiquidity(_tokenA, _tokenB, _amountADesired, _amountBDesired);
}
/// @dev Removes the specified amount of liquidity
/// Returns 50% of the incoming liquidity value on each token.
function removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity,
uint256,
uint256,
address,
uint256
) public returns (uint256, uint256) {
__removeLiquidity(_tokenA, _tokenB, _liquidity);
}
function swapExactTokensForTokens(
uint256 amountIn,
uint256,
address[] calldata path,
address,
uint256
) external returns (uint256[] memory) {
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomized(path[0], amountIn, path[1], blockNumberDeviation);
__swapAssets(msg.sender, path[0], amountIn, path[path.length - 1], amountOut);
}
/// @dev We don't calculate any intermediate values here because they aren't actually used
/// Returns the randomized by sender value of the edge path assets
function getAmountsOut(uint256 _amountIn, address[] calldata _path)
external
returns (uint256[] memory amounts_)
{
require(_path.length >= 2, "getAmountsOut: path must be >= 2");
address assetIn = _path[0];
address assetOut = _path[_path.length - 1];
uint256 amountOut = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValueRandomizedBySender(assetIn, _amountIn, assetOut);
amounts_ = new uint256[](_path.length);
amounts_[0] = _amountIn;
amounts_[_path.length - 1] = amountOut;
return amounts_;
}
function addPair(
address[] memory _listOfToken0,
address[] memory _listOfToken1,
address[] memory _listOfPair
) public onlyOwner {
require(
_listOfPair.length == _listOfToken0.length,
"constructor: _listOfPair and _listOfToken0 have an unequal length"
);
require(
_listOfPair.length == _listOfToken1.length,
"constructor: _listOfPair and _listOfToken1 have an unequal length"
);
for (uint256 i; i < _listOfPair.length; i++) {
address token0 = _listOfToken0[i];
address token1 = _listOfToken1[i];
address pair = _listOfPair[i];
assetToAssetToPair[token0][token1] = pair;
assetToAssetToPair[token1][token0] = pair;
}
}
function setBlockNumberDeviation(uint256 _deviationPct) external onlyOwner {
blockNumberDeviation = _deviationPct;
}
// PRIVATE FUNCTIONS
/// Avoids stack-too-deep error.
function __addLiquidity(
address _tokenA,
address _tokenB,
uint256 _amountADesired,
uint256 _amountBDesired
) private {
address pair = getPair(_tokenA, _tokenB);
uint256 amountA;
uint256 amountB;
uint256 amountBFromA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenA, _amountADesired, _tokenB);
uint256 amountAFromB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(_tokenB, _amountBDesired, _tokenA);
if (amountBFromA >= _amountBDesired) {
amountA = amountAFromB;
amountB = _amountBDesired;
} else {
amountA = _amountADesired;
amountB = amountBFromA;
}
uint256 tokenPerLPToken = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, 10**uint256(PRECISION), _tokenA);
// Calculate the inverse rate to know the amount of LPToken to return from a unit of token
uint256 inverseRate = uint256(10**PRECISION).mul(10**PRECISION).div(tokenPerLPToken);
// Total liquidity can be calculated as 2x liquidity from amount A
uint256 totalLiquidity = uint256(2).mul(
amountA.mul(inverseRate).div(uint256(10**PRECISION))
);
require(
ERC20(pair).balanceOf(address(this)) >= totalLiquidity,
"__addLiquidity: Integratee doesn't have enough pair balance to cover the expected amount"
);
address[] memory assetsToIntegratee = new address[](2);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](2);
address[] memory assetsFromIntegratee = new address[](1);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](1);
assetsToIntegratee[0] = _tokenA;
assetsToIntegrateeAmounts[0] = amountA;
assetsToIntegratee[1] = _tokenB;
assetsToIntegrateeAmounts[1] = amountB;
assetsFromIntegratee[0] = pair;
assetsFromIntegrateeAmounts[0] = totalLiquidity;
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
/// Avoids stack-too-deep error.
function __removeLiquidity(
address _tokenA,
address _tokenB,
uint256 _liquidity
) private {
address pair = assetToAssetToPair[_tokenA][_tokenB];
require(pair != address(0), "__removeLiquidity: this pair doesn't exist");
uint256 amountA = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenA)
.div(uint256(2));
uint256 amountB = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(pair, _liquidity, _tokenB)
.div(uint256(2));
address[] memory assetsToIntegratee = new address[](1);
uint256[] memory assetsToIntegrateeAmounts = new uint256[](1);
address[] memory assetsFromIntegratee = new address[](2);
uint256[] memory assetsFromIntegrateeAmounts = new uint256[](2);
assetsToIntegratee[0] = pair;
assetsToIntegrateeAmounts[0] = _liquidity;
assetsFromIntegratee[0] = _tokenA;
assetsFromIntegrateeAmounts[0] = amountA;
assetsFromIntegratee[1] = _tokenB;
assetsFromIntegrateeAmounts[1] = amountB;
require(
ERC20(_tokenA).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenA balance to cover the expected amount"
);
require(
ERC20(_tokenB).balanceOf(address(this)) >= amountA,
"__removeLiquidity: Integratee doesn't have enough tokenB balance to cover the expected amount"
);
__swap(
msg.sender,
assetsToIntegratee,
assetsToIntegrateeAmounts,
assetsFromIntegratee,
assetsFromIntegrateeAmounts
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev By default set to address(0). It is read by UniswapV2PoolTokenValueCalculator: __calcPoolTokenValue
function feeTo() external pure returns (address) {
return address(0);
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
function getBlockNumberDeviation() public view returns (uint256) {
return blockNumberDeviation;
}
function getPrecision() public pure returns (uint256) {
return PRECISION;
}
function getPair(address _token0, address _token1) public view returns (address) {
return assetToAssetToPair[_token0][_token1];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockIntegrateeBase.sol";
abstract contract SimpleMockIntegrateeBase is MockIntegrateeBase {
constructor(
address[] memory _defaultRateAssets,
address[] memory _specialAssets,
uint8[] memory _specialAssetDecimals,
uint256 _ratePrecision
)
public
MockIntegrateeBase(
_defaultRateAssets,
_specialAssets,
_specialAssetDecimals,
_ratePrecision
)
{}
function __getRateAndSwapAssets(
address payable _trader,
address _srcToken,
uint256 _srcAmount,
address _destToken
) internal returns (uint256 destAmount_) {
uint256 actualRate = __getRate(_srcToken, _destToken);
__swapAssets(_trader, _srcToken, _srcAmount, _destToken, actualRate);
return actualRate;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "../../prices/CentralizedRateProvider.sol";
import "../../utils/SwapperBase.sol";
contract MockCTokenBase is ERC20, SwapperBase, Ownable {
address internal immutable TOKEN;
address internal immutable CENTRALIZED_RATE_PROVIDER;
uint256 internal rate;
mapping(address => mapping(address => uint256)) internal _allowances;
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
) public ERC20(_name, _symbol) {
_setupDecimals(_decimals);
TOKEN = _token;
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
rate = _initialRate;
}
function approve(address _spender, uint256 _amount) public virtual override returns (bool) {
_allowances[msg.sender][_spender] = _amount;
return true;
}
/// @dev Overriden `allowance` function, give the integratee infinite approval by default
function allowance(address _owner, address _spender) public view override returns (uint256) {
if (_spender == address(this) || _owner == _spender) {
return 2**256 - 1;
} else {
return _allowances[_owner][_spender];
}
}
/// @dev Necessary as this contract doesn't directly inherit from MockToken
function mintFor(address _who, uint256 _amount) external onlyOwner {
_mint(_who, _amount);
}
/// @dev Necessary to allow updates on persistent deployments (e.g Kovan)
function setRate(uint256 _rate) public onlyOwner {
rate = _rate;
}
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual override returns (bool) {
_transfer(_sender, _recipient, _amount);
return true;
}
// INTERNAL FUNCTIONS
/// @dev Calculates the cTokenAmount given a tokenAmount
/// Makes use of a inverse rate with the CentralizedRateProvider as a derivative can't be used as quoteAsset
function __calcCTokenAmount(uint256 _tokenAmount) internal returns (uint256 cTokenAmount_) {
uint256 tokenDecimals = ERC20(TOKEN).decimals();
uint256 cTokenDecimals = decimals();
// Result in Token Decimals
uint256 tokenPerCTokenUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(cTokenDecimals), TOKEN);
// Result in cToken decimals
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(cTokenDecimals)).div(
tokenPerCTokenUnit
);
// Amount in token decimals, result in cToken decimals
cTokenAmount_ = _tokenAmount.mul(inverseRate).div(10**tokenDecimals);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @dev Part of ICERC20 token interface
function underlying() public view returns (address) {
return TOKEN;
}
/// @dev Part of ICERC20 token interface.
/// Called from CompoundPriceFeed, returns the actual Rate cToken/Token
function exchangeRateStored() public view returns (uint256) {
return rate;
}
function getCentralizedRateProvider() public view returns (address) {
return CENTRALIZED_RATE_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCTokenIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _token,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _token, _centralizedRateProvider, _initialRate)
{}
function mint(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
TOKEN,
_amount,
address(this)
);
__swapAssets(msg.sender, TOKEN, _amount, address(this), destAmount);
return _amount;
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, TOKEN, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./MockCTokenBase.sol";
contract MockCEtherIntegratee is MockCTokenBase {
constructor(
string memory _name,
string memory _symbol,
uint8 _decimals,
address _weth,
address _centralizedRateProvider,
uint256 _initialRate
)
public
MockCTokenBase(_name, _symbol, _decimals, _weth, _centralizedRateProvider, _initialRate)
{}
function mint() external payable {
uint256 amount = msg.value;
uint256 destAmount = __calcCTokenAmount(amount);
__swapAssets(msg.sender, ETH_ADDRESS, amount, address(this), destAmount);
}
function redeem(uint256 _amount) external returns (uint256) {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_amount,
TOKEN
);
__swapAssets(msg.sender, address(this), _amount, ETH_ADDRESS, destAmount);
return _amount;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../../../interfaces/ICurveAddressProvider.sol";
import "../../../../interfaces/ICurveSwapsERC20.sol";
import "../../../../interfaces/ICurveSwapsEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CurveExchangeAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for swapping assets on Curve <https://www.curve.fi/>
contract CurveExchangeAdapter is AdapterBase {
address private constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
address private immutable ADDRESS_PROVIDER;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _addressProvider,
address _wethToken
) public AdapterBase(_integrationManager) {
ADDRESS_PROVIDER = _addressProvider;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH from swap and to unwrap WETH
receive() external payable {}
// EXTERNAL FUNCTIONS
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "CURVE_EXCHANGE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(_selector == TAKE_ORDER_SELECTOR, "parseAssetsForMethod: _selector invalid");
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
require(pool != address(0), "parseAssetsForMethod: No pool address provided");
spendAssets_ = new address[](1);
spendAssets_[0] = outgoingAsset;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = outgoingAssetAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = incomingAsset;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIncomingAssetAmount;
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Trades assets on Curve
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
function takeOrder(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata
) external onlyIntegrationManager {
(
address pool,
address outgoingAsset,
uint256 outgoingAssetAmount,
address incomingAsset,
uint256 minIncomingAssetAmount
) = __decodeCallArgs(_encodedCallArgs);
address swaps = ICurveAddressProvider(ADDRESS_PROVIDER).get_address(2);
__takeOrder(
_vaultProxy,
swaps,
pool,
outgoingAsset,
outgoingAssetAmount,
incomingAsset,
minIncomingAssetAmount
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the take order encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address pool_,
address outgoingAsset_,
uint256 outgoingAssetAmount_,
address incomingAsset_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, address, uint256, address, uint256));
}
/// @dev Helper to execute takeOrder. Avoids stack-too-deep error.
function __takeOrder(
address _vaultProxy,
address _swaps,
address _pool,
address _outgoingAsset,
uint256 _outgoingAssetAmount,
address _incomingAsset,
uint256 _minIncomingAssetAmount
) private {
if (_outgoingAsset == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(_outgoingAssetAmount);
ICurveSwapsEther(_swaps).exchange{value: _outgoingAssetAmount}(
_pool,
ETH_ADDRESS,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
} else if (_incomingAsset == WETH_TOKEN) {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
ETH_ADDRESS,
_outgoingAssetAmount,
_minIncomingAssetAmount,
address(this)
);
// wrap received ETH and send back to the vault
uint256 receivedAmount = payable(address(this)).balance;
IWETH(payable(WETH_TOKEN)).deposit{value: receivedAmount}();
ERC20(WETH_TOKEN).safeTransfer(_vaultProxy, receivedAmount);
} else {
__approveMaxAsNeeded(_outgoingAsset, _swaps, _outgoingAssetAmount);
ICurveSwapsERC20(_swaps).exchange(
_pool,
_outgoingAsset,
_incomingAsset,
_outgoingAssetAmount,
_minIncomingAssetAmount,
_vaultProxy
);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `ADDRESS_PROVIDER` variable
/// @return addressProvider_ The `ADDRESS_PROVIDER` variable value
function getAddressProvider() external view returns (address addressProvider_) {
return ADDRESS_PROVIDER;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsERC20 Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsERC20 {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title ICurveSwapsEther Interface
/// @author Enzyme Council <[email protected]>
interface ICurveSwapsEther {
function exchange(
address,
address,
address,
uint256,
uint256,
address
) external payable returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "../../IDerivativePriceFeed.sol";
import "./SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title PeggedDerivativesPriceFeedBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price feed base for multiple derivatives that are pegged 1:1 to their underlyings,
/// and have the same decimals as their underlying
abstract contract PeggedDerivativesPriceFeedBase is
IDerivativePriceFeed,
SingleUnderlyingDerivativeRegistryMixin
{
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address underlying = getUnderlyingForDerivative(_derivative);
require(underlying != address(0), "calcUnderlyingValues: Not a supported derivative");
underlyings_ = new address[](1);
underlyings_[0] = underlying;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount;
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return getUnderlyingForDerivative(_asset) != address(0);
}
/// @dev Provides validation that the derivative and underlying have the same decimals.
/// Can be overrode by the inheriting price feed using super() to implement further validation.
function __validateDerivative(address _derivative, address _underlying)
internal
virtual
override
{
require(
ERC20(_derivative).decimals() == ERC20(_underlying).decimals(),
"__validateDerivative: Unequal decimals"
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../utils/DispatcherOwnerMixin.sol";
/// @title SingleUnderlyingDerivativeRegistryMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice Mixin for derivative price feeds that handle multiple derivatives
/// that each have a single underlying asset
abstract contract SingleUnderlyingDerivativeRegistryMixin is DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address indexed underlying);
event DerivativeRemoved(address indexed derivative);
mapping(address => address) private derivativeToUnderlying;
constructor(address _dispatcher) public DispatcherOwnerMixin(_dispatcher) {}
/// @notice Adds derivatives with corresponding underlyings to the price feed
/// @param _derivatives The derivatives to add
/// @param _underlyings The corresponding underlyings to add
function addDerivatives(address[] memory _derivatives, address[] memory _underlyings)
external
virtual
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: Empty _derivatives");
require(_derivatives.length == _underlyings.length, "addDerivatives: Unequal arrays");
for (uint256 i; i < _derivatives.length; i++) {
require(_derivatives[i] != address(0), "addDerivatives: Empty derivative");
require(_underlyings[i] != address(0), "addDerivatives: Empty underlying");
require(
getUnderlyingForDerivative(_derivatives[i]) == address(0),
"addDerivatives: Value already set"
);
__validateDerivative(_derivatives[i], _underlyings[i]);
derivativeToUnderlying[_derivatives[i]] = _underlyings[i];
emit DerivativeAdded(_derivatives[i], _underlyings[i]);
}
}
/// @notice Removes derivatives from the price feed
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] memory _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: Empty _derivatives");
for (uint256 i; i < _derivatives.length; i++) {
require(
getUnderlyingForDerivative(_derivatives[i]) != address(0),
"removeDerivatives: Value not set"
);
delete derivativeToUnderlying[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @dev Optionally allow the inheriting price feed to validate the derivative-underlying pair
function __validateDerivative(address, address) internal virtual {
// UNIMPLEMENTED
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the underlying asset for a given derivative
/// @param _derivative The derivative for which to get the underlying asset
/// @return underlying_ The underlying asset
function getUnderlyingForDerivative(address _derivative)
public
view
returns (address underlying_)
{
return derivativeToUnderlying[_derivative];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/PeggedDerivativesPriceFeedBase.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of PeggedDerivativesPriceFeedBase
contract TestPeggedDerivativesPriceFeed is PeggedDerivativesPriceFeedBase {
constructor(address _dispatcher) public PeggedDerivativesPriceFeedBase(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../release/infrastructure/price-feeds/derivatives/feeds/utils/SingleUnderlyingDerivativeRegistryMixin.sol";
/// @title TestSingleUnderlyingDerivativeRegistry Contract
/// @author Enzyme Council <[email protected]>
/// @notice A test implementation of SingleUnderlyingDerivativeRegistryMixin
contract TestSingleUnderlyingDerivativeRegistry is SingleUnderlyingDerivativeRegistryMixin {
constructor(address _dispatcher) public SingleUnderlyingDerivativeRegistryMixin(_dispatcher) {}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAaveProtocolDataProvider.sol";
import "./utils/PeggedDerivativesPriceFeedBase.sol";
/// @title AavePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Aave
contract AavePriceFeed is PeggedDerivativesPriceFeedBase {
address private immutable PROTOCOL_DATA_PROVIDER;
constructor(address _dispatcher, address _protocolDataProvider)
public
PeggedDerivativesPriceFeedBase(_dispatcher)
{
PROTOCOL_DATA_PROVIDER = _protocolDataProvider;
}
function __validateDerivative(address _derivative, address _underlying) internal override {
super.__validateDerivative(_derivative, _underlying);
(address aTokenAddress, , ) = IAaveProtocolDataProvider(PROTOCOL_DATA_PROVIDER)
.getReserveTokensAddresses(_underlying);
require(
aTokenAddress == _derivative,
"__validateDerivative: Invalid aToken or token provided"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `PROTOCOL_DATA_PROVIDER` variable value
/// @return protocolDataProvider_ The `PROTOCOL_DATA_PROVIDER` variable value
function getProtocolDataProvider() external view returns (address protocolDataProvider_) {
return PROTOCOL_DATA_PROVIDER;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveProtocolDataProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveProtocolDataProvider {
function getReserveTokensAddresses(address)
external
view
returns (
address,
address,
address
);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/AavePriceFeed.sol";
import "../../../../interfaces/IAaveLendingPool.sol";
import "../../../../interfaces/IAaveLendingPoolAddressProvider.sol";
import "../utils/AdapterBase.sol";
/// @title AaveAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Aave Lending <https://aave.com/>
contract AaveAdapter is AdapterBase {
address private immutable AAVE_PRICE_FEED;
address private immutable LENDING_POOL_ADDRESS_PROVIDER;
uint16 private constant REFERRAL_CODE = 158;
constructor(
address _integrationManager,
address _lendingPoolAddressProvider,
address _aavePriceFeed
) public AdapterBase(_integrationManager) {
LENDING_POOL_ADDRESS_PROVIDER = _lendingPoolAddressProvider;
AAVE_PRICE_FEED = _aavePriceFeed;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "AAVE";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = aToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else if (_selector == REDEEM_SELECTOR) {
(address aToken, uint256 amount) = __decodeCallArgs(_encodedCallArgs);
// Prevent from invalid token/aToken combination
address token = AavePriceFeed(AAVE_PRICE_FEED).getUnderlyingForDerivative(aToken);
require(token != address(0), "parseAssetsForMethod: Unsupported aToken");
spendAssets_ = new address[](1);
spendAssets_[0] = aToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = amount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = amount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).deposit(
spendAssets[0],
spendAssetAmounts[0],
_vaultProxy,
REFERRAL_CODE
);
}
/// @notice Redeems an amount of aTokens from AAVE
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
) external onlyIntegrationManager {
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
address lendingPoolAddress = IAaveLendingPoolAddressProvider(LENDING_POOL_ADDRESS_PROVIDER)
.getLendingPool();
__approveMaxAsNeeded(spendAssets[0], lendingPoolAddress, spendAssetAmounts[0]);
IAaveLendingPool(lendingPoolAddress).withdraw(
incomingAssets[0],
spendAssetAmounts[0],
_vaultProxy
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address aToken, uint256 amount)
{
return abi.decode(_encodedCallArgs, (address, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `AAVE_PRICE_FEED` variable
/// @return aavePriceFeed_ The `AAVE_PRICE_FEED` variable value
function getAavePriceFeed() external view returns (address aavePriceFeed_) {
return AAVE_PRICE_FEED;
}
/// @notice Gets the `LENDING_POOL_ADDRESS_PROVIDER` variable
/// @return lendingPoolAddressProvider_ The `LENDING_POOL_ADDRESS_PROVIDER` variable value
function getLendingPoolAddressProvider()
external
view
returns (address lendingPoolAddressProvider_)
{
return LENDING_POOL_ADDRESS_PROVIDER;
}
/// @notice Gets the `REFERRAL_CODE` variable
/// @return referralCode_ The `REFERRAL_CODE` variable value
function getReferralCode() external pure returns (uint16 referralCode_) {
return REFERRAL_CODE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPool interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPool {
function deposit(
address,
uint256,
address,
uint16
) external;
function withdraw(
address,
uint256,
address
) external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAaveLendingPoolAddressProvider interface
/// @author Enzyme Council <[email protected]>
interface IAaveLendingPoolAddressProvider {
function getLendingPool() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of assets in a fund's holdings
contract AssetWhitelist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Non-whitelisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Must whitelist denominationAsset"
);
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (!isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
/// @title AddressListPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice An abstract mixin contract for policies that use an address list
abstract contract AddressListPolicyMixin {
using EnumerableSet for EnumerableSet.AddressSet;
event AddressesAdded(address indexed comptrollerProxy, address[] items);
event AddressesRemoved(address indexed comptrollerProxy, address[] items);
mapping(address => EnumerableSet.AddressSet) private comptrollerProxyToList;
// EXTERNAL FUNCTIONS
/// @notice Get all addresses in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @return list_ The addresses in the fund's list
function getList(address _comptrollerProxy) external view returns (address[] memory list_) {
list_ = new address[](comptrollerProxyToList[_comptrollerProxy].length());
for (uint256 i = 0; i < list_.length; i++) {
list_[i] = comptrollerProxyToList[_comptrollerProxy].at(i);
}
return list_;
}
// PUBLIC FUNCTIONS
/// @notice Check if an address is in a fund's list
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _item The address to check against the list
/// @return isInList_ True if the address is in the list
function isInList(address _comptrollerProxy, address _item)
public
view
returns (bool isInList_)
{
return comptrollerProxyToList[_comptrollerProxy].contains(_item);
}
// INTERNAL FUNCTIONS
/// @dev Helper to add addresses to the calling fund's list
function __addToList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__addToList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].add(_items[i]),
"__addToList: Address already exists in list"
);
}
emit AddressesAdded(_comptrollerProxy, _items);
}
/// @dev Helper to remove addresses from the calling fund's list
function __removeFromList(address _comptrollerProxy, address[] memory _items) internal {
require(_items.length > 0, "__removeFromList: No addresses provided");
for (uint256 i = 0; i < _items.length; i++) {
require(
comptrollerProxyToList[_comptrollerProxy].remove(_items[i]),
"__removeFromList: Address does not exist in list"
);
}
emit AddressesRemoved(_comptrollerProxy, _items);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/comptroller/ComptrollerLib.sol";
import "../../../../core/fund/vault/VaultLib.sol";
import "../../../../utils/AddressArrayLib.sol";
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PostCallOnIntegrationValidatePolicyBase.sol";
/// @title AssetBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of assets in a fund's holdings
contract AssetBlacklist is PostCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
using AddressArrayLib for address[];
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Validates and initializes a policy as necessary prior to fund activation
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _vaultProxy The fund's VaultProxy address
function activateForFund(address _comptrollerProxy, address _vaultProxy)
external
override
onlyPolicyManager
{
require(
passesRule(_comptrollerProxy, VaultLib(_vaultProxy).getTrackedAssets()),
"activateForFund: Blacklisted asset detected"
);
}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
address[] memory assets = abi.decode(_encodedSettings, (address[]));
require(
!assets.contains(ComptrollerLib(_comptrollerProxy).getDenominationAsset()),
"addFundSettings: Cannot blacklist denominationAsset"
);
__addToList(_comptrollerProxy, assets);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ASSET_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _assets The assets with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address[] memory _assets)
public
view
returns (bool isValid_)
{
for (uint256 i; i < _assets.length; i++) {
if (isInList(_comptrollerProxy, _assets[i])) {
return false;
}
}
return true;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, , address[] memory incomingAssets, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, incomingAssets);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of adapters for use by a fund
contract AdapterWhitelist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_WHITELIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title CallOnIntegrationPreValidatePolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreCallOnIntegration policy hook
abstract contract PreCallOnIntegrationValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreCallOnIntegration;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedRuleArgs)
internal
pure
returns (address adapter_, bytes4 selector_)
{
return abi.decode(_encodedRuleArgs, (address, bytes4));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../utils/FundDeployerOwnerMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title GuaranteedRedemption Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that guarantees that shares will either be continuously redeemable or
/// redeemable within a predictable daily window by preventing trading during a configurable daily period
contract GuaranteedRedemption is PreCallOnIntegrationValidatePolicyBase, FundDeployerOwnerMixin {
using SafeMath for uint256;
event AdapterAdded(address adapter);
event AdapterRemoved(address adapter);
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 startTimestamp,
uint256 duration
);
event RedemptionWindowBufferSet(uint256 prevBuffer, uint256 nextBuffer);
struct RedemptionWindow {
uint256 startTimestamp;
uint256 duration;
}
uint256 private constant ONE_DAY = 24 * 60 * 60;
mapping(address => bool) private adapterToCanBlockRedemption;
mapping(address => RedemptionWindow) private comptrollerProxyToRedemptionWindow;
uint256 private redemptionWindowBuffer;
constructor(
address _policyManager,
address _fundDeployer,
uint256 _redemptionWindowBuffer,
address[] memory _redemptionBlockingAdapters
) public PolicyBase(_policyManager) FundDeployerOwnerMixin(_fundDeployer) {
redemptionWindowBuffer = _redemptionWindowBuffer;
__addRedemptionBlockingAdapters(_redemptionBlockingAdapters);
}
// EXTERNAL FUNCTIONS
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
(uint256 startTimestamp, uint256 duration) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
if (startTimestamp == 0) {
require(duration == 0, "addFundSettings: duration must be 0 if startTimestamp is 0");
return;
}
// Use 23 hours instead of 1 day to allow up to 1 hr of redemptionWindowBuffer
require(
duration > 0 && duration <= 23 hours,
"addFundSettings: duration must be between 1 second and 23 hours"
);
comptrollerProxyToRedemptionWindow[_comptrollerProxy].startTimestamp = startTimestamp;
comptrollerProxyToRedemptionWindow[_comptrollerProxy].duration = duration;
emit FundSettingsSet(_comptrollerProxy, startTimestamp, duration);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "GUARANTEED_REDEMPTION";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
if (!adapterCanBlockRedemption(_adapter)) {
return true;
}
RedemptionWindow memory redemptionWindow
= comptrollerProxyToRedemptionWindow[_comptrollerProxy];
// If no RedemptionWindow is set, the fund can never use redemption-blocking adapters
if (redemptionWindow.startTimestamp == 0) {
return false;
}
uint256 latestRedemptionWindowStart = calcLatestRedemptionWindowStart(
redemptionWindow.startTimestamp
);
// A fund can't trade during its redemption window, nor in the buffer beforehand.
// The lower bound is only relevant when the startTimestamp is in the future,
// so we check it last.
if (
block.timestamp >= latestRedemptionWindowStart.add(redemptionWindow.duration) ||
block.timestamp <= latestRedemptionWindowStart.sub(redemptionWindowBuffer)
) {
return true;
}
return false;
}
/// @notice Sets a new value for the redemptionWindowBuffer variable
/// @param _nextRedemptionWindowBuffer The number of seconds for the redemptionWindowBuffer
/// @dev The redemptionWindowBuffer is added to the beginning of the redemption window,
/// and should always be >= the longest potential block on redemption amongst all adapters.
/// (e.g., Synthetix blocks token transfers during a timelock after trading synths)
function setRedemptionWindowBuffer(uint256 _nextRedemptionWindowBuffer)
external
onlyFundDeployerOwner
{
uint256 prevRedemptionWindowBuffer = redemptionWindowBuffer;
require(
_nextRedemptionWindowBuffer != prevRedemptionWindowBuffer,
"setRedemptionWindowBuffer: Value already set"
);
redemptionWindowBuffer = _nextRedemptionWindowBuffer;
emit RedemptionWindowBufferSet(prevRedemptionWindowBuffer, _nextRedemptionWindowBuffer);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
// PUBLIC FUNCTIONS
/// @notice Calculates the start of the most recent redemption window
/// @param _startTimestamp The initial startTimestamp for the redemption window
/// @return latestRedemptionWindowStart_ The starting timestamp of the most recent redemption window
function calcLatestRedemptionWindowStart(uint256 _startTimestamp)
public
view
returns (uint256 latestRedemptionWindowStart_)
{
if (block.timestamp <= _startTimestamp) {
return _startTimestamp;
}
uint256 timeSinceStartTimestamp = block.timestamp.sub(_startTimestamp);
uint256 timeSincePeriodStart = timeSinceStartTimestamp.mod(ONE_DAY);
return block.timestamp.sub(timeSincePeriodStart);
}
///////////////////////////////////////////
// REDEMPTION-BLOCKING ADAPTERS REGISTRY //
///////////////////////////////////////////
/// @notice Add adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be added
function addRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"__addRedemptionBlockingAdapters: _adapters cannot be empty"
);
__addRedemptionBlockingAdapters(_adapters);
}
/// @notice Remove adapters which can block shares redemption
/// @param _adapters The addresses of adapters to be removed
function removeRedemptionBlockingAdapters(address[] calldata _adapters)
external
onlyFundDeployerOwner
{
require(
_adapters.length > 0,
"removeRedemptionBlockingAdapters: _adapters cannot be empty"
);
for (uint256 i; i < _adapters.length; i++) {
require(
adapterCanBlockRedemption(_adapters[i]),
"removeRedemptionBlockingAdapters: adapter is not added"
);
adapterToCanBlockRedemption[_adapters[i]] = false;
emit AdapterRemoved(_adapters[i]);
}
}
/// @dev Helper to mark adapters that can block shares redemption
function __addRedemptionBlockingAdapters(address[] memory _adapters) private {
for (uint256 i; i < _adapters.length; i++) {
require(
_adapters[i] != address(0),
"__addRedemptionBlockingAdapters: adapter cannot be empty"
);
require(
!adapterCanBlockRedemption(_adapters[i]),
"__addRedemptionBlockingAdapters: adapter already added"
);
adapterToCanBlockRedemption[_adapters[i]] = true;
emit AdapterAdded(_adapters[i]);
}
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `redemptionWindowBuffer` variable
/// @return redemptionWindowBuffer_ The `redemptionWindowBuffer` variable value
function getRedemptionWindowBuffer() external view returns (uint256 redemptionWindowBuffer_) {
return redemptionWindowBuffer;
}
/// @notice Gets the RedemptionWindow settings for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return redemptionWindow_ The RedemptionWindow settings
function getRedemptionWindowForFund(address _comptrollerProxy)
external
view
returns (RedemptionWindow memory redemptionWindow_)
{
return comptrollerProxyToRedemptionWindow[_comptrollerProxy];
}
/// @notice Checks whether an adapter can block shares redemption
/// @param _adapter The address of the adapter to check
/// @return canBlockRedemption_ True if the adapter can block shares redemption
function adapterCanBlockRedemption(address _adapter)
public
view
returns (bool canBlockRedemption_)
{
return adapterToCanBlockRedemption[_adapter];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreCallOnIntegrationValidatePolicyBase.sol";
/// @title AdapterBlacklist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that disallows a configurable blacklist of adapters from use by a fund
contract AdapterBlacklist is PreCallOnIntegrationValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Add the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__addToList(_comptrollerProxy, abi.decode(_encodedSettings, (address[])));
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "ADAPTER_BLACKLIST";
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _adapter The adapter with which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _adapter)
public
view
returns (bool isValid_)
{
return !isInList(_comptrollerProxy, _adapter);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address adapter, ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, adapter);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title InvestorWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of investors to buy shares in a fund
contract InvestorWhitelist is PreBuySharesValidatePolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "INVESTOR_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investor The investor for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _investor)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _investor);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address buyer, , , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, buyer);
}
/// @dev Helper to update the investor whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesPolicyMixin Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the PreBuyShares policy hook
abstract contract PreBuySharesValidatePolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.PreBuyShares;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address buyer_,
uint256 investmentAmount_,
uint256 minSharesQuantity_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256, uint256, uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./utils/PreBuySharesValidatePolicyBase.sol";
/// @title MinMaxInvestment Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that restricts the amount of the fund's denomination asset that a user can
/// send in a single call to buy shares in a fund
contract MinMaxInvestment is PreBuySharesValidatePolicyBase {
event FundSettingsSet(
address indexed comptrollerProxy,
uint256 minInvestmentAmount,
uint256 maxInvestmentAmount
);
struct FundSettings {
uint256 minInvestmentAmount;
uint256 maxInvestmentAmount;
}
mapping(address => FundSettings) private comptrollerProxyToFundSettings;
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "MIN_MAX_INVESTMENT";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__setFundSettings(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _investmentAmount The investment amount for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, uint256 _investmentAmount)
public
view
returns (bool isValid_)
{
uint256 minInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount;
uint256 maxInvestmentAmount = comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount;
// Both minInvestmentAmount and maxInvestmentAmount can be 0 in order to close the fund
// temporarily
if (minInvestmentAmount == 0) {
return _investmentAmount <= maxInvestmentAmount;
} else if (maxInvestmentAmount == 0) {
return _investmentAmount >= minInvestmentAmount;
}
return
_investmentAmount >= minInvestmentAmount && _investmentAmount <= maxInvestmentAmount;
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(, uint256 investmentAmount, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, investmentAmount);
}
/// @dev Helper to set the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function __setFundSettings(address _comptrollerProxy, bytes memory _encodedSettings) private {
(uint256 minInvestmentAmount, uint256 maxInvestmentAmount) = abi.decode(
_encodedSettings,
(uint256, uint256)
);
require(
maxInvestmentAmount == 0 || minInvestmentAmount < maxInvestmentAmount,
"__setFundSettings: minInvestmentAmount must be less than maxInvestmentAmount"
);
comptrollerProxyToFundSettings[_comptrollerProxy]
.minInvestmentAmount = minInvestmentAmount;
comptrollerProxyToFundSettings[_comptrollerProxy]
.maxInvestmentAmount = maxInvestmentAmount;
emit FundSettingsSet(_comptrollerProxy, minInvestmentAmount, maxInvestmentAmount);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the min and max investment amount for a given fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @return fundSettings_ The fund settings
function getFundSettings(address _comptrollerProxy)
external
view
returns (FundSettings memory fundSettings_)
{
return comptrollerProxyToFundSettings[_comptrollerProxy];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/AddressListPolicyMixin.sol";
import "./utils/BuySharesSetupPolicyBase.sol";
/// @title BuySharesCallerWhitelist Contract
/// @author Enzyme Council <[email protected]>
/// @notice A policy that only allows a configurable whitelist of buyShares callers for a fund
contract BuySharesCallerWhitelist is BuySharesSetupPolicyBase, AddressListPolicyMixin {
constructor(address _policyManager) public PolicyBase(_policyManager) {}
/// @notice Adds the initial policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _encodedSettings)
external
override
onlyPolicyManager
{
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Provides a constant string identifier for a policy
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "BUY_SHARES_CALLER_WHITELIST";
}
/// @notice Updates the policy settings for a fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedSettings Encoded settings to apply to a fund
function updateFundSettings(
address _comptrollerProxy,
address,
bytes calldata _encodedSettings
) external override onlyPolicyManager {
__updateList(_comptrollerProxy, _encodedSettings);
}
/// @notice Checks whether a particular condition passes the rule for a particular fund
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _buySharesCaller The buyShares caller for which to check the rule
/// @return isValid_ True if the rule passes
function passesRule(address _comptrollerProxy, address _buySharesCaller)
public
view
returns (bool isValid_)
{
return isInList(_comptrollerProxy, _buySharesCaller);
}
/// @notice Apply the rule with the specified parameters of a PolicyHook
/// @param _comptrollerProxy The fund's ComptrollerProxy address
/// @param _encodedArgs Encoded args with which to validate the rule
/// @return isValid_ True if the rule passes
function validateRule(
address _comptrollerProxy,
address,
IPolicyManager.PolicyHook,
bytes calldata _encodedArgs
) external override returns (bool isValid_) {
(address caller, , ) = __decodeRuleArgs(_encodedArgs);
return passesRule(_comptrollerProxy, caller);
}
/// @dev Helper to update the whitelist by adding and/or removing addresses
function __updateList(address _comptrollerProxy, bytes memory _settingsData) private {
(address[] memory itemsToAdd, address[] memory itemsToRemove) = abi.decode(
_settingsData,
(address[], address[])
);
// If an address is in both add and remove arrays, they will not be in the final list.
// We do not check for uniqueness between the two arrays for efficiency.
if (itemsToAdd.length > 0) {
__addToList(_comptrollerProxy, itemsToAdd);
}
if (itemsToRemove.length > 0) {
__removeFromList(_comptrollerProxy, itemsToRemove);
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/PolicyBase.sol";
/// @title BuySharesSetupPolicyBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mixin contract for policies that only implement the BuySharesSetup policy hook
abstract contract BuySharesSetupPolicyBase is PolicyBase {
/// @notice Gets the implemented PolicyHooks for a policy
/// @return implementedHooks_ The implemented PolicyHooks
function implementedHooks()
external
view
override
returns (IPolicyManager.PolicyHook[] memory implementedHooks_)
{
implementedHooks_ = new IPolicyManager.PolicyHook[](1);
implementedHooks_[0] = IPolicyManager.PolicyHook.BuySharesSetup;
return implementedHooks_;
}
/// @notice Helper to decode rule arguments
function __decodeRuleArgs(bytes memory _encodedArgs)
internal
pure
returns (
address caller_,
uint256[] memory investmentAmounts_,
uint256 gav_
)
{
return abi.decode(_encodedArgs, (address, uint256[], uint256));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../core/fund/vault/VaultLib.sol";
import "../utils/AdapterBase.sol";
/// @title TrackedAssetsAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter to add tracked assets to a fund (useful e.g. to handle token airdrops)
contract TrackedAssetsAdapter is AdapterBase {
constructor(address _integrationManager) public AdapterBase(_integrationManager) {}
/// @notice Add multiple assets to the Vault's list of tracked assets
/// @dev No need to perform any validation or implement any logic
function addTrackedAssets(
address,
bytes calldata,
bytes calldata
) external view {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ The identifer string
function identifier() external pure override returns (string memory identifier_) {
return "TRACKED_ASSETS";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
require(
_selector == ADD_TRACKED_ASSETS_SELECTOR,
"parseAssetsForMethod: _selector invalid"
);
incomingAssets_ = __decodeCallArgs(_encodedCallArgs);
minIncomingAssetAmounts_ = new uint256[](incomingAssets_.length);
for (uint256 i; i < minIncomingAssetAmounts_.length; i++) {
minIncomingAssetAmounts_[i] = 1;
}
return (
spendAssetsHandleType_,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (address[] memory incomingAssets_)
{
return abi.decode(_encodedCallArgs, (address[]));
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/ProxiableVaultLib.sol";
/// @title VaultProxy Contract
/// @author Enzyme Council <[email protected]>
/// @notice A proxy contract for all VaultProxy instances, slightly modified from EIP-1822
/// @dev Adapted from the recommended implementation of a Proxy in EIP-1822, updated for solc 0.6.12,
/// and using the EIP-1967 storage slot for the proxiable implementation.
/// i.e., `bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)`, which is
/// "0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
/// See: https://eips.ethereum.org/EIPS/eip-1822
contract VaultProxy {
constructor(bytes memory _constructData, address _vaultLib) public {
// "0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5" corresponds to
// `bytes32(keccak256('mln.proxiable.vaultlib'))`
require(
bytes32(0x027b9570e9fedc1a80b937ae9a06861e5faef3992491af30b684a64b3fbec7a5) ==
ProxiableVaultLib(_vaultLib).proxiableUUID(),
"constructor: _vaultLib not compatible"
);
assembly {
// solium-disable-line
sstore(0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, _vaultLib)
}
(bool success, bytes memory returnData) = _vaultLib.delegatecall(_constructData); // solium-disable-line
require(success, string(returnData));
}
fallback() external payable {
assembly {
// solium-disable-line
let contractLogic := sload(
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc
)
calldatacopy(0x0, 0x0, calldatasize())
let success := delegatecall(
sub(gas(), 10000),
contractLogic,
0x0,
calldatasize(),
0,
0
)
let retSz := returndatasize()
returndatacopy(0, 0, retSz)
switch success
case 0 {
revert(0, retSz)
}
default {
return(0, retSz)
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/IMigrationHookHandler.sol";
import "../utils/IMigratableVault.sol";
import "../vault/VaultProxy.sol";
import "./IDispatcher.sol";
/// @title Dispatcher Contract
/// @author Enzyme Council <[email protected]>
/// @notice The top-level contract linking multiple releases.
/// It handles the deployment of new VaultProxy instances,
/// and the regulation of fund migration from a previous release to the current one.
/// It can also be referred to for access-control based on this contract's owner.
/// @dev DO NOT EDIT CONTRACT
contract Dispatcher is IDispatcher {
event CurrentFundDeployerSet(address prevFundDeployer, address nextFundDeployer);
event MigrationCancelled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationExecuted(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationSignaled(
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib,
uint256 executableTimestamp
);
event MigrationTimelockSet(uint256 prevTimelock, uint256 nextTimelock);
event NominatedOwnerSet(address indexed nominatedOwner);
event NominatedOwnerRemoved(address indexed nominatedOwner);
event OwnershipTransferred(address indexed prevOwner, address indexed nextOwner);
event MigrationInCancelHookFailed(
bytes failureReturnData,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event MigrationOutHookFailed(
bytes failureReturnData,
IMigrationHookHandler.MigrationOutHook hook,
address indexed vaultProxy,
address indexed prevFundDeployer,
address indexed nextFundDeployer,
address nextVaultAccessor,
address nextVaultLib
);
event SharesTokenSymbolSet(string _nextSymbol);
event VaultProxyDeployed(
address indexed fundDeployer,
address indexed owner,
address vaultProxy,
address indexed vaultLib,
address vaultAccessor,
string fundName
);
struct MigrationRequest {
address nextFundDeployer;
address nextVaultAccessor;
address nextVaultLib;
uint256 executableTimestamp;
}
address private currentFundDeployer;
address private nominatedOwner;
address private owner;
uint256 private migrationTimelock;
string private sharesTokenSymbol;
mapping(address => address) private vaultProxyToFundDeployer;
mapping(address => MigrationRequest) private vaultProxyToMigrationRequest;
modifier onlyCurrentFundDeployer() {
require(
msg.sender == currentFundDeployer,
"Only the current FundDeployer can call this function"
);
_;
}
modifier onlyOwner() {
require(msg.sender == owner, "Only the contract owner can call this function");
_;
}
constructor() public {
migrationTimelock = 2 days;
owner = msg.sender;
sharesTokenSymbol = "ENZF";
}
/////////////
// GENERAL //
/////////////
/// @notice Sets a new `symbol` value for VaultProxy instances
/// @param _nextSymbol The symbol value to set
function setSharesTokenSymbol(string calldata _nextSymbol) external override onlyOwner {
sharesTokenSymbol = _nextSymbol;
emit SharesTokenSymbolSet(_nextSymbol);
}
////////////////////
// ACCESS CONTROL //
////////////////////
/// @notice Claim ownership of the contract
function claimOwnership() external override {
address nextOwner = nominatedOwner;
require(
msg.sender == nextOwner,
"claimOwnership: Only the nominatedOwner can call this function"
);
delete nominatedOwner;
address prevOwner = owner;
owner = nextOwner;
emit OwnershipTransferred(prevOwner, nextOwner);
}
/// @notice Revoke the nomination of a new contract owner
function removeNominatedOwner() external override onlyOwner {
address removedNominatedOwner = nominatedOwner;
require(
removedNominatedOwner != address(0),
"removeNominatedOwner: There is no nominated owner"
);
delete nominatedOwner;
emit NominatedOwnerRemoved(removedNominatedOwner);
}
/// @notice Set a new FundDeployer for use within the contract
/// @param _nextFundDeployer The address of the FundDeployer contract
function setCurrentFundDeployer(address _nextFundDeployer) external override onlyOwner {
require(
_nextFundDeployer != address(0),
"setCurrentFundDeployer: _nextFundDeployer cannot be empty"
);
require(
__isContract(_nextFundDeployer),
"setCurrentFundDeployer: Non-contract _nextFundDeployer"
);
address prevFundDeployer = currentFundDeployer;
require(
_nextFundDeployer != prevFundDeployer,
"setCurrentFundDeployer: _nextFundDeployer is already currentFundDeployer"
);
currentFundDeployer = _nextFundDeployer;
emit CurrentFundDeployerSet(prevFundDeployer, _nextFundDeployer);
}
/// @notice Nominate a new contract owner
/// @param _nextNominatedOwner The account to nominate
/// @dev Does not prohibit overwriting the current nominatedOwner
function setNominatedOwner(address _nextNominatedOwner) external override onlyOwner {
require(
_nextNominatedOwner != address(0),
"setNominatedOwner: _nextNominatedOwner cannot be empty"
);
require(
_nextNominatedOwner != owner,
"setNominatedOwner: _nextNominatedOwner is already the owner"
);
require(
_nextNominatedOwner != nominatedOwner,
"setNominatedOwner: _nextNominatedOwner is already nominated"
);
nominatedOwner = _nextNominatedOwner;
emit NominatedOwnerSet(_nextNominatedOwner);
}
/// @dev Helper to check whether an address is a deployed contract
function __isContract(address _who) private view returns (bool isContract_) {
uint256 size;
assembly {
size := extcodesize(_who)
}
return size > 0;
}
////////////////
// DEPLOYMENT //
////////////////
/// @notice Deploys a VaultProxy
/// @param _vaultLib The VaultLib library with which to instantiate the VaultProxy
/// @param _owner The account to set as the VaultProxy's owner
/// @param _vaultAccessor The account to set as the VaultProxy's permissioned accessor
/// @param _fundName The name of the fund
/// @dev Input validation should be handled by the VaultProxy during deployment
function deployVaultProxy(
address _vaultLib,
address _owner,
address _vaultAccessor,
string calldata _fundName
) external override onlyCurrentFundDeployer returns (address vaultProxy_) {
require(__isContract(_vaultAccessor), "deployVaultProxy: Non-contract _vaultAccessor");
bytes memory constructData = abi.encodeWithSelector(
IMigratableVault.init.selector,
_owner,
_vaultAccessor,
_fundName
);
vaultProxy_ = address(new VaultProxy(constructData, _vaultLib));
address fundDeployer = msg.sender;
vaultProxyToFundDeployer[vaultProxy_] = fundDeployer;
emit VaultProxyDeployed(
fundDeployer,
_owner,
vaultProxy_,
_vaultLib,
_vaultAccessor,
_fundName
);
return vaultProxy_;
}
////////////////
// MIGRATIONS //
////////////////
/// @notice Cancels a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to cancel the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
/// @dev Because this function must also be callable by a permissioned migrator, it has an
/// extra migration hook to the nextFundDeployer for the case where cancelMigration()
/// is called directly (rather than via the nextFundDeployer).
function cancelMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(nextFundDeployer != address(0), "cancelMigration: No migration request exists");
// TODO: confirm that if canMigrate() does not exist but the caller is a valid FundDeployer, this still works.
require(
msg.sender == nextFundDeployer || IMigratableVault(_vaultProxy).canMigrate(msg.sender),
"cancelMigration: Not an allowed caller"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
uint256 executableTimestamp = request.executableTimestamp;
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostCancel,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
__invokeMigrationInCancelHook(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationCancelled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Executes a pending migration request
/// @param _vaultProxy The VaultProxy contract for which to execute the migration request
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function executeMigration(address _vaultProxy, bool _bypassFailure) external override {
MigrationRequest memory request = vaultProxyToMigrationRequest[_vaultProxy];
address nextFundDeployer = request.nextFundDeployer;
require(
nextFundDeployer != address(0),
"executeMigration: No migration request exists for _vaultProxy"
);
require(
msg.sender == nextFundDeployer,
"executeMigration: Only the target FundDeployer can call this function"
);
require(
nextFundDeployer == currentFundDeployer,
"executeMigration: The target FundDeployer is no longer the current FundDeployer"
);
uint256 executableTimestamp = request.executableTimestamp;
require(
block.timestamp >= executableTimestamp,
"executeMigration: The migration timelock has not elapsed"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
address nextVaultAccessor = request.nextVaultAccessor;
address nextVaultLib = request.nextVaultLib;
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
// Upgrade the VaultProxy to a new VaultLib and update the accessor via the new VaultLib
IMigratableVault(_vaultProxy).setVaultLib(nextVaultLib);
IMigratableVault(_vaultProxy).setAccessor(nextVaultAccessor);
// Update the FundDeployer that migrated the VaultProxy
vaultProxyToFundDeployer[_vaultProxy] = nextFundDeployer;
// Remove the migration request
delete vaultProxyToMigrationRequest[_vaultProxy];
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostMigrate,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
_bypassFailure
);
emit MigrationExecuted(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
nextVaultAccessor,
nextVaultLib,
executableTimestamp
);
}
/// @notice Sets a new migration timelock
/// @param _nextTimelock The number of seconds for the new timelock
function setMigrationTimelock(uint256 _nextTimelock) external override onlyOwner {
uint256 prevTimelock = migrationTimelock;
require(
_nextTimelock != prevTimelock,
"setMigrationTimelock: _nextTimelock is the current timelock"
);
migrationTimelock = _nextTimelock;
emit MigrationTimelockSet(prevTimelock, _nextTimelock);
}
/// @notice Signals a migration by creating a migration request
/// @param _vaultProxy The VaultProxy contract for which to signal migration
/// @param _nextVaultAccessor The account that will be the next `accessor` on the VaultProxy
/// @param _nextVaultLib The next VaultLib library contract address to set on the VaultProxy
/// @param _bypassFailure True if a failure in either migration hook should be ignored
function signalMigration(
address _vaultProxy,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) external override onlyCurrentFundDeployer {
require(
__isContract(_nextVaultAccessor),
"signalMigration: Non-contract _nextVaultAccessor"
);
address prevFundDeployer = vaultProxyToFundDeployer[_vaultProxy];
require(prevFundDeployer != address(0), "signalMigration: _vaultProxy does not exist");
address nextFundDeployer = msg.sender;
require(
nextFundDeployer != prevFundDeployer,
"signalMigration: Can only migrate to a new FundDeployer"
);
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PreSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
uint256 executableTimestamp = block.timestamp + migrationTimelock;
vaultProxyToMigrationRequest[_vaultProxy] = MigrationRequest({
nextFundDeployer: nextFundDeployer,
nextVaultAccessor: _nextVaultAccessor,
nextVaultLib: _nextVaultLib,
executableTimestamp: executableTimestamp
});
__invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook.PostSignal,
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
_bypassFailure
);
emit MigrationSignaled(
_vaultProxy,
prevFundDeployer,
nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib,
executableTimestamp
);
}
/// @dev Helper to invoke a MigrationInCancelHook on the next FundDeployer being "migrated in" to,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationInCancelHook(
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _nextFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationInCancelHook.selector,
_vaultProxy,
_prevFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked("MigrationOutCancelHook: ", returnData))
);
emit MigrationInCancelHookFailed(
returnData,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to invoke a IMigrationHookHandler.MigrationOutHook on the previous FundDeployer being "migrated out" of,
/// which can optionally be implemented on the FundDeployer
function __invokeMigrationOutHook(
IMigrationHookHandler.MigrationOutHook _hook,
address _vaultProxy,
address _prevFundDeployer,
address _nextFundDeployer,
address _nextVaultAccessor,
address _nextVaultLib,
bool _bypassFailure
) private {
(bool success, bytes memory returnData) = _prevFundDeployer.call(
abi.encodeWithSelector(
IMigrationHookHandler.invokeMigrationOutHook.selector,
_hook,
_vaultProxy,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
)
);
if (!success) {
require(
_bypassFailure,
string(abi.encodePacked(__migrationOutHookFailureReasonPrefix(_hook), returnData))
);
emit MigrationOutHookFailed(
returnData,
_hook,
_vaultProxy,
_prevFundDeployer,
_nextFundDeployer,
_nextVaultAccessor,
_nextVaultLib
);
}
}
/// @dev Helper to return a revert reason string prefix for a given MigrationOutHook
function __migrationOutHookFailureReasonPrefix(IMigrationHookHandler.MigrationOutHook _hook)
private
pure
returns (string memory failureReasonPrefix_)
{
if (_hook == IMigrationHookHandler.MigrationOutHook.PreSignal) {
return "MigrationOutHook.PreSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostSignal) {
return "MigrationOutHook.PostSignal: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PreMigrate) {
return "MigrationOutHook.PreMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostMigrate) {
return "MigrationOutHook.PostMigrate: ";
}
if (_hook == IMigrationHookHandler.MigrationOutHook.PostCancel) {
return "MigrationOutHook.PostCancel: ";
}
return "";
}
///////////////////
// STATE GETTERS //
///////////////////
// Provides several potentially helpful getters that are not strictly necessary
/// @notice Gets the current FundDeployer that is allowed to deploy and migrate funds
/// @return currentFundDeployer_ The current FundDeployer contract address
function getCurrentFundDeployer()
external
view
override
returns (address currentFundDeployer_)
{
return currentFundDeployer;
}
/// @notice Gets the FundDeployer with which a given VaultProxy is associated
/// @param _vaultProxy The VaultProxy instance
/// @return fundDeployer_ The FundDeployer contract address
function getFundDeployerForVaultProxy(address _vaultProxy)
external
view
override
returns (address fundDeployer_)
{
return vaultProxyToFundDeployer[_vaultProxy];
}
/// @notice Gets the details of a pending migration request for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return nextFundDeployer_ The FundDeployer contract address from which the migration
/// request was made
/// @return nextVaultAccessor_ The account that will be the next `accessor` on the VaultProxy
/// @return nextVaultLib_ The next VaultLib library contract address to set on the VaultProxy
/// @return executableTimestamp_ The timestamp at which the migration request can be executed
function getMigrationRequestDetailsForVaultProxy(address _vaultProxy)
external
view
override
returns (
address nextFundDeployer_,
address nextVaultAccessor_,
address nextVaultLib_,
uint256 executableTimestamp_
)
{
MigrationRequest memory r = vaultProxyToMigrationRequest[_vaultProxy];
if (r.executableTimestamp > 0) {
return (
r.nextFundDeployer,
r.nextVaultAccessor,
r.nextVaultLib,
r.executableTimestamp
);
}
}
/// @notice Gets the amount of time that must pass between signaling and executing a migration
/// @return migrationTimelock_ The timelock value (in seconds)
function getMigrationTimelock() external view override returns (uint256 migrationTimelock_) {
return migrationTimelock;
}
/// @notice Gets the account that is nominated to be the next owner of this contract
/// @return nominatedOwner_ The account that is nominated to be the owner
function getNominatedOwner() external view override returns (address nominatedOwner_) {
return nominatedOwner;
}
/// @notice Gets the owner of this contract
/// @return owner_ The account that is the owner
function getOwner() external view override returns (address owner_) {
return owner;
}
/// @notice Gets the shares token `symbol` value for use in VaultProxy instances
/// @return sharesTokenSymbol_ The `symbol` value
function getSharesTokenSymbol()
external
view
override
returns (string memory sharesTokenSymbol_)
{
return sharesTokenSymbol;
}
/// @notice Gets the time remaining until the migration request of a given VaultProxy can be executed
/// @param _vaultProxy The VaultProxy instance
/// @return secondsRemaining_ The number of seconds remaining on the timelock
function getTimelockRemainingForMigrationRequest(address _vaultProxy)
external
view
override
returns (uint256 secondsRemaining_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
if (executableTimestamp == 0) {
return 0;
}
if (block.timestamp >= executableTimestamp) {
return 0;
}
return executableTimestamp - block.timestamp;
}
/// @notice Checks whether a migration request that is executable exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasExecutableRequest_ True if a migration request exists and is executable
function hasExecutableMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasExecutableRequest_)
{
uint256 executableTimestamp = vaultProxyToMigrationRequest[_vaultProxy]
.executableTimestamp;
return executableTimestamp > 0 && block.timestamp >= executableTimestamp;
}
/// @notice Checks whether a migration request exists for a given VaultProxy
/// @param _vaultProxy The VaultProxy instance
/// @return hasMigrationRequest_ True if a migration request exists
function hasMigrationRequest(address _vaultProxy)
external
view
override
returns (bool hasMigrationRequest_)
{
return vaultProxyToMigrationRequest[_vaultProxy].executableTimestamp > 0;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../persistent/vault/VaultLibBaseCore.sol";
/// @title MockVaultLib Contract
/// @author Enzyme Council <[email protected]>
/// @notice A mock VaultLib implementation that only extends VaultLibBaseCore
contract MockVaultLib is VaultLibBaseCore {
function getAccessor() external view returns (address) {
return accessor;
}
function getCreator() external view returns (address) {
return creator;
}
function getMigrator() external view returns (address) {
return migrator;
}
function getOwner() external view returns (address) {
return owner;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title ICERC20 Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound tokens (cTokens)
interface ICERC20 is IERC20 {
function decimals() external view returns (uint8);
function mint(uint256) external returns (uint256);
function redeem(uint256) external returns (uint256);
function exchangeRateStored() external view returns (uint256);
function underlying() external returns (address);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../utils/DispatcherOwnerMixin.sol";
import "../IDerivativePriceFeed.sol";
/// @title CompoundPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Compound Tokens (cTokens)
contract CompoundPriceFeed is IDerivativePriceFeed, DispatcherOwnerMixin {
using SafeMath for uint256;
event CTokenAdded(address indexed cToken, address indexed token);
uint256 private constant CTOKEN_RATE_DIVISOR = 10**18;
mapping(address => address) private cTokenToToken;
constructor(
address _dispatcher,
address _weth,
address _ceth,
address[] memory cERC20Tokens
) public DispatcherOwnerMixin(_dispatcher) {
// Set cEth
cTokenToToken[_ceth] = _weth;
emit CTokenAdded(_ceth, _weth);
// Set any other cTokens
if (cERC20Tokens.length > 0) {
__addCERC20Tokens(cERC20Tokens);
}
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
underlyings_ = new address[](1);
underlyings_[0] = cTokenToToken[_derivative];
require(underlyings_[0] != address(0), "calcUnderlyingValues: Unsupported derivative");
underlyingAmounts_ = new uint256[](1);
// Returns a rate scaled to 10^18
underlyingAmounts_[0] = _derivativeAmount
.mul(ICERC20(_derivative).exchangeRateStored())
.div(CTOKEN_RATE_DIVISOR);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return cTokenToToken[_asset] != address(0);
}
//////////////////////
// CTOKENS REGISTRY //
//////////////////////
/// @notice Adds cTokens to the price feed
/// @param _cTokens cTokens to add
/// @dev Only allows CERC20 tokens. CEther is set in the constructor.
function addCTokens(address[] calldata _cTokens) external onlyDispatcherOwner {
__addCERC20Tokens(_cTokens);
}
/// @dev Helper to add cTokens
function __addCERC20Tokens(address[] memory _cTokens) private {
require(_cTokens.length > 0, "__addCTokens: Empty _cTokens");
for (uint256 i; i < _cTokens.length; i++) {
require(cTokenToToken[_cTokens[i]] == address(0), "__addCTokens: Value already set");
address token = ICERC20(_cTokens[i]).underlying();
cTokenToToken[_cTokens[i]] = token;
emit CTokenAdded(_cTokens[i], token);
}
}
////////////////////
// STATE GETTERS //
///////////////////
/// @notice Returns the underlying asset of a given cToken
/// @param _cToken The cToken for which to get the underlying asset
/// @return token_ The underlying token
function getTokenFromCToken(address _cToken) public view returns (address token_) {
return cTokenToToken[_cToken];
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../infrastructure/price-feeds/derivatives/feeds/CompoundPriceFeed.sol";
import "../../../../interfaces/ICERC20.sol";
import "../../../../interfaces/ICEther.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title CompoundAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Compound <https://compound.finance/>
contract CompoundAdapter is AdapterBase {
address private immutable COMPOUND_PRICE_FEED;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _compoundPriceFeed,
address _wethToken
) public AdapterBase(_integrationManager) {
COMPOUND_PRICE_FEED = _compoundPriceFeed;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during cEther lend/redeem
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "COMPOUND";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(address cToken, uint256 tokenAmount, uint256 minCTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = token;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = tokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = cToken;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minCTokenAmount;
} else if (_selector == REDEEM_SELECTOR) {
(address cToken, uint256 cTokenAmount, uint256 minTokenAmount) = __decodeCallArgs(
_encodedCallArgs
);
address token = CompoundPriceFeed(COMPOUND_PRICE_FEED).getTokenFromCToken(cToken);
require(token != address(0), "parseAssetsForMethod: Unsupported cToken");
spendAssets_ = new address[](1);
spendAssets_[0] = cToken;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = cTokenAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = token;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minTokenAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends an amount of a token to Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
if (spendAssets[0] == WETH_TOKEN) {
IWETH(WETH_TOKEN).withdraw(spendAssetAmounts[0]);
ICEther(incomingAssets[0]).mint{value: spendAssetAmounts[0]}();
} else {
__approveMaxAsNeeded(spendAssets[0], incomingAssets[0], spendAssetAmounts[0]);
ICERC20(incomingAssets[0]).mint(spendAssetAmounts[0]);
}
}
/// @notice Redeems an amount of cTokens from Compound
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
// More efficient to parse all from _encodedAssetTransferArgs
(
,
address[] memory spendAssets,
uint256[] memory spendAssetAmounts,
address[] memory incomingAssets
) = __decodeEncodedAssetTransferArgs(_encodedAssetTransferArgs);
ICERC20(spendAssets[0]).redeem(spendAssetAmounts[0]);
if (incomingAssets[0] == WETH_TOKEN) {
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode callArgs for lend and redeem
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (
address cToken_,
uint256 outgoingAssetAmount_,
uint256 minIncomingAssetAmount_
)
{
return abi.decode(_encodedCallArgs, (address, uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `COMPOUND_PRICE_FEED` variable
/// @return compoundPriceFeed_ The `COMPOUND_PRICE_FEED` variable value
function getCompoundPriceFeed() external view returns (address compoundPriceFeed_) {
return COMPOUND_PRICE_FEED;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity ^0.6.12;
/// @title ICEther Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for interactions with Compound Ether
interface ICEther {
function mint() external payable;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/// @title IChai Interface
/// @author Enzyme Council <[email protected]>
/// @notice Minimal interface for our interactions with the Chai contract
interface IChai is IERC20 {
function exit(address, uint256) external;
function join(address, uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IChai.sol";
import "../utils/AdapterBase.sol";
/// @title ChaiAdapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Chai <https://github.com/dapphub/chai>
contract ChaiAdapter is AdapterBase {
address private immutable CHAI;
address private immutable DAI;
constructor(
address _integrationManager,
address _chai,
address _dai
) public AdapterBase(_integrationManager) {
CHAI = _chai;
DAI = _dai;
}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "CHAI";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 daiAmount, uint256 minChaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = DAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = daiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = CHAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minChaiAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 chaiAmount, uint256 minDaiAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = CHAI;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = chaiAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = DAI;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minDaiAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lend Dai for Chai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 daiAmount, ) = __decodeCallArgs(_encodedCallArgs);
__approveMaxAsNeeded(DAI, CHAI, daiAmount);
// Execute Lend on Chai
// Chai.join allows specifying the vaultProxy as the destination of Chai tokens
IChai(CHAI).join(_vaultProxy, daiAmount);
}
/// @notice Redeem Chai for Dai
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 chaiAmount, ) = __decodeCallArgs(_encodedCallArgs);
// Execute redeem on Chai
// Chai.exit sends Dai back to the adapter
IChai(CHAI).exit(address(this), chaiAmount);
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../utils/SwapperBase.sol";
contract MockGenericIntegratee is SwapperBase {
function swap(
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
msg.sender,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
function swapOnBehalf(
address payable _trader,
address[] calldata _assetsToIntegratee,
uint256[] calldata _assetsToIntegrateeAmounts,
address[] calldata _assetsFromIntegratee,
uint256[] calldata _assetsFromIntegrateeAmounts
) external payable {
__swap(
_trader,
_assetsToIntegratee,
_assetsToIntegrateeAmounts,
_assetsFromIntegratee,
_assetsFromIntegrateeAmounts
);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../prices/CentralizedRateProvider.sol";
import "../tokens/MockToken.sol";
import "../utils/SwapperBase.sol";
contract MockChaiIntegratee is MockToken, SwapperBase {
address private immutable CENTRALIZED_RATE_PROVIDER;
address public immutable DAI;
constructor(
address _dai,
address _centralizedRateProvider,
uint8 _decimals
) public MockToken("Chai", "CHAI", _decimals) {
_setupDecimals(_decimals);
CENTRALIZED_RATE_PROVIDER = _centralizedRateProvider;
DAI = _dai;
}
function join(address, uint256 _daiAmount) external {
uint256 tokenDecimals = ERC20(DAI).decimals();
uint256 chaiDecimals = decimals();
// Calculate the amount of tokens per one unit of DAI
uint256 daiPerChaiUnit = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER)
.calcLiveAssetValue(address(this), 10**uint256(chaiDecimals), DAI);
// Calculate the inverse rate to know the amount of CHAI to return from a unit of DAI
uint256 inverseRate = uint256(10**tokenDecimals).mul(10**uint256(chaiDecimals)).div(
daiPerChaiUnit
);
// Mint and send those CHAI to sender
uint256 destAmount = _daiAmount.mul(inverseRate).div(10**tokenDecimals);
_mint(address(this), destAmount);
__swapAssets(msg.sender, DAI, _daiAmount, address(this), destAmount);
}
function exit(address payable _trader, uint256 _chaiAmount) external {
uint256 destAmount = CentralizedRateProvider(CENTRALIZED_RATE_PROVIDER).calcLiveAssetValue(
address(this),
_chaiAmount,
DAI
);
// Burn CHAI of the trader.
_burn(_trader, _chaiAmount);
// Release DAI to the trader.
ERC20(DAI).transfer(msg.sender, destAmount);
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../../../../interfaces/IWETH.sol";
import "../utils/AdapterBase.sol";
/// @title AlphaHomoraV1Adapter Contract
/// @author Enzyme Council <[email protected]>
/// @notice Adapter for Alpha Homora v1 <https://alphafinance.io/>
contract AlphaHomoraV1Adapter is AdapterBase {
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(
address _integrationManager,
address _ibethToken,
address _wethToken
) public AdapterBase(_integrationManager) {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @dev Needed to receive ETH during redemption
receive() external payable {}
/// @notice Provides a constant string identifier for an adapter
/// @return identifier_ An identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ALPHA_HOMORA_V1";
}
/// @notice Parses the expected assets to receive from a call on integration
/// @param _selector The function selector for the callOnIntegration
/// @param _encodedCallArgs The encoded parameters for the callOnIntegration
/// @return spendAssetsHandleType_ A type that dictates how to handle granting
/// the adapter access to spend assets (`None` by default)
/// @return spendAssets_ The assets to spend in the call
/// @return spendAssetAmounts_ The max asset amounts to spend in the call
/// @return incomingAssets_ The assets to receive in the call
/// @return minIncomingAssetAmounts_ The min asset amounts to receive in the call
function parseAssetsForMethod(bytes4 _selector, bytes calldata _encodedCallArgs)
external
view
override
returns (
IIntegrationManager.SpendAssetsHandleType spendAssetsHandleType_,
address[] memory spendAssets_,
uint256[] memory spendAssetAmounts_,
address[] memory incomingAssets_,
uint256[] memory minIncomingAssetAmounts_
)
{
if (_selector == LEND_SELECTOR) {
(uint256 wethAmount, uint256 minIbethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = WETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = wethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = IBETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minIbethAmount;
} else if (_selector == REDEEM_SELECTOR) {
(uint256 ibethAmount, uint256 minWethAmount) = __decodeCallArgs(_encodedCallArgs);
spendAssets_ = new address[](1);
spendAssets_[0] = IBETH_TOKEN;
spendAssetAmounts_ = new uint256[](1);
spendAssetAmounts_[0] = ibethAmount;
incomingAssets_ = new address[](1);
incomingAssets_[0] = WETH_TOKEN;
minIncomingAssetAmounts_ = new uint256[](1);
minIncomingAssetAmounts_[0] = minWethAmount;
} else {
revert("parseAssetsForMethod: _selector invalid");
}
return (
IIntegrationManager.SpendAssetsHandleType.Transfer,
spendAssets_,
spendAssetAmounts_,
incomingAssets_,
minIncomingAssetAmounts_
);
}
/// @notice Lends WETH for ibETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function lend(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 wethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IWETH(payable(WETH_TOKEN)).withdraw(wethAmount);
IAlphaHomoraV1Bank(IBETH_TOKEN).deposit{value: payable(address(this)).balance}();
}
/// @notice Redeems ibETH for WETH
/// @param _vaultProxy The VaultProxy of the calling fund
/// @param _encodedCallArgs Encoded order parameters
/// @param _encodedAssetTransferArgs Encoded args for expected assets to spend and receive
function redeem(
address _vaultProxy,
bytes calldata _encodedCallArgs,
bytes calldata _encodedAssetTransferArgs
)
external
onlyIntegrationManager
fundAssetsTransferHandler(_vaultProxy, _encodedAssetTransferArgs)
{
(uint256 ibethAmount, ) = __decodeCallArgs(_encodedCallArgs);
IAlphaHomoraV1Bank(IBETH_TOKEN).withdraw(ibethAmount);
IWETH(payable(WETH_TOKEN)).deposit{value: payable(address(this)).balance}();
}
// PRIVATE FUNCTIONS
/// @dev Helper to decode the encoded call arguments
function __decodeCallArgs(bytes memory _encodedCallArgs)
private
pure
returns (uint256 outgoingAmount_, uint256 minIncomingAmount_)
{
return abi.decode(_encodedCallArgs, (uint256, uint256));
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @title IAlphaHomoraV1Bank interface
/// @author Enzyme Council <[email protected]>
interface IAlphaHomoraV1Bank {
function deposit() external payable;
function totalETH() external view returns (uint256);
function totalSupply() external view returns (uint256);
function withdraw(uint256) external;
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IAlphaHomoraV1Bank.sol";
import "../IDerivativePriceFeed.sol";
/// @title AlphaHomoraV1PriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Alpha Homora v1 ibETH
contract AlphaHomoraV1PriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
address private immutable IBETH_TOKEN;
address private immutable WETH_TOKEN;
constructor(address _ibethToken, address _wethToken) public {
IBETH_TOKEN = _ibethToken;
WETH_TOKEN = _wethToken;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only ibETH is supported");
underlyings_ = new address[](1);
underlyings_[0] = WETH_TOKEN;
underlyingAmounts_ = new uint256[](1);
IAlphaHomoraV1Bank alphaHomoraBankContract = IAlphaHomoraV1Bank(IBETH_TOKEN);
underlyingAmounts_[0] = _derivativeAmount.mul(alphaHomoraBankContract.totalETH()).div(
alphaHomoraBankContract.totalSupply()
);
return (underlyings_, underlyingAmounts_);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == IBETH_TOKEN;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `IBETH_TOKEN` variable
/// @return ibethToken_ The `IBETH_TOKEN` variable value
function getIbethToken() external view returns (address ibethToken_) {
return IBETH_TOKEN;
}
/// @notice Gets the `WETH_TOKEN` variable
/// @return wethToken_ The `WETH_TOKEN` variable value
function getWethToken() external view returns (address wethToken_) {
return WETH_TOKEN;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../../../interfaces/IMakerDaoPot.sol";
import "../IDerivativePriceFeed.sol";
/// @title ChaiPriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Price source oracle for Chai
contract ChaiPriceFeed is IDerivativePriceFeed {
using SafeMath for uint256;
uint256 private constant CHI_DIVISOR = 10**27;
address private immutable CHAI;
address private immutable DAI;
address private immutable DSR_POT;
constructor(
address _chai,
address _dai,
address _dsrPot
) public {
CHAI = _chai;
DAI = _dai;
DSR_POT = _dsrPot;
}
/// @notice Converts a given amount of a derivative to its underlying asset values
/// @param _derivative The derivative to convert
/// @param _derivativeAmount The amount of the derivative to convert
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The amount of each underlying asset for the equivalent derivative amount
/// @dev Calculation based on Chai source: https://github.com/dapphub/chai/blob/master/src/chai.sol
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
require(isSupportedAsset(_derivative), "calcUnderlyingValues: Only Chai is supported");
underlyings_ = new address[](1);
underlyings_[0] = DAI;
underlyingAmounts_ = new uint256[](1);
underlyingAmounts_[0] = _derivativeAmount.mul(IMakerDaoPot(DSR_POT).chi()).div(
CHI_DIVISOR
);
}
/// @notice Checks if an asset is supported by the price feed
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is supported
function isSupportedAsset(address _asset) public view override returns (bool isSupported_) {
return _asset == CHAI;
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `CHAI` variable value
/// @return chai_ The `CHAI` variable value
function getChai() external view returns (address chai_) {
return CHAI;
}
/// @notice Gets the `DAI` variable value
/// @return dai_ The `DAI` variable value
function getDai() external view returns (address dai_) {
return DAI;
}
/// @notice Gets the `DSR_POT` variable value
/// @return dsrPot_ The `DSR_POT` variable value
function getDsrPot() external view returns (address dsrPot_) {
return DSR_POT;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
/// @notice Limited interface for Maker DSR's Pot contract
/// @dev See DSR integration guide: https://github.com/makerdao/developerguides/blob/master/dai/dsr-integration-guide/dsr-integration-guide-01.md
interface IMakerDaoPot {
function chi() external view returns (uint256);
function rho() external view returns (uint256);
function drip() external returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./FeeBase.sol";
/// @title EntranceRateFeeBase Contract
/// @author Enzyme Council <[email protected]>
/// @notice Calculates a fee based on a rate to be charged to an investor upon entering a fund
abstract contract EntranceRateFeeBase is FeeBase {
using SafeMath for uint256;
event FundSettingsAdded(address indexed comptrollerProxy, uint256 rate);
event Settled(address indexed comptrollerProxy, address indexed payer, uint256 sharesQuantity);
uint256 private constant RATE_DIVISOR = 10**18;
IFeeManager.SettlementType private immutable SETTLEMENT_TYPE;
mapping(address => uint256) private comptrollerProxyToRate;
constructor(address _feeManager, IFeeManager.SettlementType _settlementType)
public
FeeBase(_feeManager)
{
require(
_settlementType == IFeeManager.SettlementType.Burn ||
_settlementType == IFeeManager.SettlementType.Direct,
"constructor: Invalid _settlementType"
);
SETTLEMENT_TYPE = _settlementType;
}
// EXTERNAL FUNCTIONS
/// @notice Add the fee settings for a fund
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settingsData Encoded settings to apply to the policy for a fund
function addFundSettings(address _comptrollerProxy, bytes calldata _settingsData)
external
override
onlyFeeManager
{
uint256 rate = abi.decode(_settingsData, (uint256));
require(rate > 0, "addFundSettings: Fee rate must be >0");
comptrollerProxyToRate[_comptrollerProxy] = rate;
emit FundSettingsAdded(_comptrollerProxy, rate);
}
/// @notice Gets the hooks that are implemented by the fee
/// @return implementedHooksForSettle_ The hooks during which settle() is implemented
/// @return implementedHooksForUpdate_ The hooks during which update() is implemented
/// @return usesGavOnSettle_ True if GAV is used during the settle() implementation
/// @return usesGavOnUpdate_ True if GAV is used during the update() implementation
/// @dev Used only during fee registration
function implementedHooks()
external
view
override
returns (
IFeeManager.FeeHook[] memory implementedHooksForSettle_,
IFeeManager.FeeHook[] memory implementedHooksForUpdate_,
bool usesGavOnSettle_,
bool usesGavOnUpdate_
)
{
implementedHooksForSettle_ = new IFeeManager.FeeHook[](1);
implementedHooksForSettle_[0] = IFeeManager.FeeHook.PostBuyShares;
return (implementedHooksForSettle_, new IFeeManager.FeeHook[](0), false, false);
}
/// @notice Settles the fee
/// @param _comptrollerProxy The ComptrollerProxy of the fund
/// @param _settlementData Encoded args to use in calculating the settlement
/// @return settlementType_ The type of settlement
/// @return payer_ The payer of shares due
/// @return sharesDue_ The amount of shares due
function settle(
address _comptrollerProxy,
address,
IFeeManager.FeeHook,
bytes calldata _settlementData,
uint256
)
external
override
onlyFeeManager
returns (
IFeeManager.SettlementType settlementType_,
address payer_,
uint256 sharesDue_
)
{
uint256 sharesBought;
(payer_, , sharesBought) = __decodePostBuySharesSettlementData(_settlementData);
uint256 rate = comptrollerProxyToRate[_comptrollerProxy];
sharesDue_ = sharesBought.mul(rate).div(RATE_DIVISOR.add(rate));
if (sharesDue_ == 0) {
return (IFeeManager.SettlementType.None, address(0), 0);
}
emit Settled(_comptrollerProxy, payer_, sharesDue_);
return (SETTLEMENT_TYPE, payer_, sharesDue_);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `rate` variable for a fund
/// @param _comptrollerProxy The ComptrollerProxy contract for the fund
/// @return rate_ The `rate` variable value
function getRateForFund(address _comptrollerProxy) external view returns (uint256 rate_) {
return comptrollerProxyToRate[_comptrollerProxy];
}
/// @notice Gets the `SETTLEMENT_TYPE` variable
/// @return settlementType_ The `SETTLEMENT_TYPE` variable value
function getSettlementType()
external
view
returns (IFeeManager.SettlementType settlementType_)
{
return SETTLEMENT_TYPE;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateDirectFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that transfers the fee shares to the fund manager
contract EntranceRateDirectFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Direct)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_DIRECT";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "./utils/EntranceRateFeeBase.sol";
/// @title EntranceRateBurnFee Contract
/// @author Enzyme Council <[email protected]>
/// @notice An EntranceRateFee that burns the fee shares
contract EntranceRateBurnFee is EntranceRateFeeBase {
constructor(address _feeManager)
public
EntranceRateFeeBase(_feeManager, IFeeManager.SettlementType.Burn)
{}
/// @notice Provides a constant string identifier for a fee
/// @return identifier_ The identifier string
function identifier() external pure override returns (string memory identifier_) {
return "ENTRANCE_RATE_BURN";
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract MockChaiPriceSource {
using SafeMath for uint256;
uint256 private chiStored = 10**27;
uint256 private rhoStored = now;
function drip() external returns (uint256) {
require(now >= rhoStored, "drip: invalid now");
rhoStored = now;
chiStored = chiStored.mul(99).div(100);
return chi();
}
////////////////////
// STATE GETTERS //
///////////////////
function chi() public view returns (uint256) {
return chiStored;
}
function rho() public view returns (uint256) {
return rhoStored;
}
}
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <[email protected]>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.6.12;
import "../../utils/DispatcherOwnerMixin.sol";
import "./IAggregatedDerivativePriceFeed.sol";
/// @title AggregatedDerivativePriceFeed Contract
/// @author Enzyme Council <[email protected]>
/// @notice Aggregates multiple derivative price feeds (e.g., Compound, Chai) and dispatches
/// rate requests to the appropriate feed
contract AggregatedDerivativePriceFeed is IAggregatedDerivativePriceFeed, DispatcherOwnerMixin {
event DerivativeAdded(address indexed derivative, address priceFeed);
event DerivativeRemoved(address indexed derivative);
event DerivativeUpdated(
address indexed derivative,
address prevPriceFeed,
address nextPriceFeed
);
mapping(address => address) private derivativeToPriceFeed;
constructor(
address _dispatcher,
address[] memory _derivatives,
address[] memory _priceFeeds
) public DispatcherOwnerMixin(_dispatcher) {
if (_derivatives.length > 0) {
__addDerivatives(_derivatives, _priceFeeds);
}
}
/// @notice Gets the rates for 1 unit of the derivative to its underlying assets
/// @param _derivative The derivative for which to get the rates
/// @return underlyings_ The underlying assets for the _derivative
/// @return underlyingAmounts_ The rates for the _derivative to the underlyings_
function calcUnderlyingValues(address _derivative, uint256 _derivativeAmount)
external
override
returns (address[] memory underlyings_, uint256[] memory underlyingAmounts_)
{
address derivativePriceFeed = derivativeToPriceFeed[_derivative];
require(
derivativePriceFeed != address(0),
"calcUnderlyingValues: _derivative is not supported"
);
return
IDerivativePriceFeed(derivativePriceFeed).calcUnderlyingValues(
_derivative,
_derivativeAmount
);
}
/// @notice Checks whether an asset is a supported derivative
/// @param _asset The asset to check
/// @return isSupported_ True if the asset is a supported derivative
/// @dev This should be as low-cost and simple as possible
function isSupportedAsset(address _asset) external view override returns (bool isSupported_) {
return derivativeToPriceFeed[_asset] != address(0);
}
//////////////////////////
// DERIVATIVES REGISTRY //
//////////////////////////
/// @notice Adds a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to add
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function addDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "addDerivatives: _derivatives cannot be empty");
__addDerivatives(_derivatives, _priceFeeds);
}
/// @notice Removes a list of derivatives
/// @param _derivatives The derivatives to remove
function removeDerivatives(address[] calldata _derivatives) external onlyDispatcherOwner {
require(_derivatives.length > 0, "removeDerivatives: _derivatives cannot be empty");
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] != address(0),
"removeDerivatives: Derivative not yet added"
);
delete derivativeToPriceFeed[_derivatives[i]];
emit DerivativeRemoved(_derivatives[i]);
}
}
/// @notice Updates a list of derivatives with the given price feed values
/// @param _derivatives The derivatives to update
/// @param _priceFeeds The ordered price feeds corresponding to the list of _derivatives
function updateDerivatives(address[] calldata _derivatives, address[] calldata _priceFeeds)
external
onlyDispatcherOwner
{
require(_derivatives.length > 0, "updateDerivatives: _derivatives cannot be empty");
require(
_derivatives.length == _priceFeeds.length,
"updateDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
address prevPriceFeed = derivativeToPriceFeed[_derivatives[i]];
require(prevPriceFeed != address(0), "updateDerivatives: Derivative not yet added");
require(_priceFeeds[i] != prevPriceFeed, "updateDerivatives: Value already set");
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeUpdated(_derivatives[i], prevPriceFeed, _priceFeeds[i]);
}
}
/// @dev Helper to add derivative-feed pairs
function __addDerivatives(address[] memory _derivatives, address[] memory _priceFeeds)
private
{
require(
_derivatives.length == _priceFeeds.length,
"__addDerivatives: Unequal _derivatives and _priceFeeds array lengths"
);
for (uint256 i = 0; i < _derivatives.length; i++) {
require(
derivativeToPriceFeed[_derivatives[i]] == address(0),
"__addDerivatives: Already added"
);
__validateDerivativePriceFeed(_derivatives[i], _priceFeeds[i]);
derivativeToPriceFeed[_derivatives[i]] = _priceFeeds[i];
emit DerivativeAdded(_derivatives[i], _priceFeeds[i]);
}
}
/// @dev Helper to validate a derivative price feed
function __validateDerivativePriceFeed(address _derivative, address _priceFeed) private view {
require(_derivative != address(0), "__validateDerivativePriceFeed: Empty _derivative");
require(_priceFeed != address(0), "__validateDerivativePriceFeed: Empty _priceFeed");
require(
IDerivativePriceFeed(_priceFeed).isSupportedAsset(_derivative),
"__validateDerivativePriceFeed: Unsupported derivative"
);
}
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the registered price feed for a given derivative
/// @return priceFeed_ The price feed contract address
function getPriceFeedForDerivative(address _derivative)
external
view
override
returns (address priceFeed_)
{
return derivativeToPriceFeed[_derivative];
}
}
| @notice Gets the `accessor` variable @return accessor_ The `accessor` variable value | function getAccessor() external view override returns (address accessor_) {
return accessor;
}
| 1,696,907 | [
1,
3002,
326,
1375,
3860,
280,
68,
2190,
327,
9789,
67,
1021,
1375,
3860,
280,
68,
2190,
460,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
336,
8235,
1435,
3903,
1476,
3849,
1135,
261,
2867,
9789,
67,
13,
288,
203,
3639,
327,
9789,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0xdc4B158EB7f3Ef69e389A3B6e822b93256F16d47/sources/EthTransfer.sol | This function is no longer recommended for sending Ether. | function sendViaTransfer() public payable {
payable(msg.sender).transfer(msg.value);
}
| 13,307,412 | [
1,
2503,
445,
353,
1158,
7144,
14553,
364,
5431,
512,
1136,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
282,
445,
1366,
21246,
5912,
1435,
1071,
8843,
429,
288,
203,
3639,
8843,
429,
12,
3576,
18,
15330,
2934,
13866,
12,
3576,
18,
1132,
1769,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0x9f0CB4DC658a837BF624a41E402aE65AA3Ba6816/sources/ETHY.sol | symbol = ETHY name = ETHEREUM YEILD maximum supply = 500000 ETHY | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
}
constructor() public DeflationaryERC20("Ethereum Yield", "ETHY") {
_mint(msg.sender, 500000e18);
}
| 8,760,025 | [
1,
7175,
6647,
273,
512,
2455,
61,
508,
2398,
273,
512,
19905,
41,
2799,
1624,
41,
11382,
4207,
14467,
282,
273,
1381,
11706,
512,
2455,
61,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
5771,
1345,
5912,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
97,
203,
203,
565,
3885,
1435,
1071,
1505,
2242,
367,
814,
654,
39,
3462,
2932,
41,
18664,
379,
31666,
3113,
315,
1584,
44,
61,
7923,
288,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
1381,
11706,
73,
2643,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2022-01-18
*/
pragma solidity 0.6.12;
// SPDX-License-Identifier: GPL-3.0-only
/**
* @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;
}
}
interface IStafiStorage {
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
}
abstract contract StafiBase {
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
IStafiStorage stafiStorage = IStafiStorage(0);
/**
* @dev Throws if called by any sender that doesn't match a network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.trusted", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered staking pool
*/
modifier onlyRegisteredStakingPool(address _stakingPoolAddress) {
require(getBool(keccak256(abi.encodePacked("stakingpool.exists", _stakingPoolAddress))), "Invalid staking pool");
_;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(roleHas("owner", msg.sender), "Account is not the owner");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlyAdmin() {
require(roleHas("admin", msg.sender), "Account is not an admin");
_;
}
/**
* @dev Modifier to scope access to admins
*/
modifier onlySuperUser() {
require(roleHas("owner", msg.sender) || roleHas("admin", msg.sender), "Account is not a super user");
_;
}
/**
* @dev Reverts if the address doesn't have this role
*/
modifier onlyRole(string memory _role) {
require(roleHas(_role, msg.sender), "Account does not match the specified role");
_;
}
/// @dev Set the main Storage address
constructor(address _stafiStorageAddress) public {
// Update the contract address
stafiStorage = IStafiStorage(_stafiStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(keccak256(abi.encodePacked(contractName)) != keccak256(abi.encodePacked("")), "Contract not found");
// Return
return contractName;
}
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return stafiStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint256) { return stafiStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return stafiStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return stafiStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return stafiStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int256) { return stafiStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return stafiStorage.getBytes32(_key); }
function getAddressS(string memory _key) internal view returns (address) { return stafiStorage.getAddress(keccak256(abi.encodePacked(_key))); }
function getUintS(string memory _key) internal view returns (uint256) { return stafiStorage.getUint(keccak256(abi.encodePacked(_key))); }
function getStringS(string memory _key) internal view returns (string memory) { return stafiStorage.getString(keccak256(abi.encodePacked(_key))); }
function getBytesS(string memory _key) internal view returns (bytes memory) { return stafiStorage.getBytes(keccak256(abi.encodePacked(_key))); }
function getBoolS(string memory _key) internal view returns (bool) { return stafiStorage.getBool(keccak256(abi.encodePacked(_key))); }
function getIntS(string memory _key) internal view returns (int256) { return stafiStorage.getInt(keccak256(abi.encodePacked(_key))); }
function getBytes32S(string memory _key) internal view returns (bytes32) { return stafiStorage.getBytes32(keccak256(abi.encodePacked(_key))); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { stafiStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint256 _value) internal { stafiStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { stafiStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { stafiStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { stafiStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int256 _value) internal { stafiStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { stafiStorage.setBytes32(_key, _value); }
function setAddressS(string memory _key, address _value) internal { stafiStorage.setAddress(keccak256(abi.encodePacked(_key)), _value); }
function setUintS(string memory _key, uint256 _value) internal { stafiStorage.setUint(keccak256(abi.encodePacked(_key)), _value); }
function setStringS(string memory _key, string memory _value) internal { stafiStorage.setString(keccak256(abi.encodePacked(_key)), _value); }
function setBytesS(string memory _key, bytes memory _value) internal { stafiStorage.setBytes(keccak256(abi.encodePacked(_key)), _value); }
function setBoolS(string memory _key, bool _value) internal { stafiStorage.setBool(keccak256(abi.encodePacked(_key)), _value); }
function setIntS(string memory _key, int256 _value) internal { stafiStorage.setInt(keccak256(abi.encodePacked(_key)), _value); }
function setBytes32S(string memory _key, bytes32 _value) internal { stafiStorage.setBytes32(keccak256(abi.encodePacked(_key)), _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { stafiStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { stafiStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { stafiStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { stafiStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { stafiStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { stafiStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { stafiStorage.deleteBytes32(_key); }
function deleteAddressS(string memory _key) internal { stafiStorage.deleteAddress(keccak256(abi.encodePacked(_key))); }
function deleteUintS(string memory _key) internal { stafiStorage.deleteUint(keccak256(abi.encodePacked(_key))); }
function deleteStringS(string memory _key) internal { stafiStorage.deleteString(keccak256(abi.encodePacked(_key))); }
function deleteBytesS(string memory _key) internal { stafiStorage.deleteBytes(keccak256(abi.encodePacked(_key))); }
function deleteBoolS(string memory _key) internal { stafiStorage.deleteBool(keccak256(abi.encodePacked(_key))); }
function deleteIntS(string memory _key) internal { stafiStorage.deleteInt(keccak256(abi.encodePacked(_key))); }
function deleteBytes32S(string memory _key) internal { stafiStorage.deleteBytes32(keccak256(abi.encodePacked(_key))); }
/**
* @dev Check if an address has this role
*/
function roleHas(string memory _role, address _address) internal view returns (bool) {
return getBool(keccak256(abi.encodePacked("access.role", _role, _address)));
}
}
// Represents the type of deposits
enum DepositType {
None, // Marks an invalid deposit type
FOUR, // Require 4 ETH from the node operator to be matched with 28 ETH from user deposits
EIGHT, // Require 8 ETH from the node operator to be matched with 24 ETH from user deposits
TWELVE, // Require 12 ETH from the node operator to be matched with 20 ETH from user deposits
SIXTEEN, // Require 16 ETH from the node operator to be matched with 16 ETH from user deposits
Empty // Require 0 ETH from the node operator to be matched with 32 ETH from user deposits (trusted nodes only)
}
// Represents a stakingpool's status within the network
enum StakingPoolStatus {
Initialized, // The stakingpool has been initialized and is awaiting a deposit of user ETH
Prelaunch, // The stakingpool has enough ETH to begin staking and is awaiting launch by the node
Staking, // The stakingpool is currently staking
Withdrawn, // The stakingpool has been withdrawn from by the node
Dissolved // The stakingpool has been dissolved and its user deposited ETH has been returned to the deposit pool
}
interface IStafiStakingPool {
function getStatus() external view returns (StakingPoolStatus);
function getStatusBlock() external view returns (uint256);
function getStatusTime() external view returns (uint256);
function getDepositType() external view returns (DepositType);
function getNodeAddress() external view returns (address);
function getNodeFee() external view returns (uint256);
function getNodeDepositBalance() external view returns (uint256);
function getNodeRefundBalance() external view returns (uint256);
function getNodeDepositAssigned() external view returns (bool);
function getNodeCommonlyRefunded() external view returns (bool);
function getNodeTrustedRefunded() external view returns (bool);
function getUserDepositBalance() external view returns (uint256);
function getUserDepositAssigned() external view returns (bool);
function getUserDepositAssignedTime() external view returns (uint256);
function getPlatformDepositBalance() external view returns (uint256);
function nodeDeposit() external payable;
function userDeposit() external payable;
function stake(bytes calldata _validatorPubkey, bytes calldata _validatorSignature, bytes32 _depositDataRoot) external;
function refund() external;
function dissolve() external;
function close() external;
}
interface IStafiStakingPoolQueue {
function getTotalLength() external view returns (uint256);
function getLength(DepositType _depositType) external view returns (uint256);
function getTotalCapacity() external view returns (uint256);
function getEffectiveCapacity() external view returns (uint256);
function getNextCapacity() external view returns (uint256);
function enqueueStakingPool(DepositType _depositType, address _stakingPool) external;
function dequeueStakingPool() external returns (address);
function removeStakingPool() external;
}
interface IRETHToken {
function getEthValue(uint256 _rethAmount) external view returns (uint256);
function getRethValue(uint256 _ethAmount) external view returns (uint256);
function getExchangeRate() external view returns (uint256);
function getTotalCollateral() external view returns (uint256);
function getCollateralRate() external view returns (uint256);
function depositRewards() external payable;
function depositExcess() external payable;
function userMint(uint256 _ethAmount, address _to) external;
function userBurn(uint256 _rethAmount) external;
}
interface IStafiEther {
function balanceOf(address _contractAddress) external view returns (uint256);
function depositEther() external payable;
function withdrawEther(uint256 _amount) external;
}
interface IStafiEtherWithdrawer {
function receiveEtherWithdrawal() external payable;
}
interface IStafiUserDeposit {
function getBalance() external view returns (uint256);
function getExcessBalance() external view returns (uint256);
function deposit() external payable;
function recycleDissolvedDeposit() external payable;
function recycleWithdrawnDeposit() external payable;
function assignDeposits() external;
function withdrawExcessBalance(uint256 _amount) external;
}
// Accepts user deposits and mints rETH; handles assignment of deposited ETH to pools
contract StafiUserDeposit is StafiBase, IStafiUserDeposit, IStafiEtherWithdrawer {
// Libs
using SafeMath for uint256;
// Events
event DepositReceived(address indexed from, uint256 amount, uint256 time);
event DepositRecycled(address indexed from, uint256 amount, uint256 time);
event DepositAssigned(address indexed stakingPool, uint256 amount, uint256 time);
event ExcessWithdrawn(address indexed to, uint256 amount, uint256 time);
// Construct
constructor(address _stafiStorageAddress) StafiBase(_stafiStorageAddress) public {
version = 1;
// Initialize settings on deployment
if (!getBoolS("settings.user.deposit.init")) {
// Apply settings
setDepositEnabled(true);
setAssignDepositsEnabled(true);
setMinimumDeposit(0.01 ether);
// setMaximumDepositPoolSize(100000 ether);
setMaximumDepositAssignments(2);
// Settings initialized
setBoolS("settings.user.deposit.init", true);
}
}
// Current deposit pool balance
function getBalance() override public view returns (uint256) {
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
return stafiEther.balanceOf(address(this));
}
// Excess deposit pool balance (in excess of stakingPool queue capacity)
function getExcessBalance() override public view returns (uint256) {
// Get stakingPool queue capacity
IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue"));
uint256 stakingPoolCapacity = stafiStakingPoolQueue.getEffectiveCapacity();
// Calculate and return
uint256 balance = getBalance();
if (stakingPoolCapacity >= balance) { return 0; }
else { return balance.sub(stakingPoolCapacity); }
}
// Receive a ether withdrawal
// Only accepts calls from the StafiEther contract
function receiveEtherWithdrawal() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiEther", msg.sender) {}
// Accept a deposit from a user
function deposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) {
// Check deposit settings
require(getDepositEnabled(), "Deposits into Stafi are currently disabled");
require(msg.value >= getMinimumDeposit(), "The deposited amount is less than the minimum deposit size");
// require(getBalance().add(msg.value) <= getMaximumDepositPoolSize(), "The deposit pool size after depositing exceeds the maximum size");
// Load contracts
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
// Mint rETH to user account
rETHToken.userMint(msg.value, msg.sender);
// Emit deposit received event
emit DepositReceived(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Recycle a deposit from a dissolved stakingPool
// Only accepts calls from registered stakingPools
function recycleDissolvedDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyRegisteredStakingPool(msg.sender) {
// Emit deposit recycled event
emit DepositRecycled(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Recycle a deposit from a withdrawn stakingPool
function recycleWithdrawnDeposit() override external payable onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("stafiNetworkWithdrawal", msg.sender) {
// Emit deposit recycled event
emit DepositRecycled(msg.sender, msg.value, now);
// Process deposit
processDeposit();
}
// Process a deposit
function processDeposit() private {
// Load contracts
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Transfer ETH to stafiEther
stafiEther.depositEther{value: msg.value}();
// Assign deposits if enabled
assignDeposits();
}
// Assign deposits to available stakingPools
function assignDeposits() override public onlyLatestContract("stafiUserDeposit", address(this)) {
// Check deposit settings
require(getAssignDepositsEnabled(), "Deposit assignments are currently disabled");
// Load contracts
IStafiStakingPoolQueue stafiStakingPoolQueue = IStafiStakingPoolQueue(getContractAddress("stafiStakingPoolQueue"));
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Assign deposits
uint256 maximumDepositAssignments = getMaximumDepositAssignments();
for (uint256 i = 0; i < maximumDepositAssignments; ++i) {
// Get & check next available staking pool capacity
uint256 stakingPoolCapacity = stafiStakingPoolQueue.getNextCapacity();
if (stakingPoolCapacity == 0 || getBalance() < stakingPoolCapacity) { break; }
// Dequeue next available staking pool
address stakingPoolAddress = stafiStakingPoolQueue.dequeueStakingPool();
IStafiStakingPool stakingPool = IStafiStakingPool(stakingPoolAddress);
// Withdraw ETH from stafiEther
stafiEther.withdrawEther(stakingPoolCapacity);
// Assign deposit to staking pool
stakingPool.userDeposit{value: stakingPoolCapacity}();
// Emit deposit assigned event
emit DepositAssigned(stakingPoolAddress, stakingPoolCapacity, now);
}
}
// Withdraw excess deposit pool balance for rETH collateral
function withdrawExcessBalance(uint256 _amount) override external onlyLatestContract("stafiUserDeposit", address(this)) onlyLatestContract("rETHToken", msg.sender) {
// Load contracts
IRETHToken rETHToken = IRETHToken(getContractAddress("rETHToken"));
IStafiEther stafiEther = IStafiEther(getContractAddress("stafiEther"));
// Check amount
require(_amount <= getExcessBalance(), "Insufficient excess balance for withdrawal");
// Withdraw ETH from vault
stafiEther.withdrawEther(_amount);
// Transfer to rETH contract
rETHToken.depositExcess{value: _amount}();
// Emit excess withdrawn event
emit ExcessWithdrawn(msg.sender, _amount, now);
}
// Deposits currently enabled
function getDepositEnabled() public view returns (bool) {
return getBoolS("settings.deposit.enabled");
}
function setDepositEnabled(bool _value) public onlySuperUser {
setBoolS("settings.deposit.enabled", _value);
}
// Deposit assignments currently enabled
function getAssignDepositsEnabled() public view returns (bool) {
return getBoolS("settings.deposit.assign.enabled");
}
function setAssignDepositsEnabled(bool _value) public onlySuperUser {
setBoolS("settings.deposit.assign.enabled", _value);
}
// Minimum deposit size
function getMinimumDeposit() public view returns (uint256) {
return getUintS("settings.deposit.minimum");
}
function setMinimumDeposit(uint256 _value) public onlySuperUser {
setUintS("settings.deposit.minimum", _value);
}
// The maximum size of the deposit pool
// function getMaximumDepositPoolSize() public view returns (uint256) {
// return getUintS("settings.deposit.pool.maximum");
// }
// function setMaximumDepositPoolSize(uint256 _value) public onlySuperUser {
// setUintS("settings.deposit.pool.maximum", _value);
// }
// The maximum number of deposit assignments to perform at once
function getMaximumDepositAssignments() public view returns (uint256) {
return getUintS("settings.deposit.assign.maximum");
}
function setMaximumDepositAssignments(uint256 _value) public onlySuperUser {
setUintS("settings.deposit.assign.maximum", _value);
}
} | The maximum number of deposit assignments to perform at once | function getMaximumDepositAssignments() public view returns (uint256) {
return getUintS("settings.deposit.assign.maximum");
}
| 10,724,417 | [
1,
1986,
4207,
1300,
434,
443,
1724,
13610,
358,
3073,
622,
3647,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
25194,
758,
1724,
18628,
1435,
1071,
1476,
1135,
261,
11890,
5034,
13,
288,
203,
3639,
327,
336,
5487,
55,
2932,
4272,
18,
323,
1724,
18,
6145,
18,
15724,
8863,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/4/0xC62b3c9aEeD164FFa440b29905986862688E2727/sources/MasterChef.sol | MasterChef is the master of Icecream. He can make Icecream and he is a fair guy. Note that it's ownable and the owner wields tremendous power. The ownership will be transferred to a governance smart contract once ICECREAM is sufficiently distributed and the community can show to govern itself. Have fun reading it. Hopefully it's bug-free. God bless. Info of each user. | contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct UserInfo {
}
struct PoolInfo {
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
IcecreamToken _icecream,
address _devaddr,
uint256 _icecreamPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
IcecreamToken public icecream;
address public devaddr;
uint256 public bonusEndBlock;
uint256 public icecreamPerBlock;
uint256 public constant BONUS_MULTIPLIER = 10;
IMigratorChef public migrator;
PoolInfo[] public poolInfo;
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
uint256 public totalAllocPoint = 0;
uint256 public startBlock;
) public {
icecream = _icecream;
devaddr = _devaddr;
icecreamPerBlock = _icecreamPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accIcecreamPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accIcecreamPerShare: 0
}));
}
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accIcecreamPerShare: 0
}));
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
function setMigrator(IMigratorChef _migrator) public onlyMigratorOwner {
migrator = _migrator;
}
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
return _to.sub(_from);
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
} else if (_from >= bonusEndBlock) {
} else {
function pendingIcecream(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accIcecreamPerShare = pool.accIcecreamPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 icecreamPerBlockWeek = getRewardPerBlock(pool.lastRewardBlock);
uint256 icecreamReward = multiplier.mul(icecreamPerBlockWeek).mul(pool.allocPoint).div(totalAllocPoint);
accIcecreamPerShare = accIcecreamPerShare.add(icecreamReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
}
function pendingIcecream(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accIcecreamPerShare = pool.accIcecreamPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 icecreamPerBlockWeek = getRewardPerBlock(pool.lastRewardBlock);
uint256 icecreamReward = multiplier.mul(icecreamPerBlockWeek).mul(pool.allocPoint).div(totalAllocPoint);
accIcecreamPerShare = accIcecreamPerShare.add(icecreamReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 icecreamPerBlockWeek = getRewardPerBlock(pool.lastRewardBlock);
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 icecreamReward = multiplier.mul(icecreamPerBlockWeek).mul(pool.allocPoint).div(totalAllocPoint);
icecream.mint(devaddr, icecreamReward.div(10));
icecream.mint(address(this), icecreamReward);
pool.accIcecreamPerShare = pool.accIcecreamPerShare.add(icecreamReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 icecreamPerBlockWeek = getRewardPerBlock(pool.lastRewardBlock);
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 icecreamReward = multiplier.mul(icecreamPerBlockWeek).mul(pool.allocPoint).div(totalAllocPoint);
icecream.mint(devaddr, icecreamReward.div(10));
icecream.mint(address(this), icecreamReward);
pool.accIcecreamPerShare = pool.accIcecreamPerShare.add(icecreamReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 icecreamPerBlockWeek = getRewardPerBlock(pool.lastRewardBlock);
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 icecreamReward = multiplier.mul(icecreamPerBlockWeek).mul(pool.allocPoint).div(totalAllocPoint);
icecream.mint(devaddr, icecreamReward.div(10));
icecream.mint(address(this), icecreamReward);
pool.accIcecreamPerShare = pool.accIcecreamPerShare.add(icecreamReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(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.accIcecreamPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(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.accIcecreamPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(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.accIcecreamPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(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.accIcecreamPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accIcecreamPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accIcecreamPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accIcecreamPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeIcecreamTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accIcecreamPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
function safeIcecreamTransfer(address _to, uint256 _amount) internal {
uint256 icecreamBal = icecream.balanceOf(address(this));
if (_amount > icecreamBal) {
icecream.transfer(_to, icecreamBal);
icecream.transfer(_to, _amount);
}
}
function safeIcecreamTransfer(address _to, uint256 _amount) internal {
uint256 icecreamBal = icecream.balanceOf(address(this));
if (_amount > icecreamBal) {
icecream.transfer(_to, icecreamBal);
icecream.transfer(_to, _amount);
}
}
} else {
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
function getRewardPerBlock(uint256 blockNumber) public view returns (uint256) {
if (blockNumber >= startBlock){
uint256 perDayBlocks = 5760;
uint256 blockDaysPassed = (blockNumber.sub(startBlock)).div(perDayBlocks);
if(blockDaysPassed <= 0){
return icecreamPerBlock;
}
else if(blockDaysPassed > 0 && blockDaysPassed <= 30){
return icecreamPerBlock;
}
else if(blockDaysPassed > 30 && blockDaysPassed <= 60){
return icecreamPerBlock.div(2);
}
else if(blockDaysPassed > 60 && blockDaysPassed <= 90){
return icecreamPerBlock.div(4);
}
else if(blockDaysPassed > 90 && blockDaysPassed <= 120){
return icecreamPerBlock.div(8);
}
else if(blockDaysPassed > 120 && blockDaysPassed <= 150){
return icecreamPerBlock.div(16);
}
else if(blockDaysPassed > 150 && blockDaysPassed <= 180){
return icecreamPerBlock.div(32);
}
else if(blockDaysPassed > 180 && blockDaysPassed <= 210){
return icecreamPerBlock.div(64);
}
else {
return icecreamPerBlock.div(100);
}
return 0;
}
}
} else {
function setStartBlock(uint256 _startBlock) public onlyOwner {
startBlock = _startBlock;
}
} | 8,613,364 | [
1,
7786,
39,
580,
74,
353,
326,
4171,
434,
467,
27832,
793,
18,
8264,
848,
1221,
467,
27832,
793,
471,
3904,
353,
279,
284,
1826,
3058,
93,
18,
3609,
716,
518,
1807,
4953,
429,
471,
326,
3410,
341,
491,
87,
268,
2764,
409,
1481,
7212,
18,
1021,
23178,
903,
506,
906,
4193,
358,
279,
314,
1643,
82,
1359,
13706,
6835,
3647,
467,
1441,
5458,
2192,
353,
18662,
715,
16859,
471,
326,
19833,
848,
2405,
358,
314,
1643,
82,
6174,
18,
21940,
9831,
6453,
518,
18,
670,
1306,
4095,
518,
1807,
7934,
17,
9156,
18,
611,
369,
324,
2656,
18,
3807,
434,
1517,
729,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
13453,
39,
580,
74,
353,
14223,
6914,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
203,
565,
1958,
25003,
288,
203,
565,
289,
203,
203,
565,
1958,
8828,
966,
288,
203,
565,
289,
203,
203,
203,
203,
565,
871,
4019,
538,
305,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
3423,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
565,
871,
512,
6592,
75,
2075,
1190,
9446,
12,
2867,
8808,
729,
16,
2254,
5034,
8808,
4231,
16,
2254,
5034,
3844,
1769,
203,
203,
565,
3885,
12,
203,
3639,
467,
27832,
793,
1345,
389,
1812,
71,
793,
16,
203,
3639,
1758,
389,
5206,
4793,
16,
203,
3639,
2254,
5034,
389,
1812,
71,
793,
2173,
1768,
16,
203,
3639,
2254,
5034,
389,
1937,
1768,
16,
203,
3639,
2254,
5034,
389,
18688,
407,
1638,
1768,
203,
565,
467,
27832,
793,
1345,
1071,
277,
27832,
793,
31,
203,
565,
1758,
1071,
4461,
4793,
31,
203,
565,
2254,
5034,
1071,
324,
22889,
1638,
1768,
31,
203,
565,
2254,
5034,
1071,
277,
27832,
793,
2173,
1768,
31,
203,
565,
2254,
5034,
1071,
5381,
605,
673,
3378,
67,
24683,
2053,
654,
273,
1728,
31,
203,
565,
6246,
2757,
639,
39,
580,
74,
1071,
30188,
31,
203,
565,
8828,
966,
8526,
1071,
2845,
966,
31,
203,
565,
2874,
261,
11890,
5034,
516,
2874,
261,
2867,
516,
25003,
3719,
2
] |
./full_match/4/0x9715C55907BD2B93140715dFc421e60f3F486C62/sources/browser/bondingcurve.sol | sub x^(28-1) * (34! * 28^(28-1) / 28!)
| res -= xi * 0x00c8c8f66db1fced378ee50e536000000000000000; | 736,123 | [
1,
1717,
619,
29020,
6030,
17,
21,
13,
225,
261,
5026,
5,
225,
9131,
29020,
6030,
17,
21,
13,
342,
9131,
24949,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
400,
3947,
14087,
380,
374,
92,
713,
71,
28,
71,
28,
74,
6028,
1966,
21,
74,
3263,
6418,
28,
1340,
3361,
73,
25,
5718,
12648,
17877,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// File: @openzeppelin\contracts-ethereum-package\contracts\math\SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin\upgrades\contracts\Initializable.sol
pragma solidity >=0.4.24 <0.7.0;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is Initializable, IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
function initialize(string memory name, string memory symbol, uint8 decimals) public initializer {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\utils\Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\GSN\Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\CapperRole.sol
pragma solidity ^0.5.0;
contract CapperRole is Initializable, Context {
using Roles for Roles.Role;
event CapperAdded(address indexed account);
event CapperRemoved(address indexed account);
Roles.Role private _cappers;
function initialize(address sender) public initializer {
if (!isCapper(sender)) {
_addCapper(sender);
}
}
modifier onlyCapper() {
require(isCapper(_msgSender()), "CapperRole: caller does not have the Capper role");
_;
}
function isCapper(address account) public view returns (bool) {
return _cappers.has(account);
}
function addCapper(address account) public onlyCapper {
_addCapper(account);
}
function renounceCapper() public {
_removeCapper(_msgSender());
}
function _addCapper(address account) internal {
_cappers.add(account);
emit CapperAdded(account);
}
function _removeCapper(address account) internal {
_cappers.remove(account);
emit CapperRemoved(account);
}
uint256[50] private ______gap;
}
// File: contracts\interfaces\defi\IDefiProtocol.sol
pragma solidity ^0.5.12;
interface IDefiProtocol {
/**
* @notice Transfer tokens from sender to DeFi protocol
* @param token Address of token
* @param amount Value of token to deposit
* @return new balances of each token
*/
function handleDeposit(address token, uint256 amount) external;
function handleDeposit(address[] calldata tokens, uint256[] calldata amounts) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param token Address of token
* @param amount Denormalized value of token to withdraw
* @return new balances of each token
*/
function withdraw(address beneficiary, address token, uint256 amount) external;
/**
* @notice Transfer tokens from DeFi protocol to beneficiary
* @param amounts Array of amounts to withdraw, in order of supportedTokens()
* @return new balances of each token
*/
function withdraw(address beneficiary, uint256[] calldata amounts) external;
/**
* @notice Claim rewards. Reward tokens will be stored on protocol balance.
* @return tokens and their amounts received
*/
function claimRewards() external returns(address[] memory tokens, uint256[] memory amounts);
/**
* @notice Withdraw reward tokens to user
* @dev called by SavingsModule
* @param token Reward token to withdraw
* @param user Who should receive tokens
* @param amount How many tokens to send
*/
function withdrawReward(address token, address user, uint256 amount) external;
/**
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOf(address token) external returns(uint256);
/**
* @notice Balance of all tokens supported by protocol
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
*/
function balanceOfAll() external returns(uint256[] memory);
/**
* @notice Returns optimal proportions of underlying tokens
* to prevent fees on deposit/withdrawl if supplying multiple tokens
* @dev This function is not view because on some protocols
* (Compound, RAY with Compound oportunity) it may cause storage writes
* same as balanceOfAll()
*/
function optimalProportions() external returns(uint256[] memory);
/**
* @notice Returns normalized (to USD with 18 decimals) summary balance
* of pool using all tokens in this protocol
*/
function normalizedBalance() external returns(uint256);
function supportedTokens() external view returns(address[] memory);
function supportedTokensCount() external view returns(uint256);
function supportedRewardTokens() external view returns(address[] memory);
function isSupportedRewardToken(address token) external view returns(bool);
/**
* @notice Returns if this protocol can swap all it's normalizedBalance() to specified token
*/
function canSwapToToken(address token) external view returns(bool);
}
// File: @openzeppelin\contracts-ethereum-package\contracts\ownership\Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: contracts\common\Base.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Base is Initializable, Context, Ownable {
address constant ZERO_ADDRESS = address(0);
function initialize() public initializer {
Ownable.initialize(_msgSender());
}
}
// File: contracts\core\ModuleNames.sol
pragma solidity ^0.5.12;
/**
* @dev List of module names
*/
contract ModuleNames {
// Pool Modules
string internal constant MODULE_ACCESS = "access";
string internal constant MODULE_SAVINGS = "savings";
string internal constant MODULE_INVESTING = "investing";
string internal constant MODULE_STAKING = "staking";
string internal constant MODULE_DCA = "dca";
string internal constant MODULE_REWARD = "reward";
// Pool tokens
string internal constant TOKEN_AKRO = "akro";
string internal constant TOKEN_ADEL = "adel";
// External Modules (used to store addresses of external contracts)
string internal constant CONTRACT_RAY = "ray";
}
// File: contracts\common\Module.sol
pragma solidity ^0.5.12;
/**
* Base contract for all modules
*/
contract Module is Base, ModuleNames {
event PoolAddressChanged(address newPool);
address public pool;
function initialize(address _pool) public initializer {
Base.initialize();
setPool(_pool);
}
function setPool(address _pool) public onlyOwner {
require(_pool != ZERO_ADDRESS, "Module: pool address can't be zero");
pool = _pool;
emit PoolAddressChanged(_pool);
}
function getModuleAddress(string memory module) public view returns(address){
require(pool != ZERO_ADDRESS, "Module: no pool");
(bool success, bytes memory result) = pool.staticcall(abi.encodeWithSignature("get(string)", module));
//Forward error from Pool contract
if (!success) assembly {
revert(add(result, 32), result)
}
address moduleAddress = abi.decode(result, (address));
// string memory error = string(abi.encodePacked("Module: requested module not found - ", module));
// require(moduleAddress != ZERO_ADDRESS, error);
require(moduleAddress != ZERO_ADDRESS, "Module: requested module not found");
return moduleAddress;
}
}
// File: contracts\interfaces\access\IAccessModule.sol
pragma solidity ^0.5.12;
interface IAccessModule {
enum Operation {
Deposit,
Withdraw
}
/**
* @notice Check if operation is allowed
* @param operation Requested operation
* @param sender Sender of transaction
*/
function isOperationAllowed(Operation operation, address sender) external view returns(bool);
}
// File: contracts\modules\access\AccessChecker.sol
pragma solidity ^0.5.12;
contract AccessChecker is Module {
modifier operationAllowed(IAccessModule.Operation operation) {
IAccessModule am = IAccessModule(getModuleAddress(MODULE_ACCESS));
require(am.isOperationAllowed(operation, _msgSender()), "AccessChecker: operation not allowed");
_;
}
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Initializable, Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\access\roles\MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole is Initializable, Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
function initialize(address sender) public initializer {
if (!isMinter(sender)) {
_addMinter(sender);
}
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is Initializable, ERC20, MinterRole {
function initialize(address sender) public initializer {
MinterRole.initialize(sender);
}
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
uint256[50] private ______gap;
}
// File: @openzeppelin\contracts-ethereum-package\contracts\token\ERC20\ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Initializable, Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
uint256[50] private ______gap;
}
// File: contracts\interfaces\token\IPoolTokenBalanceChangeRecipient.sol
pragma solidity ^0.5.12;
interface IPoolTokenBalanceChangeRecipient {
function poolTokenBalanceChanged(address user) external;
}
// File: contracts\modules\token\DistributionToken.sol
pragma solidity ^0.5.12;
//solhint-disable func-order
contract DistributionToken is ERC20, ERC20Mintable {
using SafeMath for uint256;
uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60;
event DistributionCreated(uint256 amount, uint256 totalSupply);
event DistributionsClaimed(address account, uint256 amount, uint256 fromDistribution, uint256 toDistribution);
event DistributionAccumulatorIncreased(uint256 amount);
struct Distribution {
uint256 amount; // Amount of tokens being distributed during the event
uint256 totalSupply; // Total supply before distribution
}
Distribution[] public distributions; // Array of all distributions
mapping(address => uint256) public nextDistributions; // Map account to first distribution not yet processed
uint256 public nextDistributionTimestamp; //Timestamp when next distribuition should be fired regardles of accumulated tokens
uint256 public distributionAccumulator; //Tokens accumulated for next distribution
function distribute(uint256 amount) external onlyMinter {
distributionAccumulator = distributionAccumulator.add(amount);
emit DistributionAccumulatorIncreased(amount);
_createDistributionIfReady();
}
function createDistribution() external onlyMinter {
require(distributionAccumulator > 0, "DistributionToken: nothing to distribute");
_createDistribution();
}
function claimDistributions(address account) external returns(uint256) {
_createDistributionIfReady();
uint256 amount = _updateUserBalance(account, distributions.length);
if (amount > 0) userBalanceChanged(account);
return amount;
}
/**
* @notice Claims distributions and allows to specify how many distributions to process.
* This allows limit gas usage.
* One can do this for others
*/
function claimDistributions(address account, uint256 toDistribution) external returns(uint256) {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
require(nextDistributions[account] < toDistribution, "DistributionToken: no distributions to claim");
uint256 amount = _updateUserBalance(account, toDistribution);
if (amount > 0) userBalanceChanged(account);
return amount;
}
function claimDistributions(address[] calldata accounts) external {
_createDistributionIfReady();
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], distributions.length);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
function claimDistributions(address[] calldata accounts, uint256 toDistribution) external {
require(toDistribution <= distributions.length, "DistributionToken: lastDistribution too hight");
for (uint256 i=0; i < accounts.length; i++){
uint256 amount = _updateUserBalance(accounts[i], toDistribution);
if (amount > 0) userBalanceChanged(accounts[i]);
}
}
/**
* @notice Full balance of account includes:
* - balance of tokens account holds himself (0 for addresses of locking contracts)
* - balance of tokens locked in contracts
* - tokens not yet claimed from distributions
*/
function fullBalanceOf(address account) public view returns(uint256){
if (account == address(this)) return 0; //Token itself only holds tokens for others
uint256 distributionBalance = distributionBalanceOf(account);
uint256 unclaimed = calculateClaimAmount(account);
return distributionBalance.add(unclaimed);
}
/**
* @notice How many tokens are not yet claimed from distributions
* @param account Account to check
* @return Amount of tokens available to claim
*/
function calculateUnclaimedDistributions(address account) public view returns(uint256) {
return calculateClaimAmount(account);
}
/**
* @notice Calculates amount of tokens distributed to inital amount between startDistribution and nextDistribution
* @param fromDistribution index of first Distribution to start calculations
* @param toDistribution index of distribuition next to the last processed
* @param initialBalance amount of tokens before startDistribution
* @return amount of tokens distributed
*/
function calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) public view returns(uint256) {
require(fromDistribution < toDistribution, "DistributionToken: startDistribution is too high");
require(toDistribution <= distributions.length, "DistributionToken: nextDistribution is too high");
return _calculateDistributedAmount(fromDistribution, toDistribution, initialBalance);
}
function nextDistribution() public view returns(uint256){
return distributions.length;
}
/**
* @notice Balance of account, which is counted for distributions
* It only represents already distributed balance.
* @dev This function should be overloaded to include balance of tokens stored in proposals
*/
function distributionBalanceOf(address account) public view returns(uint256) {
return balanceOf(account);
}
/**
* @notice Total supply which is counted for distributions
* It only represents already distributed tokens
* @dev This function should be overloaded to exclude tokens locked in loans
*/
function distributionTotalSupply() public view returns(uint256){
return totalSupply();
}
// Override functions that change user balance
function _transfer(address sender, address recipient, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(sender);
_updateUserBalance(recipient);
super._transfer(sender, recipient, amount);
userBalanceChanged(sender);
userBalanceChanged(recipient);
}
function _mint(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._mint(account, amount);
userBalanceChanged(account);
}
function _burn(address account, uint256 amount) internal {
_createDistributionIfReady();
_updateUserBalance(account);
super._burn(account, amount);
userBalanceChanged(account);
}
function _updateUserBalance(address account) internal returns(uint256) {
return _updateUserBalance(account, distributions.length);
}
function _updateUserBalance(address account, uint256 toDistribution) internal returns(uint256) {
uint256 fromDistribution = nextDistributions[account];
if (fromDistribution >= toDistribution) return 0;
uint256 distributionAmount = calculateClaimAmount(account, toDistribution);
nextDistributions[account] = toDistribution;
if (distributionAmount == 0) return 0;
super._transfer(address(this), account, distributionAmount);
emit DistributionsClaimed(account, distributionAmount, fromDistribution, toDistribution);
return distributionAmount;
}
function _createDistributionIfReady() internal {
if (!isReadyForDistribution()) return;
_createDistribution();
}
function _createDistribution() internal {
uint256 currentTotalSupply = distributionTotalSupply();
distributions.push(Distribution({
amount:distributionAccumulator,
totalSupply: currentTotalSupply
}));
super._mint(address(this), distributionAccumulator); //Use super because we overloaded _mint in this contract and need old behaviour
emit DistributionCreated(distributionAccumulator, currentTotalSupply);
// Clear data for next distribution
distributionAccumulator = 0;
nextDistributionTimestamp = now.sub(now % DISTRIBUTION_AGGREGATION_PERIOD).add(DISTRIBUTION_AGGREGATION_PERIOD);
}
/**
* @dev This is a placeholder, which may be overrided to notify other contracts of PTK balance change
*/
function userBalanceChanged(address /*account*/) internal {
}
/**
* @notice Calculates amount of account's tokens to be claimed from distributions
*/
function calculateClaimAmount(address account) internal view returns(uint256) {
if (nextDistributions[account] >= distributions.length) return 0;
return calculateClaimAmount(account, distributions.length);
}
function calculateClaimAmount(address account, uint256 toDistribution) internal view returns(uint256) {
assert(toDistribution <= distributions.length);
return _calculateDistributedAmount(nextDistributions[account], toDistribution, distributionBalanceOf(account));
}
function _calculateDistributedAmount(uint256 fromDistribution, uint256 toDistribution, uint256 initialBalance) internal view returns(uint256) {
uint256 next = fromDistribution;
uint256 balance = initialBalance;
if (initialBalance == 0) return 0;
while (next < toDistribution) {
uint256 da = balance.mul(distributions[next].amount).div(distributions[next].totalSupply);
balance = balance.add(da);
next++;
}
return balance.sub(initialBalance);
}
/**
* @dev Calculates if conditions for creating new distribution are met
*/
function isReadyForDistribution() internal view returns(bool) {
return (distributionAccumulator > 0) && (now >= nextDistributionTimestamp);
}
}
// File: contracts\modules\token\PoolToken.sol
pragma solidity ^0.5.12;
contract PoolToken is Module, ERC20, ERC20Detailed, ERC20Mintable, ERC20Burnable, DistributionToken {
bool allowTransfers;
function initialize(address _pool, string memory poolName, string memory poolSymbol) public initializer {
Module.initialize(_pool);
ERC20Detailed.initialize(poolName, poolSymbol, 18);
ERC20Mintable.initialize(_msgSender());
}
function setAllowTransfers(bool _allowTransfers) public onlyOwner {
allowTransfers = _allowTransfers;
}
/**
* @dev Overrides ERC20Burnable burnFrom to allow unlimited transfers by SavingsModule
*/
function burnFrom(address from, uint256 value) public {
address savingsModule = getModuleAddress(MODULE_SAVINGS);
if (_msgSender() == savingsModule) {
//Skip decrease allowance
_burn(from, value);
}else{
super.burnFrom(from, value);
}
}
function _transfer(address sender, address recipient, uint256 amount) internal {
if( !allowTransfers &&
(sender != address(this)) //transfers from *this* used for distributions
){
revert("PoolToken: transfers between users disabled");
}
super._transfer(sender, recipient, amount);
}
function userBalanceChanged(address account) internal {
IPoolTokenBalanceChangeRecipient savings = IPoolTokenBalanceChangeRecipient(getModuleAddress(MODULE_SAVINGS));
savings.poolTokenBalanceChanged(account);
}
function distributionBalanceOf(address account) public view returns(uint256) {
return (account == address(this))?0:super.distributionBalanceOf(account);
}
function distributionTotalSupply() public view returns(uint256) {
return super.distributionTotalSupply().sub(balanceOf(address(this)));
}
}
// File: contracts\modules\savings\RewardDistributions.sol
pragma solidity ^0.5.12;
contract RewardDistributions is Base, IPoolTokenBalanceChangeRecipient, AccessChecker {
event RewardDistribution(address indexed poolToken, address indexed rewardToken, uint256 amount, uint256 totalShares);
event RewardWithdraw(address indexed user, address indexed rewardToken, uint256 amount);
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct RewardTokenDistribution {
address poolToken; // PoolToken which holders will receive reward
uint256 totalShares; // Total shares of PoolToken participating in this distribution
address[] rewardTokens; // List of reward tokens being distributed
mapping(address=>uint256) amounts;
}
struct UserProtocolRewards {
mapping(address=>uint256) amounts; // Maps address of reward token to amount beeing distributed
}
struct RewardBalance {
uint256 nextDistribution;
mapping(address => uint256) shares; // Maps PoolToken to amount of user shares participating in distributions
mapping(address => UserProtocolRewards) rewardsByProtocol; //Maps PoolToken to ProtocolRewards struct (map of reward tokens to their balances);
}
RewardTokenDistribution[] rewardDistributions;
mapping(address=>RewardBalance) rewardBalances; //Mapping users to their RewardBalance
function poolTokenByProtocol(address _protocol) public view returns(address);
function protocolByPoolToken(address _protocol) public view returns(address);
function registeredPoolTokens() public view returns(address[] memory);
function supportedRewardTokens() public view returns(address[] memory);
function poolTokenBalanceChanged(address user) public {
address token = _msgSender();
require(isPoolToken(token), "RewardDistributions: PoolToken is not registered");
_updateRewardBalance(user, rewardDistributions.length);
uint256 newAmount = PoolToken(token).distributionBalanceOf(user);
rewardBalances[user].shares[token] = newAmount;
}
function withdrawReward() public returns(uint256[] memory) {
return withdrawReward(supportedRewardTokens());
}
/**
* @notice Withdraw reward tokens for user
* @param rewardTokens Array of tokens to withdraw
*/
function withdrawReward(address[] memory rewardTokens)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256[] memory)
{
address user = _msgSender();
uint256[] memory rAmounts = new uint256[](rewardTokens.length);
updateRewardBalance(user);
for(uint256 i=0; i < rewardTokens.length; i++) {
rAmounts[i] = _withdrawReward(user, rewardTokens[i]);
}
return rAmounts;
}
// function withdrawReward(address rewardToken)
// public operationAllowed(IAccessModule.Operation.Withdraw)
// returns(uint256){
// address user = _msgSender();
// updateRewardBalance(user);
// return _withdrawReward(user, rewardToken);
// }
function withdrawReward(address poolToken, address rewardToken)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256){
address user = _msgSender();
updateRewardBalance(user);
return _withdrawReward(user, poolToken, rewardToken);
}
// function rewardBalanceOf(address user, address[] memory rewardTokens) public view returns(uint256[] memory) {
// uint256[] memory amounts = new uint256[](rewardTokens.length);
// address[] memory poolTokens = registeredPoolTokens();
// for(uint256 i=0; i < rewardTokens.length; i++) {
// for(uint256 j=0; j < poolTokens.length; j++) {
// amounts[i] = amounts[i].add(rewardBalanceOf(user, poolTokens[j], rewardTokens[i]));
// }
// }
// return amounts;
// }
// function rewardBalanceOf(address user, address poolToken, address[] memory rewardTokens) public view returns(uint256[] memory) {
// uint256[] memory amounts = new uint256[](rewardTokens.length);
// for(uint256 i=0; i < rewardTokens.length; i++) {
// amounts[i] = rewardBalanceOf(user, poolToken, rewardTokens[i]);
// }
// return amounts;
// }
function rewardBalanceOf(address user, address poolToken, address rewardToken) public view returns(uint256 amounts) {
RewardBalance storage rb = rewardBalances[user];
UserProtocolRewards storage upr = rb.rewardsByProtocol[poolToken];
uint256 balance = upr.amounts[rewardToken];
uint256 next = rb.nextDistribution;
while (next < rewardDistributions.length) {
RewardTokenDistribution storage d = rewardDistributions[next];
next++;
uint256 sh = rb.shares[d.poolToken];
if (sh == 0 || poolToken != d.poolToken) continue;
uint256 distrAmount = d.amounts[rewardToken];
balance = balance.add(distrAmount.mul(sh).div(d.totalShares));
}
return balance;
}
/**
* @notice Updates user balance
* @param user User address
*/
function updateRewardBalance(address user) public {
_updateRewardBalance(user, rewardDistributions.length);
}
/**
* @notice Updates user balance
* @param user User address
* @param toDistribution Index of distribution next to the last one, which should be processed
*/
function updateRewardBalance(address user, uint256 toDistribution) public {
_updateRewardBalance(user, toDistribution);
}
function distributeReward(address _protocol) internal {
(address[] memory _tokens, uint256[] memory _amounts) = IDefiProtocol(_protocol).claimRewards();
if(_tokens.length > 0) {
address poolToken = poolTokenByProtocol(_protocol);
distributeReward(poolToken, _tokens, _amounts);
}
}
function storedRewardBalance(address user, address poolToken, address rewardToken) public view
returns(uint256 nextDistribution, uint256 poolTokenShares, uint256 storedReward) {
RewardBalance storage rb = rewardBalances[user];
nextDistribution = rb.nextDistribution;
poolTokenShares = rb.shares[poolToken];
storedReward = rb.rewardsByProtocol[poolToken].amounts[rewardToken];
}
function rewardDistribution(uint256 num) public view returns(address poolToken, uint256 totalShares, address[] memory rewardTokens, uint256[] memory amounts){
RewardTokenDistribution storage d = rewardDistributions[num];
poolToken = d.poolToken;
totalShares = d.totalShares;
rewardTokens = d.rewardTokens;
amounts = new uint256[](rewardTokens.length);
for(uint256 i=0; i < rewardTokens.length; i++) {
address tkn = rewardTokens[i];
amounts[i] = d.amounts[tkn];
}
}
function rewardDistributionCount() public view returns(uint256){
return rewardDistributions.length;
}
/**
* @notice Create reward distribution
*/
function distributeReward(address poolToken, address[] memory rewardTokens, uint256[] memory amounts) internal {
rewardDistributions.push(RewardTokenDistribution({
poolToken: poolToken,
totalShares: PoolToken(poolToken).distributionTotalSupply(),
rewardTokens:rewardTokens
}));
uint256 idx = rewardDistributions.length - 1;
RewardTokenDistribution storage rd = rewardDistributions[idx];
for(uint256 i = 0; i < rewardTokens.length; i++) {
rd.amounts[rewardTokens[i]] = amounts[i];
emit RewardDistribution(poolToken, rewardTokens[i], amounts[i], rd.totalShares);
}
}
function _withdrawReward(address user, address rewardToken) internal returns(uint256) {
address[] memory poolTokens = registeredPoolTokens();
uint256 totalAmount;
for(uint256 i=0; i < poolTokens.length; i++) {
address poolToken = poolTokens[i];
uint256 amount = rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken];
if(amount > 0){
totalAmount = totalAmount.add(amount);
rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken] = 0;
IDefiProtocol protocol = IDefiProtocol(protocolByPoolToken(poolToken));
protocol.withdrawReward(rewardToken, user, amount);
}
}
if(totalAmount > 0) {
emit RewardWithdraw(user, rewardToken, totalAmount);
}
return totalAmount;
}
function _withdrawReward(address user, address poolToken, address rewardToken) internal returns(uint256) {
uint256 amount = rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken];
require(amount > 0, "RewardDistributions: nothing to withdraw");
rewardBalances[user].rewardsByProtocol[poolToken].amounts[rewardToken] = 0;
IDefiProtocol protocol = IDefiProtocol(protocolByPoolToken(poolToken));
protocol.withdrawReward(rewardToken, user, amount);
emit RewardWithdraw(user, rewardToken, amount);
return amount;
}
function _updateRewardBalance(address user, uint256 toDistribution) internal {
require(toDistribution <= rewardDistributions.length, "RewardDistributions: toDistribution index is too high");
RewardBalance storage rb = rewardBalances[user];
uint256 next = rb.nextDistribution;
if(next >= toDistribution) return;
if(next == 0 && rewardDistributions.length > 0){
//This might be a new user, if so we can skip previous distributions
address[] memory poolTokens = registeredPoolTokens();
bool hasDeposit;
for(uint256 i=0; i< poolTokens.length; i++){
address poolToken = poolTokens[i];
if(rb.shares[poolToken] != 0) {
hasDeposit = true;
break;
}
}
if(!hasDeposit){
rb.nextDistribution = rewardDistributions.length;
return;
}
}
while (next < toDistribution) {
RewardTokenDistribution storage d = rewardDistributions[next];
next++;
uint256 sh = rb.shares[d.poolToken];
if (sh == 0) continue;
UserProtocolRewards storage upr = rb.rewardsByProtocol[d.poolToken];
for (uint256 i=0; i < d.rewardTokens.length; i++) {
address rToken = d.rewardTokens[i];
uint256 distrAmount = d.amounts[rToken];
upr.amounts[rToken] = upr.amounts[rToken].add(distrAmount.mul(sh).div(d.totalShares));
}
}
rb.nextDistribution = next;
}
function isPoolToken(address token) internal view returns(bool);
}
// File: contracts\modules\savings\SavingsModule.sol
pragma solidity ^0.5.12;
contract SavingsModule is Module, AccessChecker, RewardDistributions, CapperRole {
uint256 constant MAX_UINT256 = uint256(-1);
uint256 public constant DISTRIBUTION_AGGREGATION_PERIOD = 24*60*60;
event ProtocolRegistered(address protocol, address poolToken);
event YieldDistribution(address indexed poolToken, uint256 amount);
event DepositToken(address indexed protocol, address indexed token, uint256 dnAmount);
event Deposit(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee);
event WithdrawToken(address indexed protocol, address indexed token, uint256 dnAmount);
event Withdraw(address indexed protocol, address indexed user, uint256 nAmount, uint256 nFee);
event UserCapEnabledChange(bool enabled);
event UserCapChanged(address indexed protocol, address indexed user, uint256 newCap);
event DefaultUserCapChanged(address indexed protocol, uint256 newCap);
event ProtocolCapEnabledChange(bool enabled);
event ProtocolCapChanged(address indexed protocol, uint256 newCap);
event VipUserEnabledChange(bool enabled);
event VipUserChanged(address indexed protocol, address indexed user, bool isVip);
using SafeERC20 for IERC20;
using SafeMath for uint256;
struct ProtocolInfo {
PoolToken poolToken;
uint256 previousBalance;
uint256 lastRewardDistribution;
address[] supportedRewardTokens;
mapping(address => uint256) userCap; //Limit of pool tokens which can be minted for a user during deposit
uint256 withdrawAllSlippage; //Allowed slippage for withdrawAll function in wei
mapping(address=>bool) isVipUser;
}
struct TokenData {
uint8 decimals;
}
address[] registeredTokens;
IDefiProtocol[] registeredProtocols;
address[] registeredRewardTokens;
mapping(address => TokenData) tokens;
mapping(address => ProtocolInfo) protocols; //Mapping of protocol to data we need to calculate APY and do distributions
mapping(address => address) poolTokenToProtocol; //Mapping of pool tokens to protocols
mapping(address => bool) private rewardTokenRegistered; //marks registered reward tokens
bool public userCapEnabled;
bool public protocolCapEnabled;
mapping(address=>uint256) public defaultUserCap;
mapping(address=>uint256) public protocolCap;
bool public vipUserEnabled; // Enable VIP user (overrides protocol cap)
function initialize(address _pool) public initializer {
Module.initialize(_pool);
CapperRole.initialize(_msgSender());
}
function setUserCapEnabled(bool _userCapEnabled) public onlyCapper {
userCapEnabled = _userCapEnabled;
emit UserCapEnabledChange(userCapEnabled);
}
// function setUserCap(address _protocol, address user, uint256 cap) public onlyCapper {
// protocols[_protocol].userCap[user] = cap;
// emit UserCapChanged(_protocol, user, cap);
// }
// function setUserCap(address _protocol, address[] calldata users, uint256[] calldata caps) external onlyCapper {
// require(users.length == caps.length, "SavingsModule: arrays length not match");
// for(uint256 i=0; i < users.length; i++) {
// protocols[_protocol].userCap[users[i]] = caps[i];
// emit UserCapChanged(_protocol, users[i], caps[i]);
// }
// }
function setVipUserEnabled(bool _vipUserEnabled) public onlyCapper {
vipUserEnabled = _vipUserEnabled;
emit VipUserEnabledChange(_vipUserEnabled);
}
function setVipUser(address _protocol, address user, bool isVip) public onlyCapper {
protocols[_protocol].isVipUser[user] = isVip;
emit VipUserChanged(_protocol, user, isVip);
}
function setDefaultUserCap(address _protocol, uint256 cap) public onlyCapper {
defaultUserCap[_protocol] = cap;
emit DefaultUserCapChanged(_protocol, cap);
}
function setProtocolCapEnabled(bool _protocolCapEnabled) public onlyCapper {
protocolCapEnabled = _protocolCapEnabled;
emit ProtocolCapEnabledChange(protocolCapEnabled);
}
function setProtocolCap(address _protocol, uint256 cap) public onlyCapper {
protocolCap[_protocol] = cap;
emit ProtocolCapChanged(_protocol, cap);
}
function setWithdrawAllSlippage(address _protocol, uint256 slippageWei) public onlyOwner {
protocols[_protocol].withdrawAllSlippage = slippageWei;
}
function registerProtocol(IDefiProtocol protocol, PoolToken poolToken) public onlyOwner {
uint256 i;
for (i = 0; i < registeredProtocols.length; i++){
if (address(registeredProtocols[i]) == address(protocol)) revert("SavingsModule: protocol already registered");
}
registeredProtocols.push(protocol);
protocols[address(protocol)] = ProtocolInfo({
poolToken: poolToken,
previousBalance: protocol.normalizedBalance(),
lastRewardDistribution: 0,
supportedRewardTokens: protocol.supportedRewardTokens(),
withdrawAllSlippage:0
});
for(i=0; i < protocols[address(protocol)].supportedRewardTokens.length; i++) {
address rtkn = protocols[address(protocol)].supportedRewardTokens[i];
if(!rewardTokenRegistered[rtkn]){
rewardTokenRegistered[rtkn] = true;
registeredRewardTokens.push(rtkn);
}
}
poolTokenToProtocol[address(poolToken)] = address(protocol);
address[] memory supportedTokens = protocol.supportedTokens();
for (i = 0; i < supportedTokens.length; i++) {
address tkn = supportedTokens[i];
if (!isTokenRegistered(tkn)){
registeredTokens.push(tkn);
tokens[tkn].decimals = ERC20Detailed(tkn).decimals();
}
}
uint256 normalizedBalance= protocols[address(protocol)].previousBalance;
if(normalizedBalance > 0) {
uint256 ts = poolToken.totalSupply();
if(ts < normalizedBalance) {
poolToken.mint(_msgSender(), normalizedBalance.sub(ts));
}
}
emit ProtocolRegistered(address(protocol), address(poolToken));
}
/**
* @notice Only adding reward tokens is correctly supported now (!!!)
*/
function updateProtocolRewardTokens(IDefiProtocol protocol) public onlyOwner {
ProtocolInfo storage pi = protocols[address(protocol)];
pi.supportedRewardTokens = protocol.supportedRewardTokens();
for(uint256 i=0; i < pi.supportedRewardTokens.length; i++) {
address rtkn = pi.supportedRewardTokens[i];
if(!rewardTokenRegistered[rtkn]){
rewardTokenRegistered[rtkn] = true;
registeredRewardTokens.push(rtkn);
}
}
emit ProtocolRegistered(address(protocol), poolTokenByProtocol(address(protocol)));
//TODO: cleanup registeredRewardTokens if reward tokens removed
}
// function unregisterProtocol(address _protocol) public onlyOwner {
// address poolToken = address(protocols[_protocol].poolToken);
// delete protocols[_protocol];
// delete poolTokenToProtocol[poolToken];
// address[] memory supportedRewardTokens = IDefiProtocol(_protocol).supportedRewardTokens();
// for(uint256 i=0; i < supportedRewardTokens.length; i++) {
// address rtkn = supportedRewardTokens[i];
// //TODO check if this token used by other protocols
// rewardTokenRegistered[rtkn] = false;
// // Remove reward token from registered array
// for(uint256 j=0; j< registeredRewardTokens.length; j++){
// if(registeredRewardTokens[j] == rtkn) {
// if(j != registeredRewardTokens.length-1){
// registeredRewardTokens[j] = registeredRewardTokens[registeredRewardTokens.length-1];
// }
// registeredRewardTokens.pop();
// }
// }
// }
// }
/**
* @notice Deposit tokens to several protocols
* @param _protocols Array of protocols to deposit tokens (each protocol only once)
* @param _tokens Array of tokens to deposit
* @param _dnAmounts Array of amounts (denormalized to token decimals)
*/
function deposit(address[] memory _protocols, address[] memory _tokens, uint256[] memory _dnAmounts)
public operationAllowed(IAccessModule.Operation.Deposit)
returns(uint256[] memory)
{
require(_protocols.length == _tokens.length && _tokens.length == _dnAmounts.length, "SavingsModule: size of arrays does not match");
uint256[] memory ptAmounts = new uint256[](_protocols.length);
for (uint256 i=0; i < _protocols.length; i++) {
address[] memory tkns = new address[](1);
tkns[0] = _tokens[i];
uint256[] memory amnts = new uint256[](1);
amnts[0] = _dnAmounts[i];
ptAmounts[i] = deposit(_protocols[i], tkns, amnts);
}
return ptAmounts;
}
/**
* @notice Deposit tokens to a protocol
* @param _protocol Protocol to deposit tokens
* @param _tokens Array of tokens to deposit
* @param _dnAmounts Array of amounts (denormalized to token decimals)
*/
function deposit(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts)
public operationAllowed(IAccessModule.Operation.Deposit)
returns(uint256)
{
//distributeRewardIfRequired(_protocol);
uint256 nAmount;
for (uint256 i=0; i < _tokens.length; i++) {
nAmount = nAmount.add(normalizeTokenAmount(_tokens[i], _dnAmounts[i]));
}
uint256 nBalanceBefore = distributeYieldInternal(_protocol);
depositToProtocol(_protocol, _tokens, _dnAmounts);
uint256 nBalanceAfter = updateProtocolBalance(_protocol);
PoolToken poolToken = PoolToken(protocols[_protocol].poolToken);
uint256 nDeposit = nBalanceAfter.sub(nBalanceBefore);
uint256 cap;
if(userCapEnabled) {
cap = userCap(_protocol, _msgSender());
}
uint256 fee;
if(nAmount > nDeposit) {
fee = nAmount - nDeposit;
poolToken.mint(_msgSender(), nDeposit);
} else {
fee = 0;
poolToken.mint(_msgSender(), nAmount);
uint256 yield = nDeposit - nAmount;
if (yield > 0) {
//Additional Yield received from protocol (because of lottery, or something)
createYieldDistribution(poolToken, yield);
}
}
if(protocolCapEnabled) {
if( !(vipUserEnabled && protocols[_protocol].isVipUser[_msgSender()]) ) {
uint256 ptTS = poolToken.totalSupply();
require(ptTS <= protocolCap[_protocol], "SavingsModule: deposit exeeds protocols cap");
}
}
if(userCapEnabled) {
//uint256 actualAmount = nAmount.sub(fee); //Had to remove this because of stack too deep err
require(cap >= nAmount.sub(fee), "SavingsModule: deposit exeeds user cap");
// cap = cap - nAmount.sub(fee);
//protocols[_protocol].userCap[_msgSender()] = cap;
// emit UserCapChanged(_protocol, _msgSender(), cap);
}
emit Deposit(_protocol, _msgSender(), nAmount, fee);
return nDeposit;
}
function depositToProtocol(address _protocol, address[] memory _tokens, uint256[] memory _dnAmounts) internal {
require(_tokens.length == _dnAmounts.length, "SavingsModule: count of tokens does not match count of amounts");
for (uint256 i=0; i < _tokens.length; i++) {
address tkn = _tokens[i];
IERC20(tkn).safeTransferFrom(_msgSender(), _protocol, _dnAmounts[i]);
IDefiProtocol(_protocol).handleDeposit(tkn, _dnAmounts[i]);
emit DepositToken(_protocol, tkn, _dnAmounts[i]);
}
}
/**
* Withdraw tokens from protocol (all underlying tokens proportiaonally)
* @param _protocol Protocol to withdraw from
* @param nAmount Normalized (to 18 decimals) amount to withdraw
* @return Amount of PoolToken burned from user
*/
function withdrawAll(address _protocol, uint256 nAmount)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256)
{
//distributeRewardIfRequired(_protocol);
PoolToken poolToken = PoolToken(protocols[_protocol].poolToken);
uint256 nBalanceBefore = distributeYieldInternal(_protocol);
withdrawFromProtocolProportionally(_msgSender(), IDefiProtocol(_protocol), nAmount, nBalanceBefore);
uint256 nBalanceAfter = updateProtocolBalance(_protocol);
uint256 yield;
uint256 actualAmount;
if(nBalanceAfter.add(nAmount) > nBalanceBefore) {
yield = nBalanceAfter.add(nAmount).sub(nBalanceBefore);
actualAmount = nAmount;
}else{
actualAmount = nBalanceBefore.sub(nBalanceAfter);
require(actualAmount.sub(nAmount) <= protocols[_protocol].withdrawAllSlippage, "SavingsModule: withdrawal fee exeeds slippage");
}
// if(userCapEnabled){
// uint256 cap = userCap(_protocol, _msgSender());
// cap = cap.add(actualAmount);
// protocols[_protocol].userCap[_msgSender()] = cap;
// emit UserCapChanged(_protocol, _msgSender(), cap);
// }
poolToken.burnFrom(_msgSender(), actualAmount);
emit Withdraw(_protocol, _msgSender(), actualAmount, 0);
if (yield > 0) {
//Additional Yield received from protocol (because of lottery, or something)
createYieldDistribution(poolToken, yield);
}
return actualAmount;
}
/**
* Withdraw token from protocol
* @param _protocol Protocol to withdraw from
* @param token Token to withdraw
* @param dnAmount Amount to withdraw (denormalized)
* @param maxNAmount Max amount of PoolToken to burn
* @return Amount of PoolToken burned from user
*/
function withdraw(address _protocol, address token, uint256 dnAmount, uint256 maxNAmount)
public operationAllowed(IAccessModule.Operation.Withdraw)
returns(uint256){
//distributeRewardIfRequired(_protocol);
uint256 nAmount = normalizeTokenAmount(token, dnAmount);
uint256 nBalanceBefore = distributeYieldInternal(_protocol);
withdrawFromProtocolOne(_msgSender(), IDefiProtocol(_protocol), token, dnAmount);
uint256 nBalanceAfter = updateProtocolBalance(_protocol);
uint256 yield;
uint256 actualAmount;
uint256 fee;
if(nBalanceAfter.add(nAmount) > nBalanceBefore) {
yield = nBalanceAfter.add(nAmount).sub(nBalanceBefore);
actualAmount = nAmount;
}else{
actualAmount = nBalanceBefore.sub(nBalanceAfter);
if (actualAmount > nAmount) fee = actualAmount-nAmount;
}
require(maxNAmount == 0 || actualAmount <= maxNAmount, "SavingsModule: provided maxNAmount is too low");
// if(userCapEnabled){
// uint256 cap = userCap(_protocol, _msgSender());
// cap = cap.add(actualAmount);
// protocols[_protocol].userCap[_msgSender()] = cap;
// emit UserCapChanged(_protocol, _msgSender(), cap);
// }
PoolToken poolToken = PoolToken(protocols[_protocol].poolToken);
poolToken.burnFrom(_msgSender(), actualAmount);
emit WithdrawToken(_protocol, token, dnAmount);
emit Withdraw(_protocol, _msgSender(), actualAmount, fee);
if (yield > 0) {
//Additional Yield received from protocol (because of lottery, or something)
createYieldDistribution(poolToken, yield);
}
return actualAmount;
}
/**
* @notice Distributes yield. May be called by bot, if there was no deposits/withdrawals
*/
function distributeYield() public {
for(uint256 i=0; i<registeredProtocols.length; i++) {
distributeYieldInternal(address(registeredProtocols[i]));
}
}
/**
* @notice Distributes reward tokens. May be called by bot, if there was no deposits/withdrawals
*/
function distributeRewards() public {
for(uint256 i=0; i<registeredProtocols.length; i++) {
distributeRewardIfRequired(address(registeredProtocols[i]));
}
}
// function distributeRewards(address _protocol) public {
// distributeRewardIfRequired(_protocol);
// }
function distributeRewardsForced(address _protocol) public onlyOwner {
ProtocolInfo storage pi = protocols[_protocol];
pi.lastRewardDistribution = now;
distributeReward(_protocol);
}
function userCap(address _protocol, address user) public view returns(uint256) {
// uint256 cap = protocols[_protocol].userCap[user];
// if(cap == 0){
// uint256 balance = protocols[_protocol].poolToken.balanceOf(user);
// if(balance == 0) cap = defaultUserCap[_protocol];
// }
uint256 balance = protocols[_protocol].poolToken.balanceOf(user);
uint256 cap;
if(balance < defaultUserCap[_protocol]) {
cap = defaultUserCap[_protocol] - balance;
}
return cap;
}
function isVipUser(address _protocol, address user) view public returns(bool){
return protocols[_protocol].isVipUser[user];
}
function poolTokenByProtocol(address _protocol) public view returns(address) {
return address(protocols[_protocol].poolToken);
}
function protocolByPoolToken(address _poolToken) public view returns(address) {
return poolTokenToProtocol[_poolToken];
}
function rewardTokensByProtocol(address _protocol) public view returns(address[] memory) {
return protocols[_protocol].supportedRewardTokens;
}
function registeredPoolTokens() public view returns(address[] memory poolTokens) {
poolTokens = new address[](registeredProtocols.length);
for(uint256 i=0; i<poolTokens.length; i++){
poolTokens[i] = address(protocols[address(registeredProtocols[i])].poolToken);
}
}
function supportedProtocols() public view returns(IDefiProtocol[] memory) {
return registeredProtocols;
}
function supportedRewardTokens() public view returns(address[] memory) {
return registeredRewardTokens;
}
function withdrawFromProtocolProportionally(address beneficiary, IDefiProtocol protocol, uint256 nAmount, uint256 currentProtocolBalance) internal {
uint256[] memory balances = protocol.balanceOfAll();
uint256[] memory amounts = new uint256[](balances.length);
address[] memory _tokens = protocol.supportedTokens();
for (uint256 i = 0; i < amounts.length; i++) {
amounts[i] = balances[i].mul(nAmount).div(currentProtocolBalance);
emit WithdrawToken(address(protocol), _tokens[i], amounts[i]);
}
protocol.withdraw(beneficiary, amounts);
}
function withdrawFromProtocolOne(address beneficiary, IDefiProtocol protocol, address token, uint256 dnAmount) internal {
protocol.withdraw(beneficiary, token, dnAmount);
}
/**
* @notice Calculates difference from previous action with a protocol and distributes yield
* @dev MUST call this BEFORE deposit/withdraw from protocol
* @param _protocol to check
* @return Current balance of the protocol
*/
function distributeYieldInternal(address _protocol) internal returns(uint256){
uint256 currentBalance = IDefiProtocol(_protocol).normalizedBalance();
ProtocolInfo storage pi = protocols[_protocol];
PoolToken poolToken = PoolToken(pi.poolToken);
if(currentBalance > pi.previousBalance) {
uint256 yield = currentBalance.sub(pi.previousBalance);
pi.previousBalance = currentBalance;
createYieldDistribution(poolToken, yield);
}
return currentBalance;
}
function createYieldDistribution(PoolToken poolToken, uint256 yield) internal {
poolToken.distribute(yield);
emit YieldDistribution(address(poolToken), yield);
}
function distributeRewardIfRequired(address _protocol) internal {
if(!isRewardDistributionRequired(_protocol)) return;
ProtocolInfo storage pi = protocols[_protocol];
pi.lastRewardDistribution = now;
distributeReward(_protocol);
}
/**
* @notice Updates balance with result of deposit/withdraw
* @dev MUST call this AFTER deposit/withdraw from protocol
* @param _protocol to update
* @return Current balance of the protocol
*/
function updateProtocolBalance(address _protocol) internal returns(uint256){
uint256 currentBalance = IDefiProtocol(_protocol).normalizedBalance();
protocols[_protocol].previousBalance = currentBalance;
return currentBalance;
}
function isTokenRegistered(address token) private view returns(bool) {
for (uint256 i = 0; i < registeredTokens.length; i++){
if (registeredTokens[i] == token) return true;
}
return false;
}
function isPoolToken(address token) internal view returns(bool) {
for (uint256 i = 0; i < registeredProtocols.length; i++){
IDefiProtocol protocol = registeredProtocols[i];
if (address(protocols[address(protocol)].poolToken) == token) return true;
}
return false;
}
function isRewardDistributionRequired(address _protocol) internal view returns(bool) {
return now.sub(protocols[_protocol].lastRewardDistribution) > DISTRIBUTION_AGGREGATION_PERIOD;
}
function normalizeTokenAmount(address token, uint256 amount) private view returns(uint256) {
uint256 decimals = tokens[token].decimals;
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.div(10**(decimals-18));
} else if (decimals < 18) {
return amount.mul(10**(18 - decimals));
}
}
function denormalizeTokenAmount(address token, uint256 amount) private view returns(uint256) {
uint256 decimals = tokens[token].decimals;
if (decimals == 18) {
return amount;
} else if (decimals > 18) {
return amount.mul(10**(decimals-18));
} else if (decimals < 18) {
return amount.div(10**(18 - decimals));
}
}
}
// File: contracts\deploy\InvestingModule.sol
pragma solidity ^0.5.12;
contract InvestingModule is SavingsModule {
function initialize(address _pool) public initializer {
SavingsModule.initialize(_pool);
}
} | Maps PoolToken to amount of user shares participating in distributions
| mapping(address => uint256) shares; | 33,256 | [
1,
8903,
8828,
1345,
358,
3844,
434,
729,
24123,
30891,
1776,
316,
23296,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2874,
12,
2867,
516,
2254,
5034,
13,
24123,
31,
1377,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xbA5F9E64d1cCF59350Fe166Ab83EBEC735A38db6/sources/contracts/Autolend/Manager/LendManagerInterface.sol | * @title MetaLend's manager event interface @author MetaLend @notice defines the events emitted during interaction @dev use this with proxy and implementation to emit events/ | interface LendManagerEventInterface {
event NewLendMediator(address indexed user, address indexed mediator);
event NewLendMediatorImplementation(address indexed previous, address indexed next);
event NewRoyaltiesPercentage(uint256 indexed previous, uint256 indexed next);
event NewRoyaltiesReceiver(address indexed previous, address indexed next);
event NewOfferSigner(address indexed previous, address indexed next);
}
}
| 9,311,199 | [
1,
2781,
48,
409,
1807,
3301,
871,
1560,
225,
6565,
48,
409,
225,
11164,
326,
2641,
17826,
4982,
13581,
225,
999,
333,
598,
2889,
471,
4471,
358,
3626,
2641,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
511,
409,
1318,
1133,
1358,
288,
203,
565,
871,
1166,
48,
409,
13265,
10620,
12,
2867,
8808,
729,
16,
1758,
8808,
6735,
10620,
1769,
203,
565,
871,
1166,
48,
409,
13265,
10620,
13621,
12,
2867,
8808,
2416,
16,
1758,
8808,
1024,
1769,
203,
203,
565,
871,
1166,
54,
13372,
2390,
606,
16397,
12,
11890,
5034,
8808,
2416,
16,
2254,
5034,
8808,
1024,
1769,
203,
203,
565,
871,
1166,
54,
13372,
2390,
606,
12952,
12,
2867,
8808,
2416,
16,
1758,
8808,
1024,
1769,
203,
203,
565,
871,
1166,
10513,
15647,
12,
2867,
8808,
2416,
16,
1758,
8808,
1024,
1769,
203,
97,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.6.0;
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol";
import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol";
// The Agents Contract must be deployed only by the Municipality to create and delete citizens, trucks and disposal stations
contract Agents is Ownable {
using SafeMath for uint;
using SafeMath for int;
uint start; // Define a variable that each year is set equal to 1st January
bool alreadySet; // Define a varible equal to false by default, so that the "setBeginningYear" function cannot be invoked twice in a year
// Define a function the Municipality calls at the beginning of each year to set start = 1st January
function setBeginningYear () public onlyOwner returns (uint) {
require(alreadySet == false, "The function has already been called");
start = now;
alreadySet = true;
return start;
}
// Define a function to check which is the starting day of the year, to check that the Municipality has correctly set it
function showStartTime () public view returns (uint) {return start;}
// Define a struct to store relavant data about each citizen
struct Citizen {
string name; // Full name
uint family; // Number of household members
uint house; // Size of the house (mq)
uint weight; // Total weight of waste produced last year
uint TARI; // Amount of TARI due (initialized as 0 and computed by the Municipality)
uint totalRecyclableWaste; // Total amount of recyclable waste produced during the year (in kg)
uint totalNonRecyclableWaste; // Total amount of non-recyclable waste produced during the year (in kg)
bool payTARI; // True if a specific citizen has already paid the TARI, False otherwise
bool active; // Boolean to guarantee the existence and uniqueness of the citizen (True once this struct is created)
}
// Define a struct to store relavant data about each truck
struct Truck {
uint truck_number; // Truck Number (given when created by the Municipality)
uint weight; // Total weight the truck carries before dumping its cargo at a disposal station
bool waste; // Type of waste (recyclable or not) that the truck is carrying
bool active; // Boolean to guarantee the existence and uniqueness of the truck (True once this struct is created)
}
// Define a struct to store relavant data about each disposal station
struct Station {
uint station_number; // Station Number
uint weight; // Cumulative sum of the weight of trash accumulated at the station during the year
int latitude; // Gps coordinates of the station (latitude)
int longitude; // Gps coordinates of the station (longitude)
bool waste; // Type of waste (recyclable or not) that the station disposes
bool active; // Boolean to guarantee the existence and uniqueness of the station (True once this struct is created)
}
// Define 3 mappings so that each truck, citizen and station is uniquely associated to an Ethereum address
mapping(address => Truck) public trucks;
mapping(address => Citizen) public citizens;
mapping(address => Station) public stations;
// Define an event to signal to the blockchain that a citizen has been "created" (has been added to the mapping "citizens")
uint citizenCounter;
event CitizenBorn(address payable indexed _citizen, bool payTARI);
// Define an event to signal to the blockchain that a station has been "created" (has been added to the mapping "stations")
uint stationCounter;
uint stationNumber;
event StationBorn(address indexed _station, int _long, int _lat);
// Define an event to signal to the blockchain that a truck has been "created" (has been added to the mapping "trucks")
uint truckCounter;
uint truckNumber;
event TruckBorn(address indexed _truck);
// Define functions to check the total number of citizens, trucks and stations
function numberT() public view returns (uint) {return truckCounter;}
function numberC() public view returns (uint) {return citizenCounter;}
function numberS() public view returns (uint) {return stationCounter;}
// All the following functions can be invoked only by the owner of this contract, that is the Municipality
// Define a function to add a new citizen to the system, and emit the respective event
function createCitizen(address payable _address, string memory _name,
uint _family, uint _house, uint _w) public onlyOwner {
require(citizens[_address].active == false); // Make sure the citizen is not already present in the "citizens" mapping
citizenCounter++; // Increase the total counter of citizens present in the mapping
// Create the struct: TARI due, non-rec. and rec. waste are set to 0; payTARI is set to False and the citizen is declared as active
citizens[_address] = Citizen(
_name,
_family,
_house,
_w,
0,
0,
0,
false,
true);
emit CitizenBorn(_address, false);
}
// Define a function to remove a specific citizen from the system
function deleteCitizen(address _address) public onlyOwner {
require(citizens[_address].active == true); // Make sure the citizen exists in the "citizens" mapping
delete citizens[_address]; // Remove the address from the mapping
citizenCounter--; // Decrease the total citizens counter
}
// Define a function to add a new truck to the system, and emit the respective event
function createTruck(address _address, bool _recycle) public onlyOwner {
require(trucks[_address].active == false); // Make sure the truck is not already present in the "trucks" mapping
truckCounter++; // Increase the total counter of trucks present in the mapping
truckNumber++;
trucks[_address] = Truck(truckNumber, 0, _recycle, true); // Create the Truck struct and add it to the mapping
emit TruckBorn(_address);
}
// Define a function to remove a specific truck from the system
function deleteTruck(address _address) public onlyOwner {
require(trucks[_address].active == true); // Make sure the truck exists in the "trucks" mapping
delete trucks[_address]; // Remove the address from the mapping
truckCounter--; // Decrease the total trucks counter
}
// Define a function to add a new station to the system, and emit the respective event
function createStation(address _address, bool _recycle, int _lat, int _long) public onlyOwner {
require(stations[_address].active == false); // Make sure the station is not already present in the "stations" mapping
stationCounter++; // Increase the total counter of stations present in the mapping
stationNumber++;
stations[_address] = Station(stationNumber, 0, _lat, _long, _recycle, true); // Create the Station struct and add it to the mapping
emit StationBorn(_address, _long, _lat);
}
// Define a function to remove a specific station from the system
function deleteStation(address _address) public onlyOwner {
require(stations[_address].active == true); // Make sure the station exists in the "stations" mapping
delete stations[_address]; // Remove the address from the mapping
stationCounter--; // Decrease the total stations counter
}
}
| Make sure the citizen exists in the "citizens" mapping
| require(citizens[_address].active == true); | 1,069,618 | [
1,
6464,
3071,
326,
276,
305,
452,
275,
1704,
316,
326,
315,
71,
305,
452,
773,
6,
2874,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
2583,
12,
71,
305,
452,
773,
63,
67,
2867,
8009,
3535,
422,
638,
1769,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
*
* Metaverse Travel Agency
* =======================
* https://themta.io
* twiter: @themtaofficial
*
* MetaHelmet
* ----------
*/
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
/**
* @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;
}
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
/**
* @dev 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;
}
}
}
/**
* @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;
string private baseURI = "";
// 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 baseURI;
}
function _setBaseURI(string memory baseURI_) internal {
baseURI = baseURI_;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
/**
* @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);
}
}
contract Metahelmet is ERC721Enumerable, Ownable {
using SafeMath for uint256;
string public METAHELMET_PROVENANCE = "";
uint256 public constant PRICE = 101010000000000000;
uint256 public constant MAX_METAHELMETS = 10101;
uint256 public constant MAX_PURCHASE = 7;
bool public saleIsActive = false;
mapping (address => uint256) public whitelistMinted;
address public WHITELIST_SIGNER;
event Merge(uint256 indexed tokenId, address indexed nftContract, uint256 indexed nftId);
event Unmerge(uint256 indexed tokenId);
constructor() ERC721("MetaHelmet", "MTAH") {}
function withdraw() public onlyOwner {
address payable sender = payable(_msgSender());
uint balance = address(this).balance;
sender.transfer(balance);
}
function toggleSale() public onlyOwner {
saleIsActive = !saleIsActive;
}
function setWhiteListSigner(address signer) public onlyOwner {
WHITELIST_SIGNER = signer;
}
/**
* Set some Metahelmets aside
*/
function reserveMetahelmets() public onlyOwner {
require(saleIsActive == false, "Impossible reserve a Metahelmet when sale is active");
uint supply = totalSupply();
for (uint i = 0; i < 21; i++) {
_safeMint(_msgSender(), supply + i);
}
}
/**
* Mint Metahelmet
*/
function mintMetahelmet(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale must be active to mint Metahelmet");
require(numberOfTokens <= MAX_PURCHASE, "Can only mint 7 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_METAHELMETS, "Purchase would exceed max supply of Metahelmets");
require(PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
for(uint i = 0; i < numberOfTokens; i++) {
uint mintIndex = totalSupply();
if (totalSupply() < MAX_METAHELMETS) {
_safeMint(_msgSender(), mintIndex);
}
}
}
/**
* PreMint: Only people in whitelist can mint
*/
function preMintMetahelmet(uint256 numberOfTokens, uint max, bytes memory signature) public payable {
bytes32 hash;
require(WHITELIST_SIGNER != address(0), "Pre-Mint is not available yet");
require(saleIsActive == false, "Impossible Pre-Mint a Matahelmet when sale is active");
require(numberOfTokens <= MAX_PURCHASE, "Can only mint 7 tokens at a time");
require(totalSupply().add(numberOfTokens) <= MAX_METAHELMETS, "Purchase would exceed max supply of Metahelmets");
require(PRICE.mul(numberOfTokens) <= msg.value, "Ether value sent is not correct");
/*
* keccak256(address,number);
*/
hash = keccak256(abi.encodePacked(_msgSender(), max));
/*
* Check Signature
*/
require(recover(hash,signature) == WHITELIST_SIGNER, "Invalid Signature");
/*
* Check max min reached
*/
require(whitelistMinted[_msgSender()].add(numberOfTokens) <= max, "Max mint reached");
/*
* Update total minted in preMint state
*/
whitelistMinted[_msgSender()] = whitelistMinted[_msgSender()].add(numberOfTokens);
uint supply = totalSupply();
for(uint i = 0; i < numberOfTokens; i++) {
_safeMint(_msgSender(), supply+i);
}
}
/**
* Set provenance once it's calculated
*/
function setProvenanceHash(string memory provenanceHash) public onlyOwner {
METAHELMET_PROVENANCE = provenanceHash;
}
function setBaseURI(string memory baseURI) public onlyOwner {
_setBaseURI(baseURI);
}
function merge(uint256 _tokenId, IERC721 _nftContract, uint256 _nftId) public {
require(ownerOf(_tokenId) == _msgSender(), "Only owner can merge tokens");
require(_nftContract.ownerOf(_nftId) == _msgSender(), "Only owner can merge tokens");
emit Merge(_tokenId, address(_nftContract), _nftId);
}
function unmerge(uint256 _tokenId) public {
require(ownerOf(_tokenId) == _msgSender(), "Only owner can unmerge tokens");
emit Unmerge(_tokenId);
}
function recover(bytes32 _hash, bytes memory _signed) internal pure returns(address) {
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r:= mload(add(_signed,32))
s:= mload(add(_signed,64))
v:= and(mload(add(_signed,65)) ,255)
}
return ecrecover(_hash,v,r,s);
}
} | * @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())) : "";
}
| 5,832,131 | [
1,
9704,
288,
45,
654,
39,
27,
5340,
2277,
17,
2316,
3098,
5496,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
1147,
3098,
12,
11890,
5034,
1147,
548,
13,
1071,
1476,
5024,
3849,
1135,
261,
1080,
3778,
13,
288,
203,
3639,
2583,
24899,
1808,
12,
2316,
548,
3631,
315,
654,
39,
27,
5340,
2277,
30,
3699,
843,
364,
1661,
19041,
1147,
8863,
203,
203,
3639,
533,
3778,
1026,
3098,
67,
273,
389,
1969,
3098,
5621,
203,
3639,
327,
1731,
12,
1969,
3098,
67,
2934,
2469,
405,
374,
692,
533,
12,
21457,
18,
3015,
4420,
329,
12,
1969,
3098,
16,
1147,
548,
18,
10492,
1435,
3719,
294,
1408,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
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.
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
// solium-disable-next-line security/no-inline-assembly
assembly { size := extcodesize(addr) }
return size > 0;
}
}
library UrlStr {
// generate url by tokenId
// baseUrl must end with 00000000
function generateUrl(string url,uint256 _tokenId) internal pure returns (string _url){
_url = url;
bytes memory _tokenURIBytes = bytes(_url);
uint256 base_len = _tokenURIBytes.length - 1;
_tokenURIBytes[base_len - 7] = byte(48 + _tokenId / 10000000 % 10);
_tokenURIBytes[base_len - 6] = byte(48 + _tokenId / 1000000 % 10);
_tokenURIBytes[base_len - 5] = byte(48 + _tokenId / 100000 % 10);
_tokenURIBytes[base_len - 4] = byte(48 + _tokenId / 10000 % 10);
_tokenURIBytes[base_len - 3] = byte(48 + _tokenId / 1000 % 10);
_tokenURIBytes[base_len - 2] = byte(48 + _tokenId / 100 % 10);
_tokenURIBytes[base_len - 1] = byte(48 + _tokenId / 10 % 10);
_tokenURIBytes[base_len - 0] = byte(48 + _tokenId / 1 % 10);
}
}
/**
if a ERC721 item want to mount to avatar, it must to inherit this.
*/
interface AvatarChildService {
/**
@dev if you want your contract become a avatar child, please let your contract inherit this interface
@param _tokenId1 first child token id
@param _tokenId2 second child token id
@return true will unmount first token before mount ,false will directly mount child
*/
function compareItemSlots(uint256 _tokenId1, uint256 _tokenId2) external view returns (bool _res);
}
interface AvatarService {
function updateAvatarInfo(address _owner, uint256 _tokenId, string _name, uint256 _dna) external;
function createAvatar(address _owner, string _name, uint256 _dna) external returns(uint256);
function getMountTokenIds(address _owner,uint256 _tokenId, address _avatarItemAddress) external view returns(uint256[]);
function getAvatarInfo(uint256 _tokenId) external view returns (string _name, uint256 _dna);
function getOwnedTokenIds(address _owner) external view returns(uint256[] _tokenIds);
}
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId) external view returns (bool);
}
interface ERC721 /* is ERC165 */ {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
/// Note: the ERC-165 identifier for this interface is 0x780e9d63.
interface ERC721Enumerable /* is ERC721 */ {
/// @notice Count NFTs tracked by this contract
/// @return A count of valid NFTs tracked by this contract, where each one of
/// them has an assigned and queryable owner not equal to the zero address
function totalSupply() external view returns (uint256);
/// @notice Enumerate valid NFTs
/// @dev Throws if `_index` >= `totalSupply()`.
/// @param _index A counter less than `totalSupply()`
/// @return The token identifier for the `_index`th NFT,
/// (sort order not specified)
function tokenByIndex(uint256 _index) external view returns (uint256);
/// @notice Enumerate NFTs assigned to an owner
/// @dev Throws if `_index` >= `balanceOf(_owner)` or if
/// `_owner` is the zero address, representing invalid NFTs.
/// @param _owner An address where we are interested in NFTs owned by them
/// @param _index A counter less than `balanceOf(_owner)`
/// @return The token identifier for the `_index`th NFT assigned to `_owner`,
/// (sort order not specified)
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256);
}
/// Note: the ERC-165 identifier for this interface is 0x5b5e139f.
interface ERC721Metadata /* is ERC721 */ {
/// @notice A descriptive name for a collection of NFTs in this contract
function name() external view returns (string _name);
/// @notice An abbreviated name for NFTs in this contract
function symbol() external view returns (string _symbol);
/// @notice A distinct Uniform Resource Identifier (URI) for a given asset.
/// @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
/// 3986. The URI may point to a JSON file that conforms to the "ERC721
/// Metadata JSON Schema".
function tokenURI(uint256 _tokenId) external view returns (string);
}
/// @dev Note: the ERC-165 identifier for this interface is 0x150b7a02.
interface ERC721TokenReceiver {
/// @notice Handle the receipt of an NFT
/// @dev The ERC721 smart contract calls this function on the recipient
/// after a `transfer`. This function MAY throw to revert and reject the
/// transfer. Return of other than the magic value MUST result in the
/// transaction being reverted.
/// Note: the contract address is always the message sender.
/// @param _operator The address which called `safeTransferFrom` function
/// @param _from The address which previously owned the token
/// @param _tokenId The NFT identifier which is being transferred
/// @param _data Additional data with no specified format
/// @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
/// unless throwing
function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns(bytes4);
}
/**
* @title SupportsInterfaceWithLookup
* @author Matt Condon (@shrugs)
* @dev Implements ERC165 using a lookup table.
*/
contract SupportsInterfaceWithLookup is ERC165 {
bytes4 public constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
/**
* @dev a mapping of interface id to whether or not it's supported
*/
mapping(bytes4 => bool) internal supportedInterfaces;
/**
* @dev A contract implementing SupportsInterfaceWithLookup
* implement ERC165 itself
*/
constructor()
public
{
_registerInterface(InterfaceId_ERC165);
}
/**
* @dev implement supportsInterface(bytes4) using a lookup table
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return supportedInterfaces[_interfaceId];
}
/**
* @dev private method for registering an interface
*/
function _registerInterface(bytes4 _interfaceId)
internal
{
require(_interfaceId != 0xffffffff);
supportedInterfaces[_interfaceId] = true;
}
}
/**
* @title BitGuildAccessAdmin
* @dev Allow two roles: 'owner' or 'operator'
* - owner: admin/superuser (e.g. with financial rights)
* - operator: can update configurations
*/
contract BitGuildAccessAdmin {
address public owner;
address[] public operators;
uint public MAX_OPS = 20; // Default maximum number of operators allowed
mapping(address => bool) public isOperator;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
event OperatorAdded(address operator);
event OperatorRemoved(address operator);
// @dev The BitGuildAccessAdmin constructor: sets owner 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 Throws if called by any non-operator account. Owner has all ops rights.
modifier onlyOperator {
require(
isOperator[msg.sender] || msg.sender == owner,
"Permission denied. Must be an operator or the 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),
"Invalid new owner address."
);
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
/**
* @dev Allows the current owner or operators to add operators
* @param _newOperator New operator address
*/
function addOperator(address _newOperator) public onlyOwner {
require(
_newOperator != address(0),
"Invalid new operator address."
);
// Make sure no dups
require(
!isOperator[_newOperator],
"New operator exists."
);
// Only allow so many ops
require(
operators.length < MAX_OPS,
"Overflow."
);
operators.push(_newOperator);
isOperator[_newOperator] = true;
emit OperatorAdded(_newOperator);
}
/**
* @dev Allows the current owner or operators to remove operator
* @param _operator Address of the operator to be removed
*/
function removeOperator(address _operator) public onlyOwner {
// Make sure operators array is not empty
require(
operators.length > 0,
"No operator."
);
// Make sure the operator exists
require(
isOperator[_operator],
"Not an operator."
);
// Manual array manipulation:
// - replace the _operator with last operator in array
// - remove the last item from array
address lastOperator = operators[operators.length - 1];
for (uint i = 0; i < operators.length; i++) {
if (operators[i] == _operator) {
operators[i] = lastOperator;
}
}
operators.length -= 1; // remove the last element
isOperator[_operator] = false;
emit OperatorRemoved(_operator);
}
// @dev Remove ALL operators
function removeAllOps() public onlyOwner {
for (uint i = 0; i < operators.length; i++) {
isOperator[operators[i]] = false;
}
operators.length = 0;
}
}
contract BitGuildAccessAdminExtend is BitGuildAccessAdmin {
event FrozenFunds(address target, bool frozen);
bool public isPaused = false;
mapping(address => bool) frozenAccount;
modifier whenNotPaused {
require(!isPaused);
_;
}
modifier whenPaused {
require(isPaused);
_;
}
function doPause() external whenNotPaused onlyOwner {
isPaused = true;
}
function doUnpause() external whenPaused onlyOwner {
isPaused = false;
}
function freezeAccount(address target, bool freeze) public onlyOwner {
frozenAccount[target] = freeze;
emit FrozenFunds(target, freeze);
}
}
interface ERC998ERC721TopDown {
event ReceivedChild(address indexed _from, uint256 indexed _tokenId, address indexed _childContract, uint256 _childTokenId);
event TransferChild(uint256 indexed tokenId, address indexed _to, address indexed _childContract, uint256 _childTokenId);
// gets the address and token that owns the supplied tokenId. isParent says if parentTokenId is a parent token or not.
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent);
function ownerOfChild(address _childContract, uint256 _childTokenId) external view returns (uint256 parentTokenId, uint256 isParent);
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4);
function onERC998Removed(address _operator, address _toContract, uint256 _childTokenId, bytes _data) external;
function transferChild(address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId) external;
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId, bytes _data) external;
// getChild function enables older contracts like cryptokitties to be transferred into a composable
// The _childContract must approve this contract. Then getChild can be called.
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external;
}
interface ERC998ERC721TopDownEnumerable {
function totalChildContracts(uint256 _tokenId) external view returns(uint256);
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract);
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns(uint256);
function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId);
}
interface ERC998ERC20TopDown {
event ReceivedERC20(address indexed _from, uint256 indexed _tokenId, address indexed _erc223Contract, uint256 _value);
event TransferERC20(uint256 indexed _tokenId, address indexed _to, address indexed _erc223Contract, uint256 _value);
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent);
function tokenFallback(address _from, uint256 _value, bytes _data) external;
function balanceOfERC20(uint256 _tokenId, address __erc223Contract) external view returns(uint256);
function transferERC20(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value) external;
function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external;
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) external;
}
interface ERC998ERC20TopDownEnumerable {
function totalERC20Contracts(uint256 _tokenId) external view returns(uint256);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns(address);
}
interface ERC20AndERC223 {
function transferFrom(address _from, address _to, uint _value) external returns (bool success);
function transfer(address to, uint value) external returns (bool success);
function transfer(address to, uint value, bytes data) external returns (bool success);
function allowance(address _owner, address _spender) external view returns (uint256 remaining);
}
contract ComposableTopDown is ERC721, ERC998ERC721TopDown, ERC998ERC721TopDownEnumerable,
ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, BitGuildAccessAdminExtend{
// tokenOwnerOf.selector;
uint256 constant TOKEN_OWNER_OF = 0x89885a59;
uint256 constant OWNER_OF_CHILD = 0xeadb80b8;
// tokenId => token owner
mapping (uint256 => address) internal tokenIdToTokenOwner;
// root token owner address => (tokenId => approved address)
mapping (address => mapping (uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress;
// token owner address => token count
mapping (address => uint256) internal tokenOwnerToTokenCount;
// token owner => (operator address => bool)
mapping (address => mapping (address => bool)) internal tokenOwnerToOperators;
//from zepellin ERC721Receiver.sol
//old version
bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba;
//new version
bytes4 constant ERC721_RECEIVED_NEW = 0x150b7a02;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
bytes4 constant InterfaceId_ERC998 = 0x520bdcbe;
//InterfaceId_ERC998 = bytes4(keccak256('tokenOwnerOf(uint256)')) ^
// bytes4(keccak256('ownerOfChild(address,uint256)')) ^
// bytes4(keccak256('onERC721Received(address,address,uint256,bytes)')) ^
// bytes4(keccak256('onERC998RemovedChild(address,address,uint256,bytes)')) ^
// bytes4(keccak256('transferChild(address,address,uint256)')) ^
// bytes4(keccak256('safeTransferChild(address,address,uint256)')) ^
// bytes4(keccak256('safeTransferChild(address,address,uint256,bytes)')) ^
// bytes4(keccak256('getChild(address,address,uint256,uint256)'));
////////////////////////////////////////////////////////
// ERC721 implementation
////////////////////////////////////////////////////////
function _mint(address _to,uint256 _tokenId) internal whenNotPaused {
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
emit Transfer(address(0), _to, _tokenId);
}
function isContract(address _addr) internal view returns (bool) {
uint256 size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
// 0xeadb80b8 == ownerOfChild(address,uint256)
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function ownerOf(uint256 _tokenId) external view returns (address rootOwner) {
return _ownerOf(_tokenId);
}
// returns the owner at the top of the tree of composables
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
//0x89885a59 == "tokenOwnerOf(uint256)"
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
//0x6352211e == "_ownerOf(uint256)"
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function balanceOf(address _tokenOwner) external view returns (uint256) {
require(_tokenOwner != address(0));
return tokenOwnerToTokenCount[_tokenOwner];
}
function approve(address _approved, uint256 _tokenId) external whenNotPaused {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
address rootOwner = _ownerOf(_tokenId);
require(tokenOwner != address(0));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
tokenOwner == msg.sender ||
tokenOwnerToOperators[tokenOwner][msg.sender]);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId) external view returns (address) {
address rootOwner = _ownerOf(_tokenId);
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved) external whenNotPaused {
require(_operator != address(0));
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator ) external view returns (bool) {
require(_owner != address(0));
require(_operator != address(0));
return tokenOwnerToOperators[_owner][_operator];
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
// tokenIdToTokenOwner[_tokenId] = _to;
// tokenOwnerToTokenCount[_to]++;
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
// clear approval
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
// remove and transfer token
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
//0x0da719ec == "onERC998Removed(address,address,uint256,bytes)"
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
_transfer(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "");
require(retval == ERC721_RECEIVED_OLD);
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == ERC721_RECEIVED_OLD);
}
}
////////////////////////////////////////////////////////
// ERC998ERC721 and ERC998ERC721Enumerable implementation
////////////////////////////////////////////////////////
// tokenId => child contract
mapping(uint256 => address[]) internal childContracts;
// tokenId => (child address => contract index+1)
mapping(uint256 => mapping(address => uint256)) internal childContractIndex;
// tokenId => (child address => array of child tokens)
mapping(uint256 => mapping(address => uint256[])) internal childTokens;
// tokenId => (child address => (child token => child index+1)
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal childTokenIndex;
// child address => childId => tokenId
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
function onERC998Removed(address _operator, address _toContract, uint256 _childTokenId, bytes _data) external {
uint256 tokenId = childTokenOwner[msg.sender][_childTokenId];
_removeChild(tokenId, msg.sender, _childTokenId);
}
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId) external {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId, bytes _data) external {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId, _data);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function transferChild(address _to, address _childContract, uint256 _childTokenId) external {
_transferChild(_to, _childContract,_childTokenId);
}
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external {
_getChild(_from, _tokenId, _childContract,_childTokenId);
}
function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
/**************************************
* TODO move to library
**************************************/
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
// new onERC721Received
//tokenId := calldataload(164)
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
//END TODO
//require(this == ERC721Basic(msg.sender)._ownerOf(_childTokenId), "This contract does not own the child token.");
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
//cause out of gas error if circular ownership
_ownerOf(tokenId);
return ERC721_RECEIVED_OLD;
}
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
/**************************************
* TODO move to library
**************************************/
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
// new onERC721Received
tokenId := calldataload(164)
//tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
//END TODO
//require(this == ERC721Basic(msg.sender)._ownerOf(_childTokenId), "This contract does not own the child token.");
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
//cause out of gas error if circular ownership
_ownerOf(tokenId);
return ERC721_RECEIVED_NEW;
}
function _transferChild(address _to, address _childContract, uint256 _childTokenId) internal {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
//this is here to be compatible with cryptokitties and other old contracts that require being owner and approved
// before transferring.
//does not work with current standard which does not allow approving self, so we must let it fail in that case.
//0x095ea7b3 == "approve(address,uint256)"
bytes memory calldata = abi.encodeWithSelector(0x095ea7b3, this, _childTokenId);
assembly {
let success := call(gas, _childContract, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
ERC721(_childContract).transferFrom(this, _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
// this contract has to be approved first in _childContract
function _getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal {
_receiveChild(_from, _tokenId, _childContract, _childTokenId);
require(
_from == msg.sender || ERC721(_childContract).isApprovedForAll(_from, msg.sender) ||
ERC721(_childContract).getApproved(_childTokenId) == msg.sender);
ERC721(_childContract).transferFrom(_from, this, _childTokenId);
//cause out of gas error if circular ownership
_ownerOf(_tokenId);
}
function _receiveChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
require(childTokenIndex[_tokenId][_childContract][_childTokenId] == 0, "Cannot receive child token because it has already been received.");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length;
if(childTokensLength == 0) {
childContractIndex[_tokenId][_childContract] = childContracts[_tokenId].length;
childContracts[_tokenId].push(_childContract);
}
childTokens[_tokenId][_childContract].push(_childTokenId);
childTokenIndex[_tokenId][_childContract][_childTokenId] = childTokensLength + 1;
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId];
require(tokenIndex != 0, "Child token not owned by token.");
// remove child token
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length-1;
uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex];
//if(_childTokenId == lastToken) {
childTokens[_tokenId][_childContract][tokenIndex-1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
//}
childTokens[_tokenId][_childContract].length--;
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
// remove contract
if(lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if(_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][_childContract];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
childContracts[_tokenId].length--;
delete childContractIndex[_tokenId][_childContract];
}
}
function ownerOfChild(address _childContract, uint256 _childTokenId) public view returns (uint256 parentTokenId, uint256 isParent) {
parentTokenId = childTokenOwner[_childContract][_childTokenId];
if(parentTokenId == 0 && childTokenIndex[parentTokenId][_childContract][_childTokenId] == 0) {
return (0, OWNER_OF_CHILD << 8);
}
return (parentTokenId, OWNER_OF_CHILD << 8 | 1);
}
function childExists(address _childContract, uint256 _childTokenId) external view returns (bool) {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return childTokenIndex[tokenId][_childContract][_childTokenId] != 0;
}
function totalChildContracts(uint256 _tokenId) external view returns(uint256) {
return childContracts[_tokenId].length;
}
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract) {
require(_index < childContracts[_tokenId].length, "Contract address does not exist for this token and index.");
return childContracts[_tokenId][_index];
}
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns(uint256) {
return childTokens[_tokenId][_childContract].length;
}
function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId) {
require(_index < childTokens[_tokenId][_childContract].length, "Token does not own a child token at contract address and index.");
return childTokens[_tokenId][_childContract][_index];
}
////////////////////////////////////////////////////////
// ERC998ERC223 and ERC998ERC223Enumerable implementation
////////////////////////////////////////////////////////
// tokenId => token contract
mapping(uint256 => address[]) erc223Contracts;
// tokenId => (token contract => token contract index)
mapping(uint256 => mapping(address => uint256)) erc223ContractIndex;
// tokenId => (token contract => balance)
mapping(uint256 => mapping(address => uint256)) erc223Balances;
function balanceOfERC20(uint256 _tokenId, address _erc223Contract) external view returns(uint256) {
return erc223Balances[_tokenId][_erc223Contract];
}
function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused {
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
require(erc223Balance >= _value, "Not enough token available to transfer.");
uint256 newERC223Balance = erc223Balance - _value;
erc223Balances[_tokenId][_erc223Contract] = newERC223Balance;
if(newERC223Balance == 0) {
uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1;
address lastContract = erc223Contracts[_tokenId][lastContractIndex];
if(_erc223Contract != lastContract) {
uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract];
erc223Contracts[_tokenId][contractIndex] = lastContract;
erc223ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc223Contracts[_tokenId].length--;
delete erc223ContractIndex[_tokenId][_erc223Contract];
}
}
function transferERC20(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
removeERC223(_tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transfer(_to, _value), "ERC20 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc223Contract, _value);
}
// implementation of ERC 223
function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
removeERC223(_tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transfer(_to, _value, _data), "ERC223 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc223Contract, _value);
}
// this contract has to be approved first by _erc223Contract
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if(!allowed) {
uint256 remaining;
// 0xdd62ed3e == allowance(address,address)
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc223Received(_from, _tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function erc223Received(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) private {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
if(erc223Balance == 0) {
erc223ContractIndex[_tokenId][_erc223Contract] = erc223Contracts[_tokenId].length;
erc223Contracts[_tokenId].push(_erc223Contract);
}
erc223Balances[_tokenId][_erc223Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc223Contract, _value);
}
// used by ERC 223
function tokenFallback(address _from, uint256 _value, bytes _data) external {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to.");
require(isContract(msg.sender), "msg.sender is not a contract");
/**************************************
* TODO move to library
**************************************/
// convert up to 32 bytes of_data to uint256, owner nft tokenId passed as uint in bytes
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
//END TODO
erc223Received(_from, tokenId, msg.sender, _value);
}
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns(address) {
require(_index < erc223Contracts[_tokenId].length, "Contract address does not exist for this token and index.");
return erc223Contracts[_tokenId][_index];
}
function totalERC20Contracts(uint256 _tokenId) external view returns(uint256) {
return erc223Contracts[_tokenId].length;
}
}
contract ERC998TopDownToken is SupportsInterfaceWithLookup, ERC721Enumerable, ERC721Metadata, ComposableTopDown {
using SafeMath for uint256;
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor() public {
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(InterfaceId_ERC721Enumerable);
_registerInterface(InterfaceId_ERC721Metadata);
_registerInterface(InterfaceId_ERC998);
}
modifier existsToken(uint256 _tokenId){
address owner = tokenIdToTokenOwner[_tokenId];
require(owner != address(0), "This tokenId is invalid");
_;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return "Bitizen";
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return "BTZN";
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) external view existsToken(_tokenId) returns (string) {
return "";
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(address(0) != _owner);
require(_index < tokenOwnerToTokenCount[_owner]);
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) existsToken(_tokenId) internal {
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenTo(address _to, uint256 _tokenId) internal whenNotPaused {
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFrom(address _from, uint256 _tokenId) internal whenNotPaused {
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal whenNotPaused {
super._mint(_to, _tokenId);
_addTokenTo(_to,_tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
//override
//add Enumerable info
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
super._transfer(_from, _to, _tokenId);
_addTokenTo(_to,_tokenId);
_removeTokenFrom(_from, _tokenId);
}
}
contract AvatarToken is ERC998TopDownToken, AvatarService {
using UrlStr for string;
event BatchMount(address indexed from, uint256 parent, address indexed childAddr, uint256[] children);
event BatchUnmount(address indexed from, uint256 parent, address indexed childAddr, uint256[] children);
struct Avatar {
// avatar name
string name;
// avatar gen,this decide the avatar appearance
uint256 dna;
}
// For erc721 metadata
string internal BASE_URL = "https://www.bitguild.com/bitizens/api/avatar/getAvatar/00000000";
Avatar[] avatars;
function createAvatar(address _owner, string _name, uint256 _dna) external onlyOperator returns(uint256) {
return _createAvatar(_owner, _name, _dna);
}
function getMountTokenIds(address _owner, uint256 _tokenId, address _avatarItemAddress)
external
view
onlyOperator
existsToken(_tokenId)
returns(uint256[]) {
require(tokenIdToTokenOwner[_tokenId] == _owner);
return childTokens[_tokenId][_avatarItemAddress];
}
function updateAvatarInfo(address _owner, uint256 _tokenId, string _name, uint256 _dna) external onlyOperator existsToken(_tokenId){
require(_owner != address(0), "Invalid address");
require(_owner == tokenIdToTokenOwner[_tokenId] || msg.sender == owner);
Avatar storage avatar = avatars[allTokensIndex[_tokenId]];
avatar.name = _name;
avatar.dna = _dna;
}
function updateBaseURI(string _url) external onlyOperator {
BASE_URL = _url;
}
function tokenURI(uint256 _tokenId) external view existsToken(_tokenId) returns (string) {
return BASE_URL.generateUrl(_tokenId);
}
function getOwnedTokenIds(address _owner) external view returns(uint256[] _tokenIds) {
_tokenIds = ownedTokens[_owner];
}
function getAvatarInfo(uint256 _tokenId) external view existsToken(_tokenId) returns(string _name, uint256 _dna) {
Avatar storage avatar = avatars[allTokensIndex[_tokenId]];
_name = avatar.name;
_dna = avatar.dna;
}
function batchMount(address _childContract, uint256[] _childTokenIds, uint256 _tokenId) external {
uint256 _len = _childTokenIds.length;
require(_len > 0, "No token need to mount");
address tokenOwner = _ownerOf(_tokenId);
require(tokenOwner == msg.sender);
for(uint8 i = 0; i < _len; ++i) {
uint256 childTokenId = _childTokenIds[i];
require(ERC721(_childContract).ownerOf(childTokenId) == tokenOwner);
_getChild(msg.sender, _tokenId, _childContract, childTokenId);
}
emit BatchMount(msg.sender, _tokenId, _childContract, _childTokenIds);
}
function batchUnmount(address _childContract, uint256[] _childTokenIds, uint256 _tokenId) external {
uint256 len = _childTokenIds.length;
require(len > 0, "No token need to unmount");
address tokenOwner = _ownerOf(_tokenId);
require(tokenOwner == msg.sender);
for(uint8 i = 0; i < len; ++i) {
uint256 childTokenId = _childTokenIds[i];
_transferChild(msg.sender, _childContract, childTokenId);
}
emit BatchUnmount(msg.sender,_tokenId,_childContract,_childTokenIds);
}
// create avatar
function _createAvatar(address _owner, string _name, uint256 _dna) private returns(uint256 _tokenId) {
require(_owner != address(0));
Avatar memory avatar = Avatar(_name, _dna);
_tokenId = avatars.push(avatar);
_mint(_owner, _tokenId);
}
function _unmountSameSocketItem(address _owner, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal {
uint256[] storage tokens = childTokens[_tokenId][_childContract];
for(uint256 i = 0; i < tokens.length; ++i) {
// if the child no compareItemSlots(uint256,uint256) ,this will lead to a error and stop this operate
if(AvatarChildService(_childContract).compareItemSlots(tokens[i], _childTokenId)) {
// unmount the old avatar item
_transferChild(_owner, _childContract, tokens[i]);
}
}
}
// override
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
// not allown to transfer when only one avatar
require(tokenOwnerToTokenCount[_from] > 1);
super._transfer(_from, _to, _tokenId);
}
// override
function _getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal {
_unmountSameSocketItem(_from, _tokenId, _childContract, _childTokenId);
super._getChild(_from, _tokenId, _childContract, _childTokenId);
}
function () external payable {
revert();
}
} | tokenOwnerOf.selector; tokenId => token owner root token owner address => (tokenId => approved address) token owner address => token count token owner => (operator address => bool)from zepellin ERC721Receiver.solold versionnew versionInterfaceId_ERC998 = bytes4(keccak256('tokenOwnerOf(uint256)')) ^ bytes4(keccak256('ownerOfChild(address,uint256)')) ^ bytes4(keccak256('onERC721Received(address,address,uint256,bytes)')) ^ bytes4(keccak256('onERC998RemovedChild(address,address,uint256,bytes)')) ^ bytes4(keccak256('transferChild(address,address,uint256)')) ^ bytes4(keccak256('safeTransferChild(address,address,uint256)')) ^ bytes4(keccak256('safeTransferChild(address,address,uint256,bytes)')) ^ bytes4(keccak256('getChild(address,address,uint256,uint256)')); ERC721 implementation | ERC998ERC20TopDown, ERC998ERC20TopDownEnumerable, BitGuildAccessAdminExtend{
uint256 constant TOKEN_OWNER_OF = 0x89885a59;
uint256 constant OWNER_OF_CHILD = 0xeadb80b8;
mapping (uint256 => address) internal tokenIdToTokenOwner;
mapping (address => mapping (uint256 => address)) internal rootOwnerAndTokenIdToApprovedAddress;
mapping (address => uint256) internal tokenOwnerToTokenCount;
mapping (address => mapping (address => bool)) internal tokenOwnerToOperators;
bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba;
bytes4 constant ERC721_RECEIVED_NEW = 0x150b7a02;
bytes4 constant InterfaceId_ERC998 = 0x520bdcbe;
function _mint(address _to,uint256 _tokenId) internal whenNotPaused {
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
emit Transfer(address(0), _to, _tokenId);
}
function isContract(address _addr) internal view returns (bool) {
uint256 size;
return size > 0;
}
assembly { size := extcodesize(_addr) }
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function tokenOwnerOf(uint256 _tokenId) external view returns (address tokenOwner, uint256 parentTokenId, uint256 isParent) {
tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner != address(0));
if(tokenOwner == address(this)) {
(parentTokenId, isParent) = ownerOfChild(address(this), _tokenId);
}
else {
bool callSuccess;
bytes memory calldata = abi.encodeWithSelector(0xeadb80b8, address(this), _tokenId);
assembly {
callSuccess := staticcall(gas, tokenOwner, add(calldata, 0x20), mload(calldata), calldata, 0x40)
if callSuccess {
parentTokenId := mload(calldata)
isParent := mload(add(calldata,0x20))
}
}
if(callSuccess && isParent >> 8 == OWNER_OF_CHILD) {
isParent = TOKEN_OWNER_OF << 8 | uint8(isParent);
}
else {
isParent = TOKEN_OWNER_OF << 8;
parentTokenId = 0;
}
}
return (tokenOwner, parentTokenId, isParent);
}
function ownerOf(uint256 _tokenId) external view returns (address rootOwner) {
return _ownerOf(_tokenId);
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function _ownerOf(uint256 _tokenId) internal view returns (address rootOwner) {
rootOwner = tokenIdToTokenOwner[_tokenId];
require(rootOwner != address(0));
uint256 isParent = 1;
bool callSuccess;
bytes memory calldata;
while(uint8(isParent) > 0) {
if(rootOwner == address(this)) {
(_tokenId, isParent) = ownerOfChild(address(this), _tokenId);
if(uint8(isParent) > 0) {
rootOwner = tokenIdToTokenOwner[_tokenId];
}
}
else {
if(isContract(rootOwner)) {
calldata = abi.encodeWithSelector(0x89885a59, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x60)
if callSuccess {
rootOwner := mload(calldata)
_tokenId := mload(add(calldata,0x20))
isParent := mload(add(calldata,0x40))
}
}
if(callSuccess == false || isParent >> 8 != TOKEN_OWNER_OF) {
calldata = abi.encodeWithSelector(0x6352211e, _tokenId);
assembly {
callSuccess := staticcall(gas, rootOwner, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
rootOwner := mload(calldata)
}
}
require(callSuccess, "rootOwnerOf failed");
isParent = 0;
}
}
else {
isParent = 0;
}
}
}
return rootOwner;
}
function balanceOf(address _tokenOwner) external view returns (uint256) {
require(_tokenOwner != address(0));
return tokenOwnerToTokenCount[_tokenOwner];
}
function approve(address _approved, uint256 _tokenId) external whenNotPaused {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
address rootOwner = _ownerOf(_tokenId);
require(tokenOwner != address(0));
require(
rootOwner == msg.sender ||
tokenOwnerToOperators[rootOwner][msg.sender] ||
tokenOwner == msg.sender ||
tokenOwnerToOperators[tokenOwner][msg.sender]);
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] = _approved;
emit Approval(rootOwner, _approved, _tokenId);
}
function getApproved(uint256 _tokenId) external view returns (address) {
address rootOwner = _ownerOf(_tokenId);
return rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
function setApprovalForAll(address _operator, bool _approved) external whenNotPaused {
require(_operator != address(0));
tokenOwnerToOperators[msg.sender][_operator] = _approved;
emit ApprovalForAll(msg.sender, _operator, _approved);
}
function isApprovedForAll(address _owner, address _operator ) external view returns (bool) {
require(_owner != address(0));
require(_operator != address(0));
return tokenOwnerToOperators[_owner][_operator];
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function _transfer(address _from, address _to, uint256 _tokenId) internal whenNotPaused {
require(!frozenAccount[_from]);
require(!frozenAccount[_to]);
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(tokenOwner == _from);
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
if(rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] != address(0)) {
delete rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId];
}
if(_from != _to) {
assert(tokenOwnerToTokenCount[_from] > 0);
tokenOwnerToTokenCount[_from]--;
tokenIdToTokenOwner[_tokenId] = _to;
tokenOwnerToTokenCount[_to]++;
}
emit Transfer(_from, _to, _tokenId);
if(isContract(_from)) {
bytes memory calldata = abi.encodeWithSelector(0x0da719ec, msg.sender, _to, _tokenId,"");
assembly {
let success := call(gas, _from, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
}
}
function transferFrom(address _from, address _to, uint256 _tokenId) external {
_transfer(_from, _to, _tokenId);
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "");
require(retval == ERC721_RECEIVED_OLD);
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, "");
require(retval == ERC721_RECEIVED_OLD);
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == ERC721_RECEIVED_OLD);
}
}
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes _data) external {
_transfer(_from, _to, _tokenId);
if(isContract(_to)) {
bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data);
require(retval == ERC721_RECEIVED_OLD);
}
}
mapping(uint256 => address[]) internal childContracts;
mapping(uint256 => mapping(address => uint256)) internal childContractIndex;
mapping(uint256 => mapping(address => uint256[])) internal childTokens;
mapping(uint256 => mapping(address => mapping(uint256 => uint256))) internal childTokenIndex;
mapping(address => mapping(uint256 => uint256)) internal childTokenOwner;
function onERC998Removed(address _operator, address _toContract, uint256 _childTokenId, bytes _data) external {
uint256 tokenId = childTokenOwner[msg.sender][_childTokenId];
_removeChild(tokenId, msg.sender, _childTokenId);
}
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId) external {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function safeTransferChild(address _to, address _childContract, uint256 _childTokenId, bytes _data) external {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
ERC721(_childContract).safeTransferFrom(this, _to, _childTokenId, _data);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function transferChild(address _to, address _childContract, uint256 _childTokenId) external {
_transferChild(_to, _childContract,_childTokenId);
}
function getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) external {
_getChild(_from, _tokenId, _childContract,_childTokenId);
}
function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_OLD;
}
function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_OLD;
}
function onERC721Received(address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_OLD;
}
_ownerOf(tokenId);
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(164)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_NEW;
}
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(164)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_NEW;
}
function onERC721Received(address _operator, address _from, uint256 _childTokenId, bytes _data) external returns(bytes4) {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the child token to.");
require(isContract(msg.sender), "msg.sender is not a contract.");
uint256 tokenId;
assembly {
tokenId := calldataload(164)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
_receiveChild(_from, tokenId, msg.sender, _childTokenId);
return ERC721_RECEIVED_NEW;
}
_ownerOf(tokenId);
function _transferChild(address _to, address _childContract, uint256 _childTokenId) internal {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
bytes memory calldata = abi.encodeWithSelector(0x095ea7b3, this, _childTokenId);
assembly {
let success := call(gas, _childContract, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
ERC721(_childContract).transferFrom(this, _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function _transferChild(address _to, address _childContract, uint256 _childTokenId) internal {
(uint256 tokenId, uint256 isParent) = ownerOfChild(_childContract, _childTokenId);
require(uint8(isParent) > 0);
address tokenOwner = tokenIdToTokenOwner[tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
_removeChild(tokenId, _childContract, _childTokenId);
bytes memory calldata = abi.encodeWithSelector(0x095ea7b3, this, _childTokenId);
assembly {
let success := call(gas, _childContract, 0, add(calldata, 0x20), mload(calldata), calldata, 0)
}
ERC721(_childContract).transferFrom(this, _to, _childTokenId);
emit TransferChild(tokenId, _to, _childContract, _childTokenId);
}
function _getChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) internal {
_receiveChild(_from, _tokenId, _childContract, _childTokenId);
require(
_from == msg.sender || ERC721(_childContract).isApprovedForAll(_from, msg.sender) ||
ERC721(_childContract).getApproved(_childTokenId) == msg.sender);
ERC721(_childContract).transferFrom(_from, this, _childTokenId);
_ownerOf(_tokenId);
}
function _receiveChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
require(childTokenIndex[_tokenId][_childContract][_childTokenId] == 0, "Cannot receive child token because it has already been received.");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length;
if(childTokensLength == 0) {
childContractIndex[_tokenId][_childContract] = childContracts[_tokenId].length;
childContracts[_tokenId].push(_childContract);
}
childTokens[_tokenId][_childContract].push(_childTokenId);
childTokenIndex[_tokenId][_childContract][_childTokenId] = childTokensLength + 1;
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
function _receiveChild(address _from, uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
require(childTokenIndex[_tokenId][_childContract][_childTokenId] == 0, "Cannot receive child token because it has already been received.");
uint256 childTokensLength = childTokens[_tokenId][_childContract].length;
if(childTokensLength == 0) {
childContractIndex[_tokenId][_childContract] = childContracts[_tokenId].length;
childContracts[_tokenId].push(_childContract);
}
childTokens[_tokenId][_childContract].push(_childTokenId);
childTokenIndex[_tokenId][_childContract][_childTokenId] = childTokensLength + 1;
childTokenOwner[_childContract][_childTokenId] = _tokenId;
emit ReceivedChild(_from, _tokenId, _childContract, _childTokenId);
}
function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId];
require(tokenIndex != 0, "Child token not owned by token.");
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length-1;
uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex];
childTokens[_tokenId][_childContract][tokenIndex-1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
childTokens[_tokenId][_childContract].length--;
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
if(lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if(_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][_childContract];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
childContracts[_tokenId].length--;
delete childContractIndex[_tokenId][_childContract];
}
}
function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId];
require(tokenIndex != 0, "Child token not owned by token.");
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length-1;
uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex];
childTokens[_tokenId][_childContract][tokenIndex-1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
childTokens[_tokenId][_childContract].length--;
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
if(lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if(_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][_childContract];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
childContracts[_tokenId].length--;
delete childContractIndex[_tokenId][_childContract];
}
}
function _removeChild(uint256 _tokenId, address _childContract, uint256 _childTokenId) private whenNotPaused {
uint256 tokenIndex = childTokenIndex[_tokenId][_childContract][_childTokenId];
require(tokenIndex != 0, "Child token not owned by token.");
uint256 lastTokenIndex = childTokens[_tokenId][_childContract].length-1;
uint256 lastToken = childTokens[_tokenId][_childContract][lastTokenIndex];
childTokens[_tokenId][_childContract][tokenIndex-1] = lastToken;
childTokenIndex[_tokenId][_childContract][lastToken] = tokenIndex;
childTokens[_tokenId][_childContract].length--;
delete childTokenIndex[_tokenId][_childContract][_childTokenId];
delete childTokenOwner[_childContract][_childTokenId];
if(lastTokenIndex == 0) {
uint256 lastContractIndex = childContracts[_tokenId].length - 1;
address lastContract = childContracts[_tokenId][lastContractIndex];
if(_childContract != lastContract) {
uint256 contractIndex = childContractIndex[_tokenId][_childContract];
childContracts[_tokenId][contractIndex] = lastContract;
childContractIndex[_tokenId][lastContract] = contractIndex;
}
childContracts[_tokenId].length--;
delete childContractIndex[_tokenId][_childContract];
}
}
function ownerOfChild(address _childContract, uint256 _childTokenId) public view returns (uint256 parentTokenId, uint256 isParent) {
parentTokenId = childTokenOwner[_childContract][_childTokenId];
if(parentTokenId == 0 && childTokenIndex[parentTokenId][_childContract][_childTokenId] == 0) {
return (0, OWNER_OF_CHILD << 8);
}
return (parentTokenId, OWNER_OF_CHILD << 8 | 1);
}
function ownerOfChild(address _childContract, uint256 _childTokenId) public view returns (uint256 parentTokenId, uint256 isParent) {
parentTokenId = childTokenOwner[_childContract][_childTokenId];
if(parentTokenId == 0 && childTokenIndex[parentTokenId][_childContract][_childTokenId] == 0) {
return (0, OWNER_OF_CHILD << 8);
}
return (parentTokenId, OWNER_OF_CHILD << 8 | 1);
}
function childExists(address _childContract, uint256 _childTokenId) external view returns (bool) {
uint256 tokenId = childTokenOwner[_childContract][_childTokenId];
return childTokenIndex[tokenId][_childContract][_childTokenId] != 0;
}
function totalChildContracts(uint256 _tokenId) external view returns(uint256) {
return childContracts[_tokenId].length;
}
function childContractByIndex(uint256 _tokenId, uint256 _index) external view returns (address childContract) {
require(_index < childContracts[_tokenId].length, "Contract address does not exist for this token and index.");
return childContracts[_tokenId][_index];
}
function totalChildTokens(uint256 _tokenId, address _childContract) external view returns(uint256) {
return childTokens[_tokenId][_childContract].length;
}
function childTokenByIndex(uint256 _tokenId, address _childContract, uint256 _index) external view returns (uint256 childTokenId) {
require(_index < childTokens[_tokenId][_childContract].length, "Token does not own a child token at contract address and index.");
return childTokens[_tokenId][_childContract][_index];
}
mapping(uint256 => address[]) erc223Contracts;
mapping(uint256 => mapping(address => uint256)) erc223ContractIndex;
mapping(uint256 => mapping(address => uint256)) erc223Balances;
function balanceOfERC20(uint256 _tokenId, address _erc223Contract) external view returns(uint256) {
return erc223Balances[_tokenId][_erc223Contract];
}
function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused {
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
require(erc223Balance >= _value, "Not enough token available to transfer.");
uint256 newERC223Balance = erc223Balance - _value;
erc223Balances[_tokenId][_erc223Contract] = newERC223Balance;
if(newERC223Balance == 0) {
uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1;
address lastContract = erc223Contracts[_tokenId][lastContractIndex];
if(_erc223Contract != lastContract) {
uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract];
erc223Contracts[_tokenId][contractIndex] = lastContract;
erc223ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc223Contracts[_tokenId].length--;
delete erc223ContractIndex[_tokenId][_erc223Contract];
}
}
function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused {
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
require(erc223Balance >= _value, "Not enough token available to transfer.");
uint256 newERC223Balance = erc223Balance - _value;
erc223Balances[_tokenId][_erc223Contract] = newERC223Balance;
if(newERC223Balance == 0) {
uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1;
address lastContract = erc223Contracts[_tokenId][lastContractIndex];
if(_erc223Contract != lastContract) {
uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract];
erc223Contracts[_tokenId][contractIndex] = lastContract;
erc223ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc223Contracts[_tokenId].length--;
delete erc223ContractIndex[_tokenId][_erc223Contract];
}
}
function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused {
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
require(erc223Balance >= _value, "Not enough token available to transfer.");
uint256 newERC223Balance = erc223Balance - _value;
erc223Balances[_tokenId][_erc223Contract] = newERC223Balance;
if(newERC223Balance == 0) {
uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1;
address lastContract = erc223Contracts[_tokenId][lastContractIndex];
if(_erc223Contract != lastContract) {
uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract];
erc223Contracts[_tokenId][contractIndex] = lastContract;
erc223ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc223Contracts[_tokenId].length--;
delete erc223ContractIndex[_tokenId][_erc223Contract];
}
}
function removeERC223(uint256 _tokenId, address _erc223Contract, uint256 _value) private whenNotPaused {
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
require(erc223Balance >= _value, "Not enough token available to transfer.");
uint256 newERC223Balance = erc223Balance - _value;
erc223Balances[_tokenId][_erc223Contract] = newERC223Balance;
if(newERC223Balance == 0) {
uint256 lastContractIndex = erc223Contracts[_tokenId].length - 1;
address lastContract = erc223Contracts[_tokenId][lastContractIndex];
if(_erc223Contract != lastContract) {
uint256 contractIndex = erc223ContractIndex[_tokenId][_erc223Contract];
erc223Contracts[_tokenId][contractIndex] = lastContract;
erc223ContractIndex[_tokenId][lastContract] = contractIndex;
}
erc223Contracts[_tokenId].length--;
delete erc223ContractIndex[_tokenId][_erc223Contract];
}
}
function transferERC20(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
removeERC223(_tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transfer(_to, _value), "ERC20 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc223Contract, _value);
}
function transferERC223(uint256 _tokenId, address _to, address _erc223Contract, uint256 _value, bytes _data) external {
address tokenOwner = tokenIdToTokenOwner[_tokenId];
require(_to != address(0));
address rootOwner = _ownerOf(_tokenId);
require(
rootOwner == msg.sender || tokenOwnerToOperators[rootOwner][msg.sender] ||
rootOwnerAndTokenIdToApprovedAddress[rootOwner][_tokenId] == msg.sender ||
tokenOwner == msg.sender || tokenOwnerToOperators[tokenOwner][msg.sender]);
removeERC223(_tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transfer(_to, _value, _data), "ERC223 transfer failed.");
emit TransferERC20(_tokenId, _to, _erc223Contract, _value);
}
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if(!allowed) {
uint256 remaining;
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc223Received(_from, _tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if(!allowed) {
uint256 remaining;
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc223Received(_from, _tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if(!allowed) {
uint256 remaining;
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc223Received(_from, _tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function getERC20(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) public {
bool allowed = _from == msg.sender;
if(!allowed) {
uint256 remaining;
bytes memory calldata = abi.encodeWithSelector(0xdd62ed3e,_from,msg.sender);
bool callSuccess;
assembly {
callSuccess := staticcall(gas, _erc223Contract, add(calldata, 0x20), mload(calldata), calldata, 0x20)
if callSuccess {
remaining := mload(calldata)
}
}
require(callSuccess, "call to allowance failed");
require(remaining >= _value, "Value greater than remaining");
allowed = true;
}
require(allowed, "not allowed to getERC20");
erc223Received(_from, _tokenId, _erc223Contract, _value);
require(ERC20AndERC223(_erc223Contract).transferFrom(_from, this, _value), "ERC20 transfer failed.");
}
function erc223Received(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) private {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
if(erc223Balance == 0) {
erc223ContractIndex[_tokenId][_erc223Contract] = erc223Contracts[_tokenId].length;
erc223Contracts[_tokenId].push(_erc223Contract);
}
erc223Balances[_tokenId][_erc223Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc223Contract, _value);
}
function erc223Received(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) private {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
if(erc223Balance == 0) {
erc223ContractIndex[_tokenId][_erc223Contract] = erc223Contracts[_tokenId].length;
erc223Contracts[_tokenId].push(_erc223Contract);
}
erc223Balances[_tokenId][_erc223Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc223Contract, _value);
}
function erc223Received(address _from, uint256 _tokenId, address _erc223Contract, uint256 _value) private {
require(tokenIdToTokenOwner[_tokenId] != address(0), "_tokenId does not exist.");
if(_value == 0) {
return;
}
uint256 erc223Balance = erc223Balances[_tokenId][_erc223Contract];
if(erc223Balance == 0) {
erc223ContractIndex[_tokenId][_erc223Contract] = erc223Contracts[_tokenId].length;
erc223Contracts[_tokenId].push(_erc223Contract);
}
erc223Balances[_tokenId][_erc223Contract] += _value;
emit ReceivedERC20(_from, _tokenId, _erc223Contract, _value);
}
function tokenFallback(address _from, uint256 _value, bytes _data) external {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to.");
require(isContract(msg.sender), "msg.sender is not a contract");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
}
function tokenFallback(address _from, uint256 _value, bytes _data) external {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to.");
require(isContract(msg.sender), "msg.sender is not a contract");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
}
function tokenFallback(address _from, uint256 _value, bytes _data) external {
require(_data.length > 0, "_data must contain the uint256 tokenId to transfer the token to.");
require(isContract(msg.sender), "msg.sender is not a contract");
uint256 tokenId;
assembly {
tokenId := calldataload(132)
}
if(_data.length < 32) {
tokenId = tokenId >> 256 - _data.length * 8;
}
}
erc223Received(_from, tokenId, msg.sender, _value);
function erc20ContractByIndex(uint256 _tokenId, uint256 _index) external view returns(address) {
require(_index < erc223Contracts[_tokenId].length, "Contract address does not exist for this token and index.");
return erc223Contracts[_tokenId][_index];
}
function totalERC20Contracts(uint256 _tokenId) external view returns(uint256) {
return erc223Contracts[_tokenId].length;
}
}
| 580,741 | [
1,
2316,
5541,
951,
18,
9663,
31,
1147,
548,
516,
1147,
3410,
1365,
1147,
3410,
1758,
516,
261,
2316,
548,
516,
20412,
1758,
13,
1147,
3410,
1758,
516,
1147,
1056,
1147,
3410,
516,
261,
9497,
1758,
516,
1426,
13,
2080,
998,
881,
1165,
267,
4232,
39,
27,
5340,
12952,
18,
18281,
1673,
1177,
2704,
1177,
1358,
548,
67,
654,
39,
2733,
28,
273,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
2316,
5541,
951,
12,
11890,
5034,
2506,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
8443,
951,
1763,
12,
2867,
16,
11890,
5034,
2506,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
265,
654,
39,
27,
5340,
8872,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2506,
3719,
3602,
1731,
24,
12,
79,
24410,
581,
5034,
2668,
265,
654,
39,
2733,
28,
10026,
1763,
12,
2867,
16,
2867,
16,
11890,
5034,
16,
3890,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
19694,
4232,
39,
2733,
28,
654,
39,
3462,
3401,
4164,
16,
4232,
39,
2733,
28,
654,
39,
3462,
3401,
4164,
3572,
25121,
16,
6539,
43,
680,
1862,
4446,
16675,
95,
203,
11794,
203,
225,
2254,
5034,
5381,
14275,
67,
29602,
67,
3932,
273,
374,
92,
6675,
5482,
25,
69,
6162,
31,
203,
225,
2254,
5034,
5381,
531,
22527,
67,
3932,
67,
27043,
273,
374,
92,
684,
70,
3672,
70,
28,
31,
203,
203,
225,
2874,
261,
11890,
5034,
516,
1758,
13,
2713,
1147,
28803,
1345,
5541,
31,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
11890,
5034,
516,
1758,
3719,
2713,
1365,
5541,
1876,
1345,
28803,
31639,
1887,
31,
203,
203,
225,
2874,
261,
2867,
516,
2254,
5034,
13,
2713,
1147,
5541,
774,
1345,
1380,
31,
203,
203,
225,
2874,
261,
2867,
516,
2874,
261,
2867,
516,
1426,
3719,
2713,
1147,
5541,
774,
24473,
31,
203,
203,
203,
225,
1731,
24,
5381,
4232,
39,
27,
5340,
67,
27086,
20764,
67,
11846,
273,
374,
5841,
20,
70,
29,
73,
25,
12124,
31,
203,
225,
1731,
24,
5381,
4232,
39,
27,
5340,
67,
27086,
20764,
67,
12917,
273,
374,
92,
23014,
70,
27,
69,
3103,
31,
203,
225,
1731,
24,
225,
5381,
6682,
548,
67,
654,
39,
2733,
28,
273,
374,
92,
25,
3462,
70,
7201,
2196,
31,
203,
203,
203,
203,
203,
21281,
225,
445,
389,
81,
474,
12,
2867,
389,
869,
16,
11890,
5034,
389,
2316,
548,
13,
2713,
1347,
1248,
28590,
288,
203,
565,
1147,
28803,
1345,
5541,
63,
67,
2316,
548,
2
] |
// hevm: flattened sources of src/AutoLineJob.sol
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity >=0.8.9 <0.9.0;
////// src/IJob.sol
// Copyright (C) 2021 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity ^0.8.9; */
interface IJob {
function getNextJob(bytes32 operator) external view returns (bool canExec, address target, bytes memory execPayload);
}
////// src/AutoLineJob.sol
// Copyright (C) 2021 Dai Foundation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.
/* pragma solidity ^0.8.9; */
/* import "./IJob.sol"; */
interface SequencerLike {
function isMaster(bytes32 network) external view returns (bool);
}
interface IlkRegistryLike_1 {
function list() external view returns (bytes32[] memory);
}
interface AutoLineLike_1 {
function vat() external view returns (address);
function ilks(bytes32) external view returns (uint256, uint256, uint48, uint48, uint48);
function exec(bytes32) external returns (uint256);
}
interface VatLike_1 {
function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256);
}
// Trigger autoline updates based on thresholds
contract AutoLineJob is IJob {
uint256 constant internal BPS = 10 ** 4;
SequencerLike public immutable sequencer;
IlkRegistryLike_1 public immutable ilkRegistry;
AutoLineLike_1 public immutable autoline;
VatLike_1 public immutable vat;
uint256 public immutable thi; // % above the previously exec'ed debt level
uint256 public immutable tlo; // % below the previously exec'ed debt level
constructor(address _sequencer, address _ilkRegistry, address _autoline, uint256 _thi, uint256 _tlo) {
sequencer = SequencerLike(_sequencer);
ilkRegistry = IlkRegistryLike_1(_ilkRegistry);
autoline = AutoLineLike_1(_autoline);
vat = VatLike_1(autoline.vat());
thi = _thi;
tlo = _tlo;
}
function getNextJob(bytes32 network) external view override returns (bool, address, bytes memory) {
if (!sequencer.isMaster(network)) return (false, address(0), bytes("Network is not master"));
bytes32[] memory ilks = ilkRegistry.list();
for (uint256 i = 0; i < ilks.length; i++) {
bytes32 ilk = ilks[i];
(uint256 Art, uint256 rate,, uint256 line,) = vat.ilks(ilk);
uint256 debt = Art * rate;
(uint256 maxLine, uint256 gap, uint48 ttl, uint48 last, uint48 lastInc) = autoline.ilks(ilk);
uint256 nextLine = debt + gap;
if (nextLine > maxLine) nextLine = maxLine;
// Check autoline rules
if (maxLine == 0) continue; // Ilk is not enabled
if (last == block.number) continue; // Already triggered this block
if (line == nextLine || // No change in line
nextLine > line && // Increase in line
block.timestamp < lastInc + ttl) continue; // TTL hasn't expired
// Check if current debt level is inside our do-nothing range
// Re-arranged to remove any subtraction (and thus underflow)
// Exception if we are at the maxLine
if (
nextLine != maxLine &&
debt + gap < line + gap * thi / BPS &&
debt + gap + gap * tlo / BPS > line
) continue;
// Good to adjust!
return (true, address(autoline), abi.encodeWithSelector(AutoLineLike_1.exec.selector, ilk));
}
return (false, address(0), bytes("No ilks ready"));
}
} | Trigger autoline updates based on thresholds | contract AutoLineJob is IJob {
uint256 constant internal BPS = 10 ** 4;
SequencerLike public immutable sequencer;
IlkRegistryLike_1 public immutable ilkRegistry;
AutoLineLike_1 public immutable autoline;
VatLike_1 public immutable vat;
constructor(address _sequencer, address _ilkRegistry, address _autoline, uint256 _thi, uint256 _tlo) {
sequencer = SequencerLike(_sequencer);
ilkRegistry = IlkRegistryLike_1(_ilkRegistry);
autoline = AutoLineLike_1(_autoline);
vat = VatLike_1(autoline.vat());
thi = _thi;
tlo = _tlo;
}
function getNextJob(bytes32 network) external view override returns (bool, address, bytes memory) {
if (!sequencer.isMaster(network)) return (false, address(0), bytes("Network is not master"));
bytes32[] memory ilks = ilkRegistry.list();
for (uint256 i = 0; i < ilks.length; i++) {
bytes32 ilk = ilks[i];
(uint256 Art, uint256 rate,, uint256 line,) = vat.ilks(ilk);
uint256 debt = Art * rate;
(uint256 maxLine, uint256 gap, uint48 ttl, uint48 last, uint48 lastInc) = autoline.ilks(ilk);
uint256 nextLine = debt + gap;
if (nextLine > maxLine) nextLine = maxLine;
if (
nextLine != maxLine &&
debt + gap < line + gap * thi / BPS &&
debt + gap + gap * tlo / BPS > line
) continue;
return (true, address(autoline), abi.encodeWithSelector(AutoLineLike_1.exec.selector, ilk));
}
return (false, address(0), bytes("No ilks ready"));
}
function getNextJob(bytes32 network) external view override returns (bool, address, bytes memory) {
if (!sequencer.isMaster(network)) return (false, address(0), bytes("Network is not master"));
bytes32[] memory ilks = ilkRegistry.list();
for (uint256 i = 0; i < ilks.length; i++) {
bytes32 ilk = ilks[i];
(uint256 Art, uint256 rate,, uint256 line,) = vat.ilks(ilk);
uint256 debt = Art * rate;
(uint256 maxLine, uint256 gap, uint48 ttl, uint48 last, uint48 lastInc) = autoline.ilks(ilk);
uint256 nextLine = debt + gap;
if (nextLine > maxLine) nextLine = maxLine;
if (
nextLine != maxLine &&
debt + gap < line + gap * thi / BPS &&
debt + gap + gap * tlo / BPS > line
) continue;
return (true, address(autoline), abi.encodeWithSelector(AutoLineLike_1.exec.selector, ilk));
}
return (false, address(0), bytes("No ilks ready"));
}
} | 14,632,276 | [
1,
6518,
2059,
15572,
4533,
2511,
603,
19983,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
8064,
1670,
2278,
353,
467,
2278,
288,
203,
203,
565,
2254,
5034,
5381,
2713,
605,
5857,
273,
1728,
2826,
1059,
31,
203,
377,
203,
565,
3265,
372,
23568,
8804,
1071,
11732,
26401,
23568,
31,
203,
565,
467,
80,
79,
4243,
8804,
67,
21,
1071,
11732,
14254,
79,
4243,
31,
203,
565,
8064,
1670,
8804,
67,
21,
1071,
11732,
2059,
15572,
31,
203,
565,
25299,
8804,
67,
21,
1071,
11732,
17359,
31,
203,
203,
565,
3885,
12,
2867,
389,
307,
372,
23568,
16,
1758,
389,
330,
79,
4243,
16,
1758,
389,
5854,
15572,
16,
2254,
5034,
389,
451,
77,
16,
2254,
5034,
389,
88,
383,
13,
288,
203,
3639,
26401,
23568,
273,
3265,
372,
23568,
8804,
24899,
307,
372,
23568,
1769,
203,
3639,
14254,
79,
4243,
273,
467,
80,
79,
4243,
8804,
67,
21,
24899,
330,
79,
4243,
1769,
203,
3639,
2059,
15572,
273,
8064,
1670,
8804,
67,
21,
24899,
5854,
15572,
1769,
203,
3639,
17359,
273,
25299,
8804,
67,
21,
12,
5854,
15572,
18,
25012,
10663,
203,
3639,
286,
77,
273,
389,
451,
77,
31,
203,
3639,
268,
383,
273,
389,
88,
383,
31,
203,
565,
289,
203,
203,
565,
445,
6927,
2278,
12,
3890,
1578,
2483,
13,
3903,
1476,
3849,
1135,
261,
6430,
16,
1758,
16,
1731,
3778,
13,
288,
203,
3639,
309,
16051,
307,
372,
23568,
18,
291,
7786,
12,
5185,
3719,
327,
261,
5743,
16,
1758,
12,
20,
3631,
1731,
2932,
3906,
353,
486,
4171,
7923,
1769,
203,
540,
203,
3639,
1731,
1578,
8526,
3778,
14254,
7904,
273,
14254,
79,
2
] |
./full_match/44787/0xE9F7b882F1F46dade324B0B3F346FD446E5FC0cF/sources/contracts/v2/ExchangeService.sol | * @dev Implementation of the exchange service smart contract. The {ExchangeService} smart contract receives cUSD and ensures that the user receives from the basket service Nylon. The value of a Nylon is determined by the current value of Celo in relation to the USD (we are assuming that 1 cUSD = 1 USD). It uses the IWitnetPriceFeed to get accurate data of the current price of CELO/USD. Additionally, it includes the basket service (from where Nylon are send) and the IERC20 tokens of the cUSD and Celo. The {PriceChecker} library is used to calculate an accurate value of the send amount of cUSD. NOTE: For now, the exchange service only accepts cUSD./ IWitnetPriceFeed, see {https:explorer.celo.org/address/0x96E2278d67CB9Df8820Bb46b79d3dcf7Ea38c1e9/transactions} BasketService ERC20-tokens: cUSD and Celo | contract ExchangeService is Context {
using SafeERC20 for IERC20;
using PriceChecker for uint256;
IWitnetPriceFeed private immutable celoUsdPriceFeed;
BasketService private immutable basket;
IERC20 private immutable cUSD;
IERC20 private immutable celo;
pragma solidity ^0.8.11;
constructor(address _basket) {
celoUsdPriceFeed = IWitnetPriceFeed(
address(0x751906D7d41b71968d1B0b97fB6caE07e3e65CcF)
);
basket = BasketService(_basket);
cUSD = IERC20(0x874069Fa1Eb16D44d622F2e0Ca25eeA172369bC1);
celo = IERC20(0xF194afDf50B03e69Bd7D057c1Aa9e10c9954E4C9);
}
modifier sufficientBalance(uint256 _amount) {
require(
_amount > 10**15,
"Send amount of cUSD must be above the value of 0.001!"
);
require(
cUSD.balanceOf(_msgSender()) >= _amount,
"cUSD balance is insufficient!"
);
_;
}
function _contract() internal view virtual returns (address) {
return address(this);
}
function _celoUsdPrice()
internal
view
virtual
returns (uint256 _lastPrice)
{
_lastPrice = uint256(celoUsdPriceFeed.lastPrice());
}
function exchangeCUSD(uint256 _cUSD) external sufficientBalance(_cUSD) {
(, , uint256 celoValue) = _cUSD.valueOf(_celoUsdPrice());
require(
celo.balanceOf(_contract()) >= celoValue,
"Exchange doesn't hold enough Celo!"
);
cUSD.safeTransferFrom(_msgSender(), _contract(), _cUSD);
celo.safeTransfer(address(basket), celoValue);
basket.transferNylon(_msgSender(), celoValue);
}
}
| 13,260,684 | [
1,
13621,
434,
326,
7829,
1156,
13706,
6835,
18,
1021,
288,
11688,
1179,
97,
13706,
6835,
17024,
276,
3378,
40,
471,
11932,
716,
326,
729,
17024,
628,
326,
12886,
1156,
423,
93,
9379,
18,
1021,
460,
434,
279,
423,
93,
9379,
353,
11383,
635,
326,
783,
460,
434,
385,
24214,
316,
2533,
358,
326,
587,
9903,
261,
1814,
854,
15144,
716,
404,
276,
3378,
40,
273,
404,
587,
9903,
2934,
2597,
4692,
326,
467,
59,
305,
2758,
5147,
8141,
358,
336,
22380,
501,
434,
326,
783,
6205,
434,
29538,
1502,
19,
3378,
40,
18,
26775,
16,
518,
6104,
326,
12886,
1156,
261,
2080,
1625,
423,
93,
9379,
854,
1366,
13,
471,
326,
467,
654,
39,
3462,
2430,
434,
326,
276,
3378,
40,
471,
385,
24214,
18,
1021,
288,
5147,
8847,
97,
5313,
353,
1399,
358,
4604,
392,
22380,
460,
434,
326,
1366,
3844,
434,
276,
3378,
40,
18,
5219,
2
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1
] | [
1,
16351,
18903,
1179,
353,
1772,
288,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
20137,
8847,
364,
2254,
5034,
31,
203,
203,
565,
467,
59,
305,
2758,
5147,
8141,
3238,
11732,
276,
24214,
3477,
72,
5147,
8141,
31,
203,
565,
605,
7064,
1179,
3238,
11732,
12886,
31,
203,
203,
565,
467,
654,
39,
3462,
3238,
11732,
276,
3378,
40,
31,
203,
565,
467,
654,
39,
3462,
3238,
11732,
276,
24214,
31,
203,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
2499,
31,
203,
565,
3885,
12,
2867,
389,
26219,
13,
288,
203,
3639,
276,
24214,
3477,
72,
5147,
8141,
273,
467,
59,
305,
2758,
5147,
8141,
12,
203,
5411,
1758,
12,
20,
92,
5877,
3657,
7677,
40,
27,
72,
9803,
70,
27,
3657,
9470,
72,
21,
38,
20,
70,
10580,
74,
38,
26,
5353,
41,
8642,
73,
23,
73,
9222,
39,
71,
42,
13,
203,
3639,
11272,
203,
203,
3639,
12886,
273,
605,
7064,
1179,
24899,
26219,
1769,
203,
203,
3639,
276,
3378,
40,
273,
467,
654,
39,
3462,
12,
20,
92,
28,
5608,
7677,
29,
29634,
21,
41,
70,
2313,
40,
6334,
72,
26,
3787,
42,
22,
73,
20,
23508,
2947,
1340,
37,
4033,
4366,
8148,
70,
39,
21,
1769,
203,
3639,
276,
24214,
273,
467,
654,
39,
3462,
12,
20,
16275,
15613,
1727,
40,
74,
3361,
38,
4630,
73,
8148,
38,
72,
27,
40,
6260,
27,
71,
21,
37,
69,
29,
73,
2163,
71,
2733,
6564,
41,
24,
39,
29,
1769,
203,
2
] |
./partial_match/1/0x01E4543460347a3A77E094AB3E279932d1cAe050/sources/FenixToken.sol | * @dev Sets `feeShare` for share percentage for every app transaction. Requirements: - `value` integer./ | function setTransferFee(uint value) onlyOwner public returns (bool) {
require(value < 100);
feeShare = value;
}
| 3,685,653 | [
1,
2785,
1375,
21386,
9535,
68,
364,
7433,
11622,
364,
3614,
595,
2492,
18,
29076,
30,
300,
1375,
1132,
68,
3571,
18,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
444,
5912,
14667,
12,
11890,
460,
13,
1338,
5541,
1071,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
1132,
411,
2130,
1769,
203,
3639,
14036,
9535,
273,
460,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0x78BD25aB3fA11A5da06c9299e109Fb18840135F3/sources/FairLaunch.sol | AKITA tokens created per block. | uint256 public akitaPerBlock;
| 11,211,029 | [
1,
14607,
1285,
37,
2430,
2522,
1534,
1203,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
225,
2254,
5034,
1071,
279,
8691,
69,
2173,
1768,
31,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0x669852D9020A1397564DF15533A832314d377318/sources/GoVitalik.sol | check trading open required for wallet distribution | function _transfer(
address sender,
address recipient,
uint256 amount
) private returns (bool) {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
if (!tradingOpen) {
require(
sender == owner(),
"TOKEN: This account cannot send tokens until trading is enabled"
);
}
if (inSwapAndLiquify) {
return _basicTransfer(sender, recipient, amount);
if (sender != owner() && recipient != owner()) {
_checkTxLimit(sender, amount);
}
bool overMinimumTokenBalance = contractTokenBalance >=
minimumTokensBeforeSwap;
if (
overMinimumTokenBalance &&
!inSwapAndLiquify &&
!isMarketPair[sender]
) {
swapAndLiquify(contractTokenBalance);
}
amount,
"Insufficient Balance"
);
uint256 finalAmount = (isExcludedFromFee[sender] ||
isExcludedFromFee[recipient])
? amount
: takeFee(sender, recipient, amount);
require(balanceOf(recipient).add(finalAmount) <= _walletMax);
emit Transfer(sender, recipient, finalAmount);
return true;
}
}
| 15,941,840 | [
1,
1893,
1284,
7459,
1696,
1931,
364,
9230,
7006,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
13866,
12,
203,
3639,
1758,
5793,
16,
203,
3639,
1758,
8027,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
3238,
1135,
261,
6430,
13,
288,
203,
3639,
2583,
12,
15330,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
628,
326,
3634,
1758,
8863,
203,
3639,
2583,
12,
20367,
480,
1758,
12,
20,
3631,
315,
654,
39,
3462,
30,
7412,
358,
326,
3634,
1758,
8863,
203,
203,
3639,
309,
16051,
313,
14968,
3678,
13,
288,
203,
5411,
2583,
12,
203,
7734,
5793,
422,
3410,
9334,
203,
7734,
315,
8412,
30,
1220,
2236,
2780,
1366,
2430,
3180,
1284,
7459,
353,
3696,
6,
203,
5411,
11272,
203,
3639,
289,
203,
203,
3639,
309,
261,
267,
12521,
1876,
48,
18988,
1164,
13,
288,
203,
5411,
327,
389,
13240,
5912,
12,
15330,
16,
8027,
16,
3844,
1769,
203,
5411,
309,
261,
15330,
480,
3410,
1435,
597,
8027,
480,
3410,
10756,
288,
203,
7734,
389,
1893,
4188,
3039,
12,
15330,
16,
3844,
1769,
203,
5411,
289,
203,
203,
5411,
1426,
1879,
13042,
1345,
13937,
273,
6835,
1345,
13937,
1545,
203,
7734,
5224,
5157,
4649,
12521,
31,
203,
5411,
309,
261,
203,
7734,
1879,
13042,
1345,
13937,
597,
203,
7734,
401,
267,
12521,
1876,
48,
18988,
1164,
597,
203,
7734,
401,
291,
3882,
278,
4154,
63,
15330,
65,
203,
5411,
262,
288,
203,
7734,
7720,
1876,
48,
18988,
1164,
12,
16351,
1345,
13937,
1769,
203,
5411,
289,
203,
203,
7734,
3844,
16,
203,
7734,
315,
5048,
11339,
30918,
6,
203,
5411,
11272,
203,
5411,
2
] |
./full_match/1/0x0648D28ec4190318110BDA59d3096d971a2AA856/sources/Swap.sol | Get Pair Get Reserves Token Transfer Get Output Amount Call Swap | function _uniswapV2Swap(
uint256 inputAmount,
Pair memory pairInfo
) internal {
IUniswapV2Pair pair = IUniswapV2Pair(pairInfo.pair);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 reserveInput = pairInfo.isReserveIn ? reserve0 : reserve1;
TokenInterface(pairInfo.tokenIn).safeTransfer(
address(pairInfo.pair),
inputAmount
);
inputAmount = TokenInterface(pairInfo.tokenIn).balanceOf(address(pairInfo.pair)).sub(reserveInput);
uint256 outputAmount = _getAmountOut(
pairInfo.isReserveIn,
inputAmount,
reserve0,
reserve1
);
(uint256 amount0Out, uint256 amount1Out) =
pairInfo.isReserveIn
? (uint256(0), outputAmount)
: (outputAmount, uint256(0));
pair.swap(amount0Out, amount1Out, address(this), new bytes(0));
}
| 3,132,067 | [
1,
967,
8599,
968,
1124,
264,
3324,
3155,
12279,
968,
3633,
16811,
3049,
12738,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
389,
318,
291,
91,
438,
58,
22,
12521,
12,
203,
3639,
2254,
5034,
810,
6275,
16,
377,
203,
3639,
8599,
3778,
3082,
966,
203,
565,
262,
2713,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
4154,
3082,
273,
467,
984,
291,
91,
438,
58,
22,
4154,
12,
6017,
966,
18,
6017,
1769,
203,
3639,
261,
11890,
5034,
20501,
20,
16,
2254,
5034,
20501,
21,
16,
262,
273,
3082,
18,
588,
607,
264,
3324,
5621,
203,
3639,
2254,
5034,
20501,
1210,
273,
3082,
966,
18,
291,
607,
6527,
382,
692,
20501,
20,
294,
20501,
21,
31,
203,
203,
3639,
29938,
12,
6017,
966,
18,
2316,
382,
2934,
4626,
5912,
12,
203,
5411,
1758,
12,
6017,
966,
18,
6017,
3631,
203,
5411,
810,
6275,
203,
3639,
11272,
203,
3639,
810,
6275,
273,
29938,
12,
6017,
966,
18,
2316,
382,
2934,
12296,
951,
12,
2867,
12,
6017,
966,
18,
6017,
13,
2934,
1717,
12,
455,
6527,
1210,
1769,
203,
203,
3639,
2254,
5034,
876,
6275,
273,
389,
588,
6275,
1182,
12,
203,
5411,
3082,
966,
18,
291,
607,
6527,
382,
16,
203,
5411,
810,
6275,
16,
203,
5411,
20501,
20,
16,
203,
5411,
20501,
21,
203,
3639,
11272,
4202,
203,
203,
3639,
261,
11890,
5034,
3844,
20,
1182,
16,
2254,
5034,
3844,
21,
1182,
13,
273,
203,
5411,
3082,
966,
18,
291,
607,
6527,
382,
203,
7734,
692,
261,
11890,
5034,
12,
20,
3631,
876,
6275,
13,
203,
7734,
294,
261,
2844,
6275,
16,
2254,
5034,
12,
20,
10019,
203,
203,
3639,
3082,
2
] |
./partial_match/56/0xd4cC0C9a71Cb716097B753eE45FEB83a758B1fbF/sources/STEAMER.sol | / is the token balance of this contract address over the min number of tokens that we need to initiate a swap + liquidity lock? also, don't get caught in a circular liquidity event. also, don't swap & liquify if sender is uniswap pair. | override the internal _transfer function so that we can do the swap + liquditiy
function _transfer(
address from,
address to,
uint256 amount
) internal override {
require(amount > 0, "Transfer amount must be greater than zero");
if(from != owner() && to != owner()) {
if((from == _pancakeWaterBNBPool || to == _pancakeWaterBNBPool) && !tradingEnable)
require(false, "ERC20: trading disabled yet");
}
amount,
feeDecimals,
feePercentage
);
super._transfer(from, address(this), tokensToLock);
super._transfer(from, to, tokensToTransfer);
}
| 11,059,017 | [
1,
19,
353,
326,
1147,
11013,
434,
333,
6835,
1758,
1879,
326,
1131,
1300,
434,
2430,
716,
732,
1608,
358,
18711,
279,
7720,
397,
4501,
372,
24237,
2176,
35,
2546,
16,
2727,
1404,
336,
13537,
316,
279,
15302,
4501,
372,
24237,
871,
18,
2546,
16,
2727,
1404,
7720,
473,
4501,
372,
1164,
309,
5793,
353,
640,
291,
91,
438,
3082,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
3849,
326,
2713,
389,
13866,
445,
1427,
716,
732,
848,
741,
326,
7720,
397,
4501,
372,
72,
305,
77,
93,
203,
565,
445,
389,
13866,
12,
203,
3639,
1758,
628,
16,
203,
3639,
1758,
358,
16,
203,
3639,
2254,
5034,
3844,
203,
565,
262,
2713,
3849,
288,
203,
3639,
2583,
12,
8949,
405,
374,
16,
315,
5912,
3844,
1297,
506,
6802,
2353,
3634,
8863,
203,
3639,
309,
12,
2080,
480,
3410,
1435,
597,
358,
480,
3410,
10756,
288,
203,
5411,
309,
12443,
2080,
422,
389,
7355,
23780,
24064,
15388,
38,
2864,
747,
358,
422,
389,
7355,
23780,
24064,
15388,
38,
2864,
13,
597,
401,
313,
14968,
8317,
13,
203,
7734,
2583,
12,
5743,
16,
315,
654,
39,
3462,
30,
1284,
7459,
5673,
4671,
8863,
203,
3639,
289,
203,
203,
5411,
3844,
16,
203,
5411,
14036,
31809,
16,
203,
5411,
14036,
16397,
203,
3639,
11272,
203,
203,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
1758,
12,
2211,
3631,
2430,
774,
2531,
1769,
203,
3639,
2240,
6315,
13866,
12,
2080,
16,
358,
16,
2430,
774,
5912,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/1/0xc5a3b5b534A5404C72e75D803404aFD866A4EB24/sources/contracts/HexCombinator.sol | @notice Deposit HEX and bridged HEX on whichever network you are on to mint CHEX. 1 CHEX = 1 eHEX + 1 pHEX. You must grant this contract the appropriate approvals. Transaction must include the flat rate arbitrage throttle, paid in ETH or PLS. | function mint(uint256 amount) external payable nonReentrant{
require(msg.value == arbitrage_throttle, "Transaction must include the arbitrage throttle.");
IERC20(HEX_ADDRESS).transferFrom(msg.sender, address(this), amount);
IERC20(getAddress()).transferFrom(msg.sender, address(this), amount);
_mint(msg.sender, amount);
emit Minted(msg.sender, amount);
}
| 17,165,105 | [
1,
758,
1724,
23971,
471,
324,
1691,
2423,
23971,
603,
600,
335,
580,
502,
2483,
1846,
854,
603,
358,
312,
474,
6469,
2294,
18,
404,
6469,
2294,
273,
404,
425,
20661,
397,
404,
293,
20661,
18,
4554,
1297,
7936,
333,
6835,
326,
5505,
6617,
4524,
18,
5947,
1297,
2341,
326,
3569,
4993,
10056,
86,
410,
18304,
16,
30591,
316,
512,
2455,
578,
453,
3045,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12,
11890,
5034,
3844,
13,
3903,
8843,
429,
1661,
426,
8230,
970,
95,
203,
3639,
2583,
12,
3576,
18,
1132,
422,
10056,
86,
410,
67,
27971,
298,
16,
315,
3342,
1297,
2341,
326,
10056,
86,
410,
18304,
1199,
1769,
203,
3639,
467,
654,
39,
3462,
12,
20661,
67,
15140,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
3639,
467,
654,
39,
3462,
12,
588,
1887,
1435,
2934,
13866,
1265,
12,
3576,
18,
15330,
16,
1758,
12,
2211,
3631,
3844,
1769,
203,
3639,
389,
81,
474,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
3639,
3626,
490,
474,
329,
12,
3576,
18,
15330,
16,
3844,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./full_match/4/0x536305Fbb4Bf4E9247CDe6CD92A11Ea28083ce9e/sources/contracts/project1/RouterContract.sol | require( IERC20(addOfBNB).balanceOf(msg.sender) >=amount ,'insufficient balanceOf' ); | function DepositBNB(uint amount)public{
require(amount > 0 , "amont should be > 0");
uint distributedAmount = amount/3 ;
address[] memory pathA ;
pathA = new address[](2);
pathA[0] = 0xD0Aa029cB7Ee427794a1060D7c98a2b9D8279bca ;
pathA[1] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ;
address[] memory pathC ;
pathC = new address[](2);
pathC[0] = 0xb11887070842140bfe6d94228972Dc3c2c00B5d7 ;
pathC[1] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ;
address[] memory pathB ;
pathB = new address[](2);
pathB[0] = 0x28A9e3c379Cd845134500AA7b8964e0d20be1911 ;
pathB[1] = 0xf50E2F9430C1B080640eB8cd926723AA7B6c900a ;
IERC20(addOfBNB).approve(msg.sender , amount) ;
UniswapV2Router02(addOfRouter).swapExactTokensForTokens(distributedAmount , distributedAmount , pathA,msg.sender,7 );
UniswapV2Router02(addOfRouter).swapExactTokensForTokens(distributedAmount , distributedAmount , pathB,msg.sender,7 );
UniswapV2Router02(addOfRouter).swapExactTokensForTokens(distributedAmount , distributedAmount , pathC,msg.sender,7 );
}
| 748,613 | [
1,
6528,
12,
467,
654,
39,
3462,
12,
1289,
951,
15388,
38,
2934,
12296,
951,
12,
3576,
18,
15330,
13,
1545,
8949,
269,
11,
2679,
11339,
11013,
951,
11,
11272,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
377,
445,
4019,
538,
305,
15388,
38,
12,
11890,
3844,
13,
482,
95,
203,
540,
2583,
12,
8949,
405,
374,
269,
315,
301,
1580,
1410,
506,
405,
374,
8863,
203,
540,
2254,
16859,
6275,
225,
273,
3844,
19,
23,
274,
7010,
203,
540,
1758,
8526,
3778,
589,
37,
274,
203,
540,
589,
37,
273,
394,
1758,
8526,
12,
22,
1769,
203,
540,
589,
37,
63,
20,
65,
273,
374,
17593,
20,
37,
69,
3103,
29,
71,
38,
27,
41,
73,
9452,
4700,
11290,
69,
2163,
4848,
40,
27,
71,
10689,
69,
22,
70,
29,
40,
28,
5324,
29,
70,
5353,
274,
7010,
540,
589,
37,
63,
21,
65,
273,
374,
5841,
3361,
41,
22,
42,
11290,
5082,
39,
21,
38,
20,
3672,
1105,
20,
73,
38,
28,
4315,
29,
5558,
27,
4366,
5284,
27,
38,
26,
71,
29,
713,
69,
274,
7010,
203,
540,
1758,
8526,
3778,
589,
39,
274,
203,
540,
589,
39,
273,
394,
1758,
8526,
12,
22,
1769,
203,
540,
589,
39,
63,
20,
65,
273,
374,
6114,
2499,
5482,
7301,
7301,
5193,
22,
27092,
70,
3030,
26,
72,
11290,
3787,
6675,
9060,
40,
71,
23,
71,
22,
71,
713,
38,
25,
72,
27,
274,
7010,
540,
589,
39,
63,
21,
65,
273,
374,
5841,
3361,
41,
22,
42,
11290,
5082,
39,
21,
38,
20,
3672,
1105,
20,
73,
38,
28,
4315,
29,
5558,
27,
4366,
5284,
27,
38,
26,
71,
29,
713,
69,
274,
7010,
203,
3639,
1758,
8526,
3778,
589,
38,
274,
203,
540,
589,
38,
273,
394,
1758,
2
] |
./partial_match/42/0xe4380E034f5816c6A4db4419a3a1fFE78F976f8f/sources/WETHpartyStarter.sol | File: contracts/CloneParty.sol=====================USE AT YOUR OWN RISK HARD-CODED LIMITS These numbers are quite arbitrary; they are small enough to avoid overflows when doing calculations with periods or shares, yet big enough to not limit reasonable use cases. default = 5 *************** EVENTS *************** ******************* INTERNAL ACCOUNTING ******************* | contract WETHParty is ReentrancyGuard {
using SafeMath for uint256;
using SafeERC20 for IERC20;
GOVERNANCE PARAMS
uint256 public dilutionBound;
address public wETH;
bool public initialized;
event SummonComplete(address[] indexed summoners, address[] tokens, uint256 summoningTime, uint256 periodDuration, uint256 votingPeriodLength, uint256 gracePeriodLength, uint256 proposalDepositReward, uint256 partyGoal, uint256 depositRate);
event MakeDeposit(address indexed memberAddress, uint256 tribute, uint256 mintedTokens, uint256 indexed shares, uint8 goalHit);
event ProcessAmendGovernance(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass, address newToken, address newIdle, uint256 newPartyGoal, uint256 newDepositRate);
event SubmitProposal(address indexed applicant, uint256 sharesRequested, uint256 lootRequested, uint256 tributeOffered, address tributeToken, uint256 paymentRequested, address paymentToken, bytes32 details, bool[8] flags, uint256 proposalId, address indexed delegateKey, address indexed memberAddress);
event SponsorProposal(address indexed sponsor, address indexed memberAddress, uint256 proposalId, uint256 proposalIndex, uint256 startingPeriod);
event SubmitVote(uint256 proposalId, uint256 indexed proposalIndex, address indexed delegateKey, address indexed memberAddress, uint8 uintVote);
event ProcessProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event ProcessGuildKickProposal(uint256 indexed proposalIndex, uint256 indexed proposalId, bool didPass);
event Ragequit(address indexed memberAddress, uint256 sharesToBurn, uint256 lootToBurn);
event TokensCollected(address indexed token, uint256 amountToCollect);
event CancelProposal(uint256 indexed proposalId, address applicantAddress);
event UpdateDelegateKey(address indexed memberAddress, address newDelegateKey);
event WithdrawEarnings(address indexed memberAddress, address wETH, uint256 earningsToUser, address depositToken);
event Withdraw(address indexed memberAddress, address token, uint256 amount);
address public constant GUILD = address(0xdead);
address public constant ESCROW = address(0xbeef);
address public constant TOTAL = address(0xbabe);
function balanceOf(address who) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
}
using Address for address;
}
}
}
}
}
bool private _notEntered;
}
}
}
WELCOME TO THE POOL Party vWETH
Forked from an early version of the permissioned Mystic v2x by LexDAO
Special thanks to LexDAO for pushing the boundaries of Moloch mysticism
Developed by Peeps Democracy
MIT License - But please use for good (ie. don't be a dick).
Definitely NO WARRANTIES.
=======================*/
enum Vote {
Yes,
No
}
struct Member {
}
struct Proposal {
}
mapping(address => bool) public tokenWhitelist;
address[] public approvedTokens;
mapping(address => bool) public proposedToKick;
mapping(address => Member) public members;
address[] public memberList;
mapping(uint256 => Proposal) public proposals;
uint256[] public proposalQueue;
SUMMONING FUNCTIONS
function init(
address[] calldata _founders,
address[] calldata _approvedTokens,
address _daoFee,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _proposalDepositReward,
uint256 _depositRate,
uint256 _partyGoal,
uint256 _dilutionBound
) external {
require(!initialized, "initialized");
initialized = true;
require(_periodDuration > 0, "_periodDuration zeroed");
require(_votingPeriodLength > 0, "_votingPeriodLength zeroed");
require(_votingPeriodLength <= MAX_INPUT, "_votingPeriodLength maxed");
require(_gracePeriodLength <= MAX_INPUT, "_gracePeriodLength maxed");
require(_approvedTokens.length > 0, "need token");
depositToken = _approvedTokens[0];
wETH = _approvedTokens[0];
emit SummonComplete(_founders, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDepositReward, _depositRate, _partyGoal);
for (uint256 i = 0; i < _approvedTokens.length; i++) {
require(!tokenWhitelist[_approvedTokens[i]], "token duplicated");
tokenWhitelist[_approvedTokens[i]] = true;
approvedTokens.push(_approvedTokens[i]);
}
for (uint256 i = 0; i < _founders.length; i++) {
_addFounder(_founders[i]);
}
daoFee = _daoFee;
periodDuration = _periodDuration;
votingPeriodLength = _votingPeriodLength;
gracePeriodLength = _gracePeriodLength;
proposalDepositReward = _proposalDepositReward;
depositRate = _depositRate;
partyGoal = _partyGoal;
summoningTime = now;
goalHit = 0;
dilutionBound = _dilutionBound;
_initReentrancyGuard();
}
function init(
address[] calldata _founders,
address[] calldata _approvedTokens,
address _daoFee,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _proposalDepositReward,
uint256 _depositRate,
uint256 _partyGoal,
uint256 _dilutionBound
) external {
require(!initialized, "initialized");
initialized = true;
require(_periodDuration > 0, "_periodDuration zeroed");
require(_votingPeriodLength > 0, "_votingPeriodLength zeroed");
require(_votingPeriodLength <= MAX_INPUT, "_votingPeriodLength maxed");
require(_gracePeriodLength <= MAX_INPUT, "_gracePeriodLength maxed");
require(_approvedTokens.length > 0, "need token");
depositToken = _approvedTokens[0];
wETH = _approvedTokens[0];
emit SummonComplete(_founders, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDepositReward, _depositRate, _partyGoal);
for (uint256 i = 0; i < _approvedTokens.length; i++) {
require(!tokenWhitelist[_approvedTokens[i]], "token duplicated");
tokenWhitelist[_approvedTokens[i]] = true;
approvedTokens.push(_approvedTokens[i]);
}
for (uint256 i = 0; i < _founders.length; i++) {
_addFounder(_founders[i]);
}
daoFee = _daoFee;
periodDuration = _periodDuration;
votingPeriodLength = _votingPeriodLength;
gracePeriodLength = _gracePeriodLength;
proposalDepositReward = _proposalDepositReward;
depositRate = _depositRate;
partyGoal = _partyGoal;
summoningTime = now;
goalHit = 0;
dilutionBound = _dilutionBound;
_initReentrancyGuard();
}
function init(
address[] calldata _founders,
address[] calldata _approvedTokens,
address _daoFee,
uint256 _periodDuration,
uint256 _votingPeriodLength,
uint256 _gracePeriodLength,
uint256 _proposalDepositReward,
uint256 _depositRate,
uint256 _partyGoal,
uint256 _dilutionBound
) external {
require(!initialized, "initialized");
initialized = true;
require(_periodDuration > 0, "_periodDuration zeroed");
require(_votingPeriodLength > 0, "_votingPeriodLength zeroed");
require(_votingPeriodLength <= MAX_INPUT, "_votingPeriodLength maxed");
require(_gracePeriodLength <= MAX_INPUT, "_gracePeriodLength maxed");
require(_approvedTokens.length > 0, "need token");
depositToken = _approvedTokens[0];
wETH = _approvedTokens[0];
emit SummonComplete(_founders, _approvedTokens, now, _periodDuration, _votingPeriodLength, _gracePeriodLength, _proposalDepositReward, _depositRate, _partyGoal);
for (uint256 i = 0; i < _approvedTokens.length; i++) {
require(!tokenWhitelist[_approvedTokens[i]], "token duplicated");
tokenWhitelist[_approvedTokens[i]] = true;
approvedTokens.push(_approvedTokens[i]);
}
for (uint256 i = 0; i < _founders.length; i++) {
_addFounder(_founders[i]);
}
daoFee = _daoFee;
periodDuration = _periodDuration;
votingPeriodLength = _votingPeriodLength;
gracePeriodLength = _gracePeriodLength;
proposalDepositReward = _proposalDepositReward;
depositRate = _depositRate;
partyGoal = _partyGoal;
summoningTime = now;
goalHit = 0;
dilutionBound = _dilutionBound;
_initReentrancyGuard();
}
function _addFounder(address founder) internal {
members[founder] = Member(0, 0, 0, 0, 0, 0, false, true);
memberList.push(founder);
}
function _setWETH(address _wETH) internal {
wETH = _wETH;
}
PROPOSAL FUNCTIONS
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
(bool success,) = wETH.call{value: msg.value}("");
} else {
require(IERC20(depositToken).transferFrom(msg.sender, address(this), proposalDepositReward), "proposal deposit failed");
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
function submitProposal(
address applicant,
uint256 tributeOffered,
uint256 sharesRequested,
uint256 lootRequested,
uint256 paymentRequested,
uint256 flagNumber,
address tributeToken,
address paymentToken,
bytes32 details
) public payable nonReentrant returns (uint256 proposalId) {
require(sharesRequested.add(lootRequested) <= MAX_INPUT, "shares maxed");
if(flagNumber != 7){
require(tokenWhitelist[tributeToken] && tokenWhitelist[paymentToken], "tokens not whitelisted");
if (msg.value > 0) {
require(tributeToken == wETH && msg.value == tributeOffered, "!ethBalance");
require(success, "!ethCall");
IERC20(wETH).safeTransfer(address(this), msg.value);
IERC20(tributeToken).safeTransferFrom(msg.sender, address(this), tributeOffered);
}
unsafeAddToBalance(ESCROW, tributeToken, tributeOffered);
}
require(applicant != address(0), "applicant cannot be 0");
require(members[applicant].jailed == false, "applicant jailed");
require(flagNumber != 0 || flagNumber != 1 || flagNumber != 2 || flagNumber != 3, "flag must be 4 - guildkick, 5 - spending, 6 - membership, 7 - governance");
unsafeAddToBalance(ESCROW, paymentToken, proposalDepositReward);
if(flagNumber == 5) {
require(goalHit == 1, "goal not met yet");
}
if(flagNumber == 6) {
require(paymentRequested == 0 || goalHit == 1, "goal not met yet");
}
flags[flagNumber] = true;
if(flagNumber == 4) {
_submitProposal(applicant, 0, 0, 0, address(0), 0, address(0), details, flags);
}
_submitProposal(applicant, 0, 0, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
else {
_submitProposal(applicant, sharesRequested, lootRequested, tributeOffered, tributeToken, paymentRequested, paymentToken, details, flags);
}
}
| 3,346,381 | [
1,
812,
30,
20092,
19,
10930,
17619,
18,
18281,
2429,
894,
33,
8001,
14464,
1624,
51,
1099,
531,
5665,
534,
5127,
47,
670,
8085,
17,
9086,
2056,
13052,
10158,
8646,
5600,
854,
25102,
11078,
31,
2898,
854,
5264,
7304,
358,
4543,
9391,
87,
1347,
9957,
20882,
598,
12777,
578,
24123,
16,
4671,
5446,
7304,
358,
486,
1800,
23589,
999,
6088,
18,
805,
273,
1381,
225,
9964,
55,
282,
18139,
29437,
1360,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
678,
1584,
44,
17619,
353,
868,
8230,
12514,
16709,
288,
203,
565,
1450,
14060,
10477,
364,
2254,
5034,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
377,
203,
565,
12389,
2204,
50,
4722,
4655,
55,
203,
565,
2254,
5034,
1071,
302,
330,
1421,
3499,
31,
203,
203,
565,
1758,
1071,
341,
1584,
44,
31,
203,
377,
203,
565,
1426,
1071,
6454,
31,
203,
203,
203,
203,
565,
871,
9352,
2586,
6322,
12,
2867,
8526,
8808,
2142,
2586,
414,
16,
1758,
8526,
2430,
16,
2254,
5034,
2142,
2586,
310,
950,
16,
2254,
5034,
3879,
5326,
16,
2254,
5034,
331,
17128,
5027,
1782,
16,
2254,
5034,
13658,
5027,
1782,
16,
2254,
5034,
14708,
758,
1724,
17631,
1060,
16,
2254,
5034,
18285,
27716,
16,
2254,
5034,
443,
1724,
4727,
1769,
203,
565,
871,
4344,
758,
1724,
12,
2867,
8808,
3140,
1887,
16,
2254,
5034,
433,
495,
624,
16,
2254,
5034,
312,
474,
329,
5157,
16,
2254,
5034,
8808,
24123,
16,
2254,
28,
17683,
13616,
1769,
203,
565,
871,
4389,
9864,
409,
43,
1643,
82,
1359,
12,
11890,
5034,
8808,
14708,
1016,
16,
2254,
5034,
8808,
14708,
548,
16,
1426,
5061,
6433,
16,
1758,
394,
1345,
16,
1758,
394,
13834,
16,
2254,
5034,
394,
17619,
27716,
16,
2254,
5034,
394,
758,
1724,
4727,
1769,
377,
203,
565,
871,
17320,
14592,
12,
2867,
8808,
513,
1780,
970,
16,
2254,
5034,
24123,
11244,
16,
2254,
5034,
437,
352,
11244,
16,
2254,
5034,
433,
495,
624,
10513,
329,
16,
1758,
433,
495,
624,
2
] |
./full_match/4/0xfB8e42E6E9E6f275ebe9DFd15e8D3878aC4C03c2/sources/LPBond.sol | Info for creating new bonds | contract TimeBondDepository is Ownable {
using FixedPoint for *;
using SafeERC20 for IERC20;
using SafeMath for uint;
using SafeMath for uint32;
event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD );
event BondRedeemed( address indexed recipient, uint payout, uint remaining );
event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio );
event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition );
bool public useHelper;
struct Terms {
}
struct Bond {
}
struct Adjust {
}
constructor (
address _Time,
address _principle,
address _treasury,
address _DAO,
address _bondCalculator
) {
require( _Time != address(0) );
Time = _Time;
require( _principle != address(0) );
principle = _principle;
require( _treasury != address(0) );
treasury = _treasury;
require( _DAO != address(0) );
DAO = _DAO;
bondCalculator = _bondCalculator;
isLiquidityBond = ( _bondCalculator != address(0) );
}
function initializeBondTerms(
uint _controlVariable,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt,
uint32 _vestingTerm
) external onlyPolicy() {
require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt,
vestingTerm: _vestingTerm
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
function initializeBondTerms(
uint _controlVariable,
uint _minimumPrice,
uint _maxPayout,
uint _fee,
uint _maxDebt,
uint _initialDebt,
uint32 _vestingTerm
) external onlyPolicy() {
require( terms.controlVariable == 0, "Bonds must be initialized from 0" );
terms = Terms ({
controlVariable: _controlVariable,
minimumPrice: _minimumPrice,
maxPayout: _maxPayout,
fee: _fee,
maxDebt: _maxDebt,
vestingTerm: _vestingTerm
});
totalDebt = _initialDebt;
lastDecay = uint32(block.timestamp);
}
enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE }
function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() {
require( _input >= 129600, "Vesting must be longer than 36 hours" );
terms.vestingTerm = uint32(_input);
require( _input <= 1000, "Payout cannot be above 1 percent" );
terms.maxPayout = _input;
require( _input <= 10000, "DAO fee cannot exceed payout" );
terms.fee = _input;
terms.maxDebt = _input;
terms.minimumPrice = _input;
}
}
| 677,794 | [
1,
966,
364,
4979,
394,
15692,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
16351,
2647,
9807,
758,
1855,
353,
14223,
6914,
288,
203,
203,
565,
1450,
15038,
2148,
364,
380,
31,
203,
565,
1450,
14060,
654,
39,
3462,
364,
467,
654,
39,
3462,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
31,
203,
565,
1450,
14060,
10477,
364,
2254,
1578,
31,
203,
203,
203,
203,
203,
203,
565,
871,
605,
1434,
6119,
12,
2254,
443,
1724,
16,
2254,
8808,
293,
2012,
16,
2254,
8808,
7368,
16,
2254,
8808,
6205,
382,
3378,
40,
11272,
203,
565,
871,
605,
1434,
426,
24903,
329,
12,
1758,
8808,
8027,
16,
2254,
293,
2012,
16,
2254,
4463,
11272,
203,
565,
871,
605,
1434,
5147,
5033,
12,
2254,
8808,
6205,
382,
3378,
40,
16,
2254,
8808,
2713,
5147,
16,
2254,
8808,
18202,
88,
8541,
11272,
203,
565,
871,
8888,
3092,
19985,
12,
2254,
2172,
16283,
58,
16,
2254,
394,
16283,
58,
16,
2254,
18335,
16,
1426,
2719,
11272,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1426,
1071,
999,
2276,
31,
203,
203,
203,
203,
203,
203,
203,
203,
203,
565,
1958,
26563,
288,
203,
565,
289,
203,
203,
565,
1958,
605,
1434,
288,
203,
565,
289,
203,
203,
565,
1958,
17720,
288,
203,
565,
289,
203,
203,
203,
203,
203,
565,
3885,
261,
7010,
3639,
1758,
389,
950,
16,
203,
3639,
1758,
389,
683,
9523,
2444,
16,
203,
3639,
1758,
389,
27427,
345,
22498,
16,
7010,
3639,
1758,
389,
18485,
16,
7010,
3639,
1758,
389,
26425,
19278,
203,
203,
565,
262,
288,
203,
3639,
2583,
12,
389,
950,
480,
1758,
12,
2
] |
/**
*Submitted for verification at Etherscan.io on 2021-09-06
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: 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) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* ////IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import "./IERC20.sol";
////import "../../utils/Context.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 {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @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 this function is
* overloaded;
*
* 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 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
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);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += 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 += amount;
_balances[account] += 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);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= 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 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-FLATTEN-SUPPRESS-WARNING: 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 () {
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-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
interface IMinerV1{
function accountStoked(address addr) external view returns (uint256);
function totalStoke() external view returns (uint256);
function userTimes(address) external view returns (uint256);
function totalMineds( address ) external view returns (uint256);
// function current() external view returns (uint256);//private,don't call
function earnedBalance( address ) external view returns (uint256);
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
contract DEBIToken is ERC20 {
constructor() ERC20("DeerBit Token","DEBI") {
_mint(msg.sender, 100000000000 * 1e8);
}
function decimals() public pure override returns (uint8){
return 8;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import '@openzeppelin/contracts/token/ERC20/ERC20.sol';
////import "@openzeppelin/contracts/access/Ownable.sol";
// ////import './libraries/Strings.sol';
contract DBLendToken is ERC20,Ownable {
// using Strings for *;
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
address public miner;
address public timelock;
/// @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 (uint256 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint256) 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 => uint256) public nonces;
/// @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, uint256 previousBalance, uint256 newBalance);
constructor() ERC20("DBLend Line","DBL"){
_mint(msg.sender, 2100000*1e8);//Total 2100000 DBL
// timelock = _timelock;
//_delegate(address(this), address(this));
//numCheckpoints[address(this)] = 2100000*1e8;
}
function decimals() public pure override returns (uint8) {
return 8;
}
function totalSupply() public view override returns (uint256) {
return 2100000*1e8 - balanceOf(address(this));
}
///@dev init miner and approve miner transfer dbl
function initMiner(address _minerAddress) external onlyOwner returns (uint256){
require(miner == address(0), "DBL: INIT ONLY ONCE");
require(_minerAddress != address(0), "DBL: NOT VALID MINER");
return approveMiner(_minerAddress);
}
///@dev update timelock,if timelock has been set, only timelock can be call. Otherwise the owner can call.
function updateTimelock(address _timelock) external {
require((timelock == address(0) && msg.sender == owner()) || msg.sender == timelock, "NO PERMISSION");
require(_timelock != address(0),"INVALID ADDRESS");
timelock = _timelock;
}
///@dev replace miner through governance voting,if timelock is not set, the owner can operate.
function _setMiner(address _minerAddress) external {
require(msg.sender == timelock || (timelock == address(0) && msg.sender == owner()), "DBL: NEED TIMELOCK OR OWNER");
approveMiner(_minerAddress);
}
///@dev DBLToken contract approve Miner Contract to spend all dbl
function approveMiner(address _minerAddress) internal returns (uint256){
//////importance,prevent delegatecall attack
if(!isContract(_minerAddress)) return 0;
uint256 balance = balanceOf(address(this));
_approve(address(this), _minerAddress, 2100000 * 1e8);
miner = _minerAddress;
return balance;
}
///@dev Miner mint,actually transfer from address(this) to _account
function mint(address _account, uint256 _amount) public returns (bool){
require(msg.sender == miner, "DEL:ONLY MINER");
return transferFrom(address(this), _account, _amount);
}
///@dev DBL token can be transferred through governance voting
// function govTransfer(address _receipt, uint256 _amount) public returns (bool){
// require(msg.sender == timelock, "DBL:ONLY TIMELOCK");
// uint256 balance = balanceOf(address(this));
// if(_amount > balance) _amount = balance;
// return transferFrom(address(this), _account, _amount);
// }
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;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
_transfer(_msgSender(), recipient, amount);
if(recipient == address(this)){
recipient = address(0);
}
_moveDelegates(delegates[_msgSender()], delegates[recipient], amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = allowance(sender,_msgSender());
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
//如果是挖矿铸币,则src为0,不需要记录本地的投票数据
if(sender == address(this)){
sender = address(0);
}
_moveDelegates(delegates[sender], delegates[recipient], amount);
return true;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
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) public returns (address){
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "DBL::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "DBL::delegateBySig: invalid nonce");
require(block.timestamp <= expiry, "DBL::delegateBySig: signature expired");
_delegate(signatory, delegatee);
return signatory;
}
/**
* @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) {
uint256 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, uint256 blockNumber) public view returns (uint256) {
require(blockNumber < block.number, "DBL::getPriorVotes: not yet determined");
uint256 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;
}
uint256 lower = 0;
uint256 upper = nCheckpoints - 1;
while (upper > lower) {
uint256 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator);
delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
// function _transferTokens(address src, address dst, uint96 amount) internal {
// require(src != address(0), "DBL::_transferTokens: cannot transfer from the zero address");
// require(dst != address(0), "DBL::_transferTokens: cannot transfer to the zero address");
// balances[src] = sub96(balances[src], amount, "DBL::_transferTokens: transfer amount exceeds balance");
// balances[dst] = add96(balances[dst], amount, "DBL::_transferTokens: transfer amount overflows");
// emit Transfer(src, dst, amount);
// _moveDelegates(delegates[src], delegates[dst], amount);
// }
//转移投票权,减少原代理地址的票数,增加到新代理地址的票数,票数跟balance相关
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
uint256 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld - amount;
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint256 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld + amount;
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "DBL::_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 safe96(uint n, string memory errorMessage) internal pure returns (uint96) {
require(n < 2**96, errorMessage);
return uint96(n);
}
function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
uint96 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) {
require(b <= a, errorMessage);
return a - b;
}
function getChainId() internal view returns (uint256) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity ^0.8.0;
////import './DBLendToken.sol';
////import './DEBIToken.sol';
////import './interfaces/IMinerV1.sol';
// ////import './libraries/Strings.sol';
contract Miner is Ownable{
// using Strings for *;
address public immutable DBL; // DBL地址,部署时传入,不可修改
address public immutable DIBI; // DIBI地址,部署时传入,不可修改
uint256 public constant FIREST_YEAR_DBL = 1050000 * 1e8 * 1e18; // 首年产出DBL,逐年减半(1e18:为了避免分配到每区块时dibi时出现的小数)
uint256 public immutable DEPLOY_BLOCK;// = 10957872;// 合约发布时间
uint public constant blocksPerYear = 2102400;//按照平均15秒/区块,每年区块数
//指定timelock为admin,timelock执行投票通过的业务,修改Miner相关数据
address public admin;
address public pendingAdmin;
//用户质押DIBI每币能够收获的DBL数目perDibiSharedDbl。该数据从0开始,累加所有区块区间的每DIBI能生产的DBL数量
//同一区块,质押数第一次产生变化前,要更新当前每币产出perDibiSharedDbl
//用户收获铸币时,需要提前更新每币产出perDibiSharedDbl,收获完成后,更新用户债务:harvestDebt
//用户收获数目 = block.number- STAKER.lastHarvestBlock
uint256 public perDibiSharedDbl = 0;
uint256 public latestCalTime = 0; //最近一次计算perDibiSharedDbl区块时间,第一次质押时初始化
uint256 public latestBlockNum = 0;
uint256 public totalStaked = 0; // 所有质押的DIBI数量
//The Pause Guardian can pause certain actions as a safety mechanism.
bool public rewardGuardianPaused = false;
bool public stakeGuardianPaused = false;
struct STAKER{
uint256 stakeBalance; // 用户当前质押余额
uint256 lastHarvestBlock; // 最后一次收获时间
uint256 harvestDebt; // 收获时需要扣减的债务
uint256 rewardPending; // 等待收获的数量
}
mapping(address=>STAKER) public stakers; // 所有质押者
event Stake(address indexed staker,uint256 amounts, uint256 earned);
event Harvest(address indexed harver,uint256 earned);
/// @notice Emitted when an action is paused globally
event ActionPaused(string action, bool pauseState);
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
event NewAdmin(address oldAdmin, address newAdmin);
constructor(address _dbl, address _dibi, uint256 _deploy_block){
require(_dbl != address(0) && _dibi != address(0),"INVALID ADDRESS");
DBL = _dbl;
DIBI = _dibi;
DEPLOY_BLOCK = _deploy_block;
admin = msg.sender;
}
///@dev 质押前,计算最新每币产出,并对当前用户进行收获,
function stake(uint256 _amount) external {
// Pausing is a very serious situation - we revert to sound the alarms
require(!rewardGuardianPaused && !stakeGuardianPaused, "STAKE_OR_REWARD IS PAUSED");
require(_amount > 0,"AMOUNT MUST > 0");
require(DEBIToken(DIBI).balanceOf(msg.sender) >= _amount, "INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
//因为质押总数会改变,所以要计算出之前这段时间的每币产出
_calPerDibiSharedDbl();
uint256 earned = 0;
//质押的用户stake需要先收获一次
if(staker.stakeBalance>0){
earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
if(earned>0 && earned!=2**256-1){
staker.rewardPending = staker.rewardPending + earned;
// DBLendToken(DBL).mint(msg.sender,earned);
}
staker.lastHarvestBlock = block.number;
}
// require(1==2,"1222222");
//收获完成后,首先转账dibi,再修改数据状态
DEBIToken(DIBI).transferFrom(msg.sender,address(this),_amount);
if(totalStaked==0) latestBlockNum=block.number;
totalStaked += _amount;
//更新用户质押状态
staker.stakeBalance += _amount;
staker.harvestDebt = perDibiSharedDbl * staker.stakeBalance;
emit Stake(msg.sender, _amount,earned);
}
///@dev 取出DIBI
function withdraw(uint256 _amount) public {
require(stakers[msg.sender].stakeBalance >= _amount,"DBL: INSUFFICIENT DIBI");
STAKER storage staker = stakers[msg.sender];
//如果有区块间隔,先计算收获
if(block.number > staker.lastHarvestBlock){
// harvest();
//更新每质押DIBI产出数
_calPerDibiSharedDbl();
uint256 earned = ( perDibiSharedDbl * (staker.stakeBalance) - staker.harvestDebt ) / 1e18;
if(earned>0 && earned!=2**256-1){
staker.rewardPending = staker.rewardPending + earned;
}
staker.lastHarvestBlock = block.number;
}
//先改变状态,再转账
staker.stakeBalance -= _amount;
staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
totalStaked -= _amount;
DEBIToken(DIBI).transfer(msg.sender, _amount);
}
///@dev 退出质押。先收获,再退出DIBI
function unStake() external {
require(stakers[msg.sender].stakeBalance>0,"DBL: INSUFFICIENT DIBI STAKE");
harvest();
withdraw(stakers[msg.sender].stakeBalance);
}
//主动用户收获,铸币,在stake、unstake、harvest时发生
function harvest() public returns(uint256 earned){
require(stakers[msg.sender].stakeBalance > 0 || stakers[msg.sender].rewardPending > 0, "DBL: INSUFFICIENT STAKE OR REWARD");
require(block.number > stakers[msg.sender].lastHarvestBlock,"DBL: REPEAT HARVEST");
//更新每质押DIBI产出数
_calPerDibiSharedDbl();
STAKER storage staker = stakers[msg.sender];
//收获数量 = 质押代币 * 每币收获 / DIBI精度 - 用户扣减数
earned = ( staker.stakeBalance * perDibiSharedDbl - staker.harvestDebt ) / 1e18;
//铸币
if(staker.rewardPending >0 || earned>0){
//首先更改状态,避免铸币后状态未修改的攻击
staker.lastHarvestBlock = block.number;
staker.harvestDebt = staker.stakeBalance * perDibiSharedDbl;
earned = staker.rewardPending + earned;
staker.rewardPending = 0;
DBLendToken(DBL).mint(msg.sender,earned);
emit Harvest(msg.sender, earned);
}
}
///@dev 计算当前时间段DIBI每币产出,并把当前时间段的每币产出累加。并更新最近计算时间
function _calPerDibiSharedDbl() internal{
uint256 incDblPerDIBI = _calPerDibiIncDbl();
if(incDblPerDIBI > 0){
//如果被禁止产出,则关闭产量增加的逻辑。恢复后,所有产量正常恢复
if(!rewardGuardianPaused){
perDibiSharedDbl += incDblPerDIBI;
latestBlockNum = block.number;
}
}
}
///@dev 时间区段新增的每币产出
function _calPerDibiIncDbl() internal view returns (uint256 incDblPerDIBI){
incDblPerDIBI = 0;
//如果被暂停,则不再增加区块产出
if(rewardGuardianPaused) return incDblPerDIBI;
//只要时间变化了,也就是区块增加了,就不能跳过计算;如果质押变化,但区块没有改变,也不需要计算
//if(block.timestamp > latestCalTime && totalStaked>0){
if(block.number > latestBlockNum && totalStaked>0){
uint256 current = currentYearDibi();//当年产量总和
//新增产量 = 间隔时间段 * (当前年产/365天总秒数)
uint256 increaseDbl = ( block.number - latestBlockNum ) * current / blocksPerYear ;
//每币新增产量 = 新增总量 / 总质押DIBI数
incDblPerDIBI = increaseDbl / totalStaked;
}
return incDblPerDIBI;
}
///@dev 计算当前年度的DIBI产出。第一年=FIREST_YEAR_DBL,以后逐年减半
function currentYearDibi() public view returns (uint256 current){
current = FIREST_YEAR_DBL;
// if(block.timestamp > START_TIME){
if(block.number > DEPLOY_BLOCK){
uint256 severalYears = (block.number - DEPLOY_BLOCK) / blocksPerYear; // 过几年 = 发布时间长/365
if (severalYears > 0) {
current = FIREST_YEAR_DBL / (2 * severalYears); // 当年总产量 = 首年总产量 / (2*几年)
}
}
}
///@dev 查看指定用户可以收获的数量
///@param user 指定用户
function earnedBalance(address user) external view returns(uint256){
//首先计算当前未更新perDibiSharedDbl时间段的产出,但不更新状态,因而无需gas
uint256 _perDibiIncDbl = _calPerDibiIncDbl();
return stakers[user].rewardPending + ( ( perDibiSharedDbl + _perDibiIncDbl ) * stakers[user].stakeBalance - stakers[user].harvestDebt ) / 1e18;
}
///@dev 查看指定用户质押DIBI数量
///@param user 指定用户
function getAmountStakedByAddr(address user) external view returns(uint256){
return stakers[user].stakeBalance;
}
///old methods
function accountStoked(address addr) external view returns (uint256) {
return stakers[addr].stakeBalance;
}
function balanceOf(address _account) external view returns (uint256){
return DBLendToken(DBL).balanceOf(_account);
}
function setRewardPaused(bool state) external onlyOwner returns (bool) {
if(state){
_calPerDibiSharedDbl();
}
rewardGuardianPaused = state;
emit ActionPaused("Reward", state);
return state;
}
function setStakePaused(bool state) external onlyOwner returns (bool) {
stakeGuardianPaused = state;
emit ActionPaused("Stake", state);
return state;
}
function _setPendingAdmin(address _pendingAdming) external {
require(msg.sender == admin && _pendingAdming != address(0),"Miner::Only Admin Allown");
address oldPendingAdmin = pendingAdmin;
pendingAdmin = _pendingAdming;
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
}
function _acceptAdmin() external {
require(msg.sender == pendingAdmin, "Miner::Must PendingAdmin");
address oldAdmin = admin;
admin = pendingAdmin;
pendingAdmin=address(0);
emit NewAdmin(oldAdmin,admin);
}
} | function current() external view returns (uint256);private,don't call | interface IMinerV1{
function accountStoked(address addr) external view returns (uint256);
function totalStoke() external view returns (uint256);
function userTimes(address) external view returns (uint256);
function totalMineds( address ) external view returns (uint256);
function earnedBalance( address ) external view returns (uint256);
pragma solidity ^0.8.0;
}
| 6,545,897 | [
1,
915,
783,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
1152,
16,
19752,
1404,
745,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
5831,
467,
2930,
264,
58,
21,
95,
203,
565,
445,
2236,
510,
14276,
12,
2867,
3091,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
2078,
510,
3056,
1435,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
729,
10694,
12,
2867,
13,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
2078,
49,
1920,
87,
12,
1758,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
565,
445,
425,
1303,
329,
13937,
12,
1758,
262,
3903,
1476,
1135,
261,
11890,
5034,
1769,
203,
377,
203,
377,
203,
683,
9454,
18035,
560,
3602,
20,
18,
28,
18,
20,
31,
203,
97,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-License-Identifier: MIT
// Copyright 2021 Inftspaces & Martin Wawrusch
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
// associated documentation files (the "Software"), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial
// portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
// LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
pragma solidity ^0.8.2;
import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Burnable.sol";
/***
We need to whitelist mintLiveEvent function - topmost priority
We would like to whitelist (seperately from the mintLiveEvent function) the mintInftspaces function, when the saleWhitelistIsActive flag is true.
e.g. those are two different whitelists.
Questions:
* What would be the benefits of using enumerable long term? Should it be removed for minting cost reduction?
* Should we include the opensea proxy code functionality for? If so what would we need to add (looking at https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/ERC721Tradable.sol) with proxy and meta transactions
* Should we implement the new rarible standard for comissions?
* Code Quality? Improvements?
*/
///
/// URL Handling
/// By default we use the base URL for the token combined with the tokenid, but if it has been overriden during minting or set explicitely
/// then we use the one provided there. The idea is to be able to convert all NFTs to IPFS storage when Ethereum switched to Staking and prices are reasonable to update the 8888 tokens.
///
/// Also, to support reveal we make the baseUrl settable, so before the reveal we switch it to the final url.
/// @custom:security-contact [email protected]
contract Inftspaces is ERC721, ERC721Enumerable, ERC721Burnable, ERC721URIStorage, Ownable {
using Counters for Counters.Counter;
using SafeMath for uint256;
using Strings for uint256;
string public PROVENANCE;
mapping(address => bool) public claimedFreeNft;
mapping(address => uint256) public purchasedForAddress;
uint256 public price = 60_000_000_000_000_000; // 0.060 ETH
/// @dev The tokens that are minted for special sales and or participating artists.
uint256 public constant CUSTOM_RESERVE = 100;
/// @dev The maxtokens are the total tokens - the custom reservce.
uint256 public constant MAX_TOKENS = 8788;
uint256 public constant MAX_PURCHASE_PER_MINT = 11;
uint256 public maxPurchasePerAccount = 11;
bool public saleIsActive;
bool public saleWhitelistIsActive = true;
bool public isLiveMintingActive;
uint256 public maxForSale = 2000;
string public baseURI = "https://dujurg1wstjc2.cloudfront.net/metaphysical-rift/";
string private _contractURI;
address public mintLiveEventSigner;
bool public tokenURIsFrozen;
Counters.Counter private _tokenIdCounter;
/// Opensea 'freezing' event.
event PermanentURI(string _value, uint256 indexed _id);
/// Invoked when we live minted an NFT
event LiveMinted(address indexed _to, uint256 indexed _tokenId);
/// Invoked when the live minting activation has been changed.
event SetLiveMintingActive(bool _active);
/// Invoked when the sale price is updated.
//event PriceChanged(uint256 _price);
/// Invoked when the sale activation has been changed.
event SaleIsActive(bool _isActive);
constructor() ERC721("inftspaces - Metaphysical Rift", "INFTMR") {
}
/// @notice Mints between 1 and 10 NFTs.
/// @param numberOfTokens The number of tokens to mint, a valid number of 1 to 10
function mintInftspaces(uint256 numberOfTokens) public payable {
require(saleIsActive, "Sale not active");
require(numberOfTokens > 0, "1 token min");
require(numberOfTokens <= MAX_PURCHASE_PER_MINT, "11 tokens max");
require(_tokenIdCounter.current().add(numberOfTokens) <= maxForSale, "Max supply exceeded");
require(msg.value >= price.mul(numberOfTokens), "Wrong ETH amount");
uint256 mintedSoFar = purchasedForAddress[msg.sender];
require(mintedSoFar + numberOfTokens <= maxPurchasePerAccount, "11 tokens per account");
purchasedForAddress[msg.sender] = mintedSoFar + numberOfTokens;
for(uint256 i = 0; i < numberOfTokens; i++) {
uint256 mintIndex = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(msg.sender, mintIndex);
}
}
/// @notice Mint a token (If you have been whitelisted at an event).
/// @dev Called buy visitors of our live events. They are entitled to 1 mint per whitelisted address.
function mintLiveEvent(uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v,_r,_s) public {
require(isLiveMintingActive, "Live minting inactive");
require(_tokenIdCounter.current().add(1) <= MAX_TOKENS, "Max supply exceeded");
require(!claimedFreeNft[msg.sender], "Already claimed");
uint256 mintIndex = _tokenIdCounter.current();
_tokenIdCounter.increment();
claimedFreeNft[msg.sender] = true;
_safeMint(msg.sender, mintIndex);
emit LiveMinted(msg.sender, mintIndex);
}
/// @notice Live minting support for the smart contract owner
/// @dev Used only in cases where people show up on the live events and don't have money in their ether.
function mintLiveForAddress(address to) public onlyOwner {
require(to != address(0), "No zero address");
require(_tokenIdCounter.current().add(1) <= MAX_TOKENS, "Max supply exceeded");
uint256 mintIndex = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(to, mintIndex);
}
/// @notice Mint custom reserve NFTs for featured artists
/// @dev Used to create custom NFT sets for artists
function mintCustomForAddress(address to, uint256 tokenId) public onlyOwner {
require(to != address(0), "No zero address");
require(tokenId >= MAX_TOKENS, "TokenId >= 8788");
require(tokenId < MAX_TOKENS + CUSTOM_RESERVE, "TokenId <= 8887");
require(!_exists(tokenId), "Token exists");
_safeMint(to, tokenId);
}
/// @notice Fund withdrawal for owner.
function withdraw(uint256 amount) public onlyOwner {
require(address(this).balance >= amount, "Insufficient balance");
payable(msg.sender).transfer(amount);
}
/// @notice sets the price in gwai for a single nft sale.
function setPrice(uint256 newPrice) public onlyOwner {
price = newPrice;
// emit PriceChanged( newPrice);
}
function setMaxPurchasePerAccount(uint256 newMaxPurchasePerAccount) public onlyOwner {
maxPurchasePerAccount = newMaxPurchasePerAccount;
}
function setContractURI(string calldata newContractURI) public onlyOwner {
_contractURI = newContractURI;
}
/// @notice enables/disables the pre sale and sale.
function setMintLiveEventSigner(address adr) public onlyOwner {
mintLiveEventSigner = adr;
}
/// @notice enables/disables the pre sale and sale.
function setSaleIsActive(bool active) public onlyOwner {
saleIsActive = active;
emit SaleIsActive( active);
}
/// @notice enables/disables the pre sale and sale.
function setTokenURIsFrozen() public onlyOwner {
tokenURIsFrozen = true;
}
function setProvenanceHash(string calldata provenanceHash) public onlyOwner {
require(bytes(PROVENANCE).length == 0, "PROVENANCE SET");
PROVENANCE = provenanceHash;
}
/// @notice The live minting action is limited in time. People who do not mint in time will lose their slot.
function setLiveMintingActive(bool active) public onlyOwner {
isLiveMintingActive = active;
emit SetLiveMintingActive(active);
}
/// @notice Sets the maximum number of tokens that can be sold right now (presale)
function setMaxForSale(uint256 newMaxForSale) public onlyOwner {
require(newMaxForSale <= MAX_TOKENS, "Must be 8788 or less");
maxForSale = newMaxForSale;
}
/// @notice The whitelist is by default activated for the sale, but it needs to be deactivated past the presale, otherwise we won't be able to sell without whitelist.
function setSaleWhitelistIsActive(bool active) public onlyOwner {
saleWhitelistIsActive = active;
}
/// @dev This is set to empty to ensure that we can disambiguate between a stored full url and an url that is composed from the actual base url and the tokenid. Never change this.
function _baseURI() internal view virtual override returns (string memory) {
return "";
}
/// @notice Sets the baseURL, which needs to have a trailing /
function setBaseURI(string calldata newBaseURI) public onlyOwner {
baseURI = newBaseURI;
}
function _beforeTokenTransfer(address from, address to, uint256 tokenId)
internal
override(ERC721, ERC721Enumerable)
{
super._beforeTokenTransfer(from, to, tokenId);
}
function supportsInterface(bytes4 interfaceId)
public
view
override(ERC721, ERC721Enumerable)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
// The following functions are overrides required by Solidity.
function _burn(uint256 tokenId) internal override(ERC721, ERC721URIStorage) {
super._burn(tokenId);
}
function tokenURI(uint256 tokenId)
public
view
override(ERC721, ERC721URIStorage)
returns (string memory)
{
require(_exists(tokenId), "Not minted");
string memory uri = super.tokenURI(tokenId);
return bytes(uri).length > 0 ? uri : string(abi.encodePacked(baseURI, tokenId.toString(), ".json"));
}
// /// @notice Will be used by the owner to permanently freeze the metadata on ipfs once Ethereum moves to PoS
// /// This can be set as long as tokenURIs are not frozen or it has not been set to a dedicated value.
// function freezeMetadata(uint256 tokenId, string calldata uri) public onlyOwner{
// require(_exists(tokenId), "Not minted");
// require(!tokenURIsFrozen || bytes(super.tokenURI(tokenId)).length == 0, "Token URIs frozen");
// _setTokenURI(tokenId, uri);
// emit PermanentURI(uri, tokenId);
// }
/// @notice Will be used by the owner to permanently freeze the metadata on ipfs once Ethereum moves to PoS
/// This can be set as long as tokenURIs are not frozen or it has not been set to a dedicated value.
function freezeMetadatas(uint256 tokenId, string[] calldata uris) public onlyOwner{
for(uint256 i = 0; i < uris.length; i++) {
uint256 mintIndex = tokenId + i;
require(_exists(mintIndex), "Not minted");
require(!tokenURIsFrozen || bytes(super.tokenURI(mintIndex)).length == 0, "Token URIs frozen");
_setTokenURI(mintIndex, uris[i]);
emit PermanentURI(uris[i], mintIndex);
}
}
/*
* @dev Requires msg.sender to have valid access message.
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
*/
modifier onlyValidAccess(uint8 _v, bytes32 _r, bytes32 _s)
{
require( isValidAccessMessage(msg.sender,_v,_r,_s), "Invalid signer" );
_;
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(
address _add,
uint8 _v,
bytes32 _r,
bytes32 _s)
public view returns (bool)
{
bytes32 hash = keccak256(abi.encodePacked(this, _add));
return /* owner() */ mintLiveEventSigner == ecrecover(
keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)),
_v,
_r,
_s
);
}
function contractURI() public view returns (string memory) {
return _contractURI;
}
}
// 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 "../ERC721.sol";
/**
* @dev ERC721 token with storage based token URI management.
*/
abstract contract ERC721URIStorage is ERC721 {
using Strings for uint256;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = _baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
return super.tokenURI(tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
}
}
// 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;
/**
* @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;
// 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;
}
}
}
// 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 "../ERC721.sol";
import "../../../utils/Context.sol";
/**
* @title ERC721 Burnable Token
* @dev ERC721 Token that can be irreversibly burned (destroyed).
*/
abstract contract ERC721Burnable is Context, ERC721 {
/**
* @dev Burns `tokenId`. See {ERC721-_burn}.
*
* Requirements:
*
* - The caller must own `tokenId` or be an approved operator.
*/
function burn(uint256 tokenId) public virtual {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721Burnable: caller is not owner nor approved");
_burn(tokenId);
}
}
// 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;
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);
}
// 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);
} | @notice Mint a token (If you have been whitelisted at an event). @dev Called buy visitors of our live events. They are entitled to 1 mint per whitelisted address. | function mintLiveEvent(uint8 _v, bytes32 _r, bytes32 _s) onlyValidAccess(_v,_r,_s) public {
require(isLiveMintingActive, "Live minting inactive");
require(_tokenIdCounter.current().add(1) <= MAX_TOKENS, "Max supply exceeded");
require(!claimedFreeNft[msg.sender], "Already claimed");
uint256 mintIndex = _tokenIdCounter.current();
_tokenIdCounter.increment();
claimedFreeNft[msg.sender] = true;
_safeMint(msg.sender, mintIndex);
emit LiveMinted(msg.sender, mintIndex);
}
| 298,451 | [
1,
49,
474,
279,
1147,
261,
2047,
1846,
1240,
2118,
26944,
622,
392,
871,
2934,
225,
11782,
30143,
22763,
434,
3134,
8429,
2641,
18,
16448,
854,
3281,
305,
1259,
358,
404,
312,
474,
1534,
26944,
1758,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
312,
474,
12328,
1133,
12,
11890,
28,
389,
90,
16,
1731,
1578,
389,
86,
16,
1731,
1578,
389,
87,
13,
1338,
1556,
1862,
24899,
90,
16,
67,
86,
16,
67,
87,
13,
1071,
288,
203,
3639,
2583,
12,
291,
12328,
49,
474,
310,
3896,
16,
315,
12328,
312,
474,
310,
16838,
8863,
203,
3639,
2583,
24899,
2316,
548,
4789,
18,
2972,
7675,
1289,
12,
21,
13,
1648,
4552,
67,
8412,
55,
16,
315,
2747,
14467,
12428,
8863,
203,
3639,
2583,
12,
5,
14784,
329,
9194,
50,
1222,
63,
3576,
18,
15330,
6487,
315,
9430,
7516,
329,
8863,
203,
203,
3639,
2254,
5034,
312,
474,
1016,
273,
389,
2316,
548,
4789,
18,
2972,
5621,
203,
3639,
389,
2316,
548,
4789,
18,
15016,
5621,
203,
3639,
7516,
329,
9194,
50,
1222,
63,
3576,
18,
15330,
65,
273,
638,
31,
203,
3639,
389,
4626,
49,
474,
12,
3576,
18,
15330,
16,
312,
474,
1016,
1769,
203,
203,
3639,
3626,
21559,
49,
474,
329,
12,
3576,
18,
15330,
16,
312,
474,
1016,
1769,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.25;
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() {
if (msg.sender != owner) {
revert();
}
_;
}
/**
* @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;
}
}
}
contract ERC20Interface {
uint8 public decimals;
string public symbol;
string public name;
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);
}
contract _0xChange is Ownable {
//allows to close the exchange
bool is_exchange_open;
//last price paid on the exchange
mapping(address => uint[]) public last_price;
mapping(address => uint[]) public volume;
//First order of the queue for each token
mapping(address => bytes32) public first_buy_order_id;
mapping(address => bytes32) public first_sell_order_id;
//mapping of executed orders by trx id
mapping(address => mapping(bytes32 => order)) public buy_orders;
mapping(address => mapping(bytes32 => order)) public sell_orders;
//mapping of all orders in uint format, can be converted
//back toHex to access other data from the order book
mapping(address => mapping(address => uint[])) public my_buy_orders;
mapping(address => mapping(address => uint[])) public my_sell_orders;
//Executions records
//(i) mapping token => order_id => (uint) execution_id
//(ii) mapping token => execution_id => execution
//(iii) mapping token => (uint) execution_id
mapping(address => mapping(bytes32 => uint[])) public my_executions;
mapping(address => mapping(bytes32 => execution)) public executions;
mapping(address => uint[]) public execution_list;
//mapping of address with current balance with the exchange
mapping(address => uint) public eth_balance;
mapping(address => mapping(address => uint)) public token_balance;
//mapping of listed tokens
mapping(address => string) public listed_tokens;
mapping(address => bool) public is_token_listed;
address[] public token_list_array;
//contrat fee rate, i.e 0.25%
uint public fees = 25 ;
uint private fees_pool;
event Executed(address token, bytes32 execution_id);
//Default Constructor
constructor() public payable {
is_exchange_open = true;
}
//Order struct
struct order{
bytes32 id;
address token_address;
uint block_nr;
address from;
uint eth_sent;
uint eth_left;
uint token_amount;
uint token_left;
uint limit;
bool executed;
bool cancelled;
bytes32 previous_order;
bytes32 next_order;
}
//Order struct
struct execution{
bytes32 id;
address token_address;
uint block_nr;
uint timestamp;
bool order_type;
bytes32 buy_order_id;
bytes32 sell_order_id;
uint exec_amount;
uint price;
}
// ------------------------------------------------------------------------
// Place an order in the buy_orders mapping
// The queue is organized with market order first and then
// Limit order sorted from highest to lowest bid
// ------------------------------------------------------------------------
function place_buy_order(address _token, uint _amount, uint _limit) public payable returns (bytes32 order_nr) {
require(_amount * _limit / (10**uint(ERC20Interface(_token).decimals())) <= msg.value);
require(msg.value > 0);
require(is_exchange_open);
bytes32 order_id = keccak256(
abi.encodePacked(
block.number,
_token,
msg.sender,
_amount,
_limit));
buy_orders[_token][order_id].id = order_id;
buy_orders[_token][order_id].token_address = _token;
buy_orders[_token][order_id].block_nr = block.number;
buy_orders[_token][order_id].from = msg.sender;
buy_orders[_token][order_id].eth_sent = msg.value;
buy_orders[_token][order_id].eth_left = msg.value;
buy_orders[_token][order_id].token_amount = _amount;
buy_orders[_token][order_id].token_left = _amount;
buy_orders[_token][order_id].limit = _limit;
buy_orders[_token][order_id].executed = false;
buy_orders[_token][order_id].cancelled = false;
buy_orders[_token][order_id].previous_order = bytes32(0);
buy_orders[_token][order_id].next_order = bytes32(0);
my_buy_orders[_token][msg.sender].push(uint(order_id));
insertBuyOrder(_token, order_id);
matching(_token, true);
return order_id;
}
// ------------------------------------------------------------------------
// Place an order in the sell_orders mapping
// Called internally from ReceiveApproval
// The queue is organized with market order first and then
// Limit order sorted from high lowest to highes ask
// ------------------------------------------------------------------------
function place_sell_order(address _seller, address _token, uint _amount, uint _limit) internal returns (bytes32 order_nr) {
require(is_exchange_open);
bytes32 order_id = keccak256(
abi.encodePacked(
block.number,
_token,
msg.sender,
_amount,
_limit));
sell_orders[_token][order_id].id = order_id;
sell_orders[_token][order_id].token_address = _token;
sell_orders[_token][order_id]. block_nr = block.number;
sell_orders[_token][order_id].from = _seller;
sell_orders[_token][order_id].eth_sent = msg.value;
sell_orders[_token][order_id].eth_left = msg.value;
sell_orders[_token][order_id].token_amount = _amount;
sell_orders[_token][order_id].token_left = _amount;
sell_orders[_token][order_id].limit = _limit;
sell_orders[_token][order_id].executed = false;
sell_orders[_token][order_id].cancelled = false;
sell_orders[_token][order_id].previous_order = bytes32(0);
sell_orders[_token][order_id].next_order = bytes32(0);
my_sell_orders[_token][_seller].push(uint(order_id));
insertSellOrder(_token, order_id);
matching(_token, false);
return order_id;
}
// ------------------------------------------------------------------------
// Match orders in the book
// 1) Market orders are matched together using the lower of
// the last paid price on the exchange and the lowest ask
// 2) Limit orders are matched together until bid < ask
// ------------------------------------------------------------------------
function matching(address _token, bool _type) public {
bytes32 exec_id;
uint price;
uint amount;
while (matchingPossible(_token))
{
//set execution price for market vs market,
//market vs limit order, limit vs market
//and limit vs. limit type of order
price = transactionPrice(_token);
amount = transactionAmount(_token, price);
exec_id = keccak256(
abi.encodePacked(
_token,
block.number,
_token,
first_buy_order_id[_token],
first_sell_order_id[_token],
price,
amount));
executions[_token][exec_id].id = exec_id;
executions[_token][exec_id].token_address = _token;
executions[_token][exec_id].block_nr = block.number;
executions[_token][exec_id].timestamp = block.timestamp;
executions[_token][exec_id].order_type = _type;
executions[_token][exec_id].buy_order_id = first_buy_order_id[_token];
executions[_token][exec_id].sell_order_id = first_sell_order_id[_token];
executions[_token][exec_id].exec_amount = amount;
executions[_token][exec_id].price = price;
last_price[_token].push(price);
my_executions[_token][first_buy_order_id[_token]].push(uint(exec_id));
my_executions[_token][first_sell_order_id[_token]].push(uint(exec_id));
execution_list[_token].push(uint(exec_id));
settlement(_token, exec_id);
}
}
// ------------------------------------------------------------------------
// Compare the first orders of the bid and ask and define if
// a matching is possible
// ------------------------------------------------------------------------
function matchingPossible(address _token) internal view returns (bool) {
return (buy_orders[_token][first_buy_order_id[_token]].limit >= sell_orders[_token][first_sell_order_id[_token]].limit ||
(buy_orders[_token][first_buy_order_id[_token]].limit == 0 || sell_orders[_token][first_sell_order_id[_token]].limit == 0)) &&
(first_buy_order_id[_token] != 0 && first_sell_order_id[_token] != 0);
}
// ------------------------------------------------------------------------
// Return the transaction price:
// 1) Market order vs Market order: lower of last price or best offer
// 2) Market order vs Limit Order: limit order
// ------------------------------------------------------------------------
function transactionPrice(address _token) internal view returns (uint) {
if(buy_orders[_token][first_buy_order_id[_token]].limit == 0
&& sell_orders[_token][first_sell_order_id[_token]].limit == 0) {
return getBestPrice(_token);
} else if(buy_orders[_token][first_buy_order_id[_token]].limit == 0
&& sell_orders[_token][first_sell_order_id[_token]].limit != 0) {
return sell_orders[_token][first_sell_order_id[_token]].limit;
} else if(buy_orders[_token][first_buy_order_id[_token]].limit != 0
&& sell_orders[_token][first_sell_order_id[_token]].limit == 0) {
return buy_orders[_token][first_buy_order_id[_token]].limit;
} else if (buy_orders[_token][first_buy_order_id[_token]].limit != 0
&& sell_orders[_token][first_sell_order_id[_token]].limit != 0) {
//Update needed
return sell_orders[_token][first_sell_order_id[_token]].limit;
}
}
// ------------------------------------------------------------------------
// Return transaction amount as the lowest of the bid amount,
// the offer amount and the maximal amount that the buyers can aquire as
// the ether left on the order divided by the transaction price
// ------------------------------------------------------------------------
function transactionAmount(address _token, uint price) internal view returns(uint) {
return min(buy_orders[_token][first_buy_order_id[_token]].token_left, min(
buy_orders[_token][first_buy_order_id[_token]].eth_left *
(10**uint(ERC20Interface(_token).decimals())) / price,
sell_orders[_token][first_sell_order_id[_token]].token_left));
}
// ------------------------------------------------------------------------
// Arrange the settlement by:
// 1) reducing the buy and sell order amounts by the transaction amount
// 2) push the execution ID in the execution array of the orders
// 3) increase the token balance of the buyer and the eth balance of
// the seller, book the fees and emit the Execution event
// 4) close orders that have been executed, buy amount considered executed
// once remaining ETH is smaller than 10000000000 gwei.
// ------------------------------------------------------------------------
function settlement(address _token, bytes32 _exec_id) internal {
uint trx_volume = executions[_token][_exec_id].exec_amount *
executions[_token][_exec_id].price /
(10**uint(ERC20Interface(_token).decimals()));
volume[_token].push(trx_volume);
uint fee_payment;
uint payment;
//update orders
buy_orders[_token][first_buy_order_id[_token]].token_left -= executions[_token][_exec_id].exec_amount;
sell_orders[_token][first_sell_order_id[_token]].token_left -= executions[_token][_exec_id].exec_amount;
buy_orders[_token][first_buy_order_id[_token]].eth_left -= trx_volume;
//update execution
my_executions[_token][first_buy_order_id[_token]].push(uint(_exec_id));
my_executions[_token][first_sell_order_id[_token]].push(uint(_exec_id));
//Fee processing
fee_payment = trx_volume * fees / 10000;
payment = trx_volume - fee_payment;
token_balance[_token][getBuyOrderFrom(_token, executions[_token][_exec_id].buy_order_id)] += executions[_token][_exec_id].exec_amount;
eth_balance[getSellOrderFrom(_token, executions[_token][_exec_id].sell_order_id)] += payment;
fees_pool += fee_payment;
emit Executed(_token, _exec_id);
//Consider an order as executed if the token amount left is zero
//or if the eth amount left is smaller than 10000000000 wei (0.00000001 ETH)
if(buy_orders[_token][first_buy_order_id[_token]].token_left == 0 ||
buy_orders[_token][first_buy_order_id[_token]].eth_left < 10000000000) {
buy_orders[_token][first_buy_order_id[_token]].executed = true;
eth_balance[getBuyOrderFrom(_token, executions[_token][_exec_id].buy_order_id)] += buy_orders[_token][first_buy_order_id[_token]].eth_left;
buy_orders[_token][first_buy_order_id[_token]].eth_left = 0;
first_buy_order_id[_token] = buy_orders[_token][first_buy_order_id[_token]].next_order;
buy_orders[_token][first_buy_order_id[_token]].previous_order = bytes32(0);
buy_orders[_token][executions[_token][_exec_id].buy_order_id].next_order = bytes32(0);
}
if(sell_orders[_token][first_sell_order_id[_token]].token_left == 0) {
sell_orders[_token][first_sell_order_id[_token]].executed = true;
first_sell_order_id[_token] = sell_orders[_token][first_sell_order_id[_token]].next_order;
sell_orders[_token][first_sell_order_id[_token]].previous_order = bytes32(0);
sell_orders[_token][executions[_token][_exec_id].sell_order_id].next_order = bytes32(0);
}
}
// ------------------------------------------------------------------------
// Calculate best price for market orders by returning
// the lower of the the last price paid or the lowest ask
// ------------------------------------------------------------------------
function getBestPrice(address _token) public view returns (uint price) {
//lowest of last paid price or lowest limit sell order
//used to execute market orders
bytes32 position = first_sell_order_id[_token];
uint best_price = last_price[_token][last_price[_token].length-1];
while(sell_orders[_token][position].id != 0)
{
if(sell_orders[_token][position].limit != 0 &&
sell_orders[_token][position].limit < best_price) {
best_price = sell_orders[_token][position].limit;
}
position = sell_orders[_token][getNextSellOrder(_token, position)].id;
}
return best_price;
}
// ------------------------------------------------------------------------
// Cancel an order, remove it from the chain of orders and
// increase eth balance of the trader by the eth left
// ------------------------------------------------------------------------
function cancelBuyOrder(address _token, bytes32 orderId) public {
require(msg.sender == buy_orders[_token][orderId].from);
require(buy_orders[_token][orderId].cancelled == false);
require(buy_orders[_token][orderId].executed == false);
order memory _order = buy_orders[_token][orderId];
if(first_buy_order_id[_token] == orderId)
first_buy_order_id[_token] = _order.next_order;
buy_orders[_token][_order.previous_order].next_order = _order.next_order;
buy_orders[_token][_order.next_order].previous_order = _order.previous_order;
_order.next_order = bytes32(0);
_order.previous_order = bytes32(0);
_order.cancelled = true;
eth_balance[_order.from] += _order.eth_left;
_order.eth_left = 0;
buy_orders[_token][orderId] = _order;
}
// ------------------------------------------------------------------------
// Cancel an order, remove it from the chain of orders and
// increase token balance of the trader by the token left
// ------------------------------------------------------------------------
function cancelSellOrder(address _token, bytes32 orderId) public {
require(msg.sender == sell_orders[_token][orderId].from);
require(sell_orders[_token][orderId].cancelled == false);
require(sell_orders[_token][orderId].executed == false);
order memory _order = sell_orders[_token][orderId];
if(first_sell_order_id[_token] == orderId)
first_sell_order_id[_token] = _order.next_order;
sell_orders[_token][_order.previous_order].next_order = _order.next_order;
sell_orders[_token][_order.next_order].previous_order = _order.previous_order;
_order.next_order = bytes32(0);
_order.previous_order = bytes32(0);
_order.cancelled = true;
token_balance[_token][_order.from] += _order.token_amount;
_order.token_amount = 0;
sell_orders[_token][orderId] = _order;
}
function flush(address tokenAddress) private onlyOwner {
bytes32 temp;
bytes32 next;
temp = buy_orders[tokenAddress][first_buy_order_id[tokenAddress]].id;
while(temp != 0)
{
next = getNextBuyOrder(tokenAddress, temp);
cancelBuyOrder(tokenAddress, temp);
temp = next;
}
}
function flushAndClose(address tokenAddress) private onlyOwner {
flush(tokenAddress);
setIsExchangeOpen(false);
}
// ------------------------------------------------------------------------
// Insert a buy order in the order queue
// Market orders are placed first sorted by seniority
// Limit orders are placed with highest bid first and then sorted
// by seniority
// ------------------------------------------------------------------------
function insertBuyOrder(address _token, bytes32 _order_id) internal {
bytes32 position;
//In case no other buy order exists
if(first_buy_order_id[_token] == 0) {
first_buy_order_id[_token] = _order_id;
return;
}
//loop through the buy order book and insert new buy orders
position = first_buy_order_id[_token];
do
{
//insert market orders before limit order (first market order)
if(buy_orders[_token][_order_id].limit == 0 &&
buy_orders[_token][position].limit != 0 &&
(buy_orders[_token][getPreviousBuyOrder(_token, position)].id == 0 ||
buy_orders[_token][getPreviousBuyOrder(_token, position)].limit == 0)) {
if(buy_orders[_token][getPreviousBuyOrder(_token, position)].id == 0)
first_buy_order_id[_token] = _order_id;
buy_orders[_token][_order_id].previous_order = getPreviousBuyOrder(_token, position);
buy_orders[_token][_order_id].next_order = position;
buy_orders[_token][getPreviousBuyOrder(_token, position)].next_order = _order_id;
buy_orders[_token][position].previous_order = _order_id;
return;
}
//insert market order after the last market order
if(buy_orders[_token][_order_id].limit == 0 &&
buy_orders[_token][position].limit == 0 &&
(buy_orders[_token][getNextBuyOrder(_token, position)].id == 0 ||
buy_orders[_token][getNextBuyOrder(_token, position)].limit != 0)) {
buy_orders[_token][_order_id].previous_order = position;
buy_orders[_token][_order_id].next_order = buy_orders[_token][position].next_order;
buy_orders[_token][getNextBuyOrder(_token, position)].previous_order = _order_id;
buy_orders[_token][position].next_order = _order_id;
return;
}
//insert limit order for new highest bid
if(buy_orders[_token][_order_id].limit != 0 &&
buy_orders[_token][position].limit != 0 &&
buy_orders[_token][_order_id].limit > buy_orders[_token][position].limit &&
(buy_orders[_token][getPreviousBuyOrder(_token, position)].id == 0 ||
buy_orders[_token][getPreviousBuyOrder(_token, position)].limit == 0)) {
if(buy_orders[_token][getPreviousBuyOrder(_token, position)].id == 0)
first_buy_order_id[_token] = _order_id;
buy_orders[_token][_order_id].previous_order = buy_orders[_token][getPreviousBuyOrder(_token, position)].id;
buy_orders[_token][_order_id].next_order = position;
buy_orders[_token][getPreviousBuyOrder(_token, position)].next_order = _order_id;
buy_orders[_token][position].previous_order = _order_id;
return;
}
//insert limit order, case where the order is among existing limit buy orders
//or first limit order after market order(s)
if((buy_orders[_token][_order_id].limit != 0 &&
buy_orders[_token][position].limit != 0 &&
buy_orders[_token][_order_id].limit <= buy_orders[_token][position].limit &&
buy_orders[_token][_order_id].block_nr > buy_orders[_token][position].block_nr &&
(buy_orders[_token][getNextBuyOrder(_token, position)].id == 0 ||
buy_orders[_token][_order_id].limit > buy_orders[_token][getNextBuyOrder(_token, position)].limit)) ||
buy_orders[_token][_order_id].limit != 0 &&
buy_orders[_token][position].limit == 0 &&
buy_orders[_token][getNextBuyOrder(_token, position)].id == 0) {
buy_orders[_token][_order_id].previous_order = position;
buy_orders[_token][_order_id].next_order = getNextBuyOrder(_token, position);
buy_orders[_token][getNextBuyOrder(_token, position)].previous_order = _order_id;
buy_orders[_token][position].next_order = _order_id;
return;
}
position = getNextBuyOrder(_token, position);
} while(position != 0);
}
// ------------------------------------------------------------------------
// Insert a sell order in the order queue
// Market orders are placed first sorted by seniority
// Limit orders are placed with lowest ask first and then sorted
// by seniority
// ------------------------------------------------------------------------
function insertSellOrder(address _token, bytes32 _order_id) internal {
bytes32 position;
if(first_sell_order_id[_token] == 0) {
first_sell_order_id[_token] = _order_id;
return;
}
position = first_sell_order_id[_token];
do
{
//insert orders, market orders with limit 0 first_sell_order_id
//then limit order by ascending order. Orders of equal limit
//sorted ascending by block nr
if(sell_orders[_token][_order_id].limit < sell_orders[_token][position].limit) {
if(sell_orders[_token][position].previous_order == 0) {
first_sell_order_id[_token] = _order_id;
}
sell_orders[_token][_order_id].previous_order = getPreviousSellOrder(_token, position);
sell_orders[_token][_order_id].next_order = position;
sell_orders[_token][getPreviousSellOrder(_token, position)].next_order = _order_id;
sell_orders[_token][position].previous_order = _order_id;
return;
}
//insert limit order, case where the order is among existing limit buy orders
if(sell_orders[_token][_order_id].limit >= sell_orders[_token][position].limit &&
(sell_orders[_token][_order_id].limit < sell_orders[_token][getNextSellOrder(_token, position)].limit ||
sell_orders[_token][getNextSellOrder(_token, position)].id == 0) &&
sell_orders[_token][_order_id].block_nr > sell_orders[_token][position].block_nr) {
sell_orders[_token][_order_id].previous_order = position;
sell_orders[_token][_order_id].next_order = getNextSellOrder(_token, position);
sell_orders[_token][getNextSellOrder(_token, position)].previous_order = _order_id;
sell_orders[_token][position].next_order = _order_id;
return;
}
position = getNextSellOrder(_token, position);
} while(position != 0);
}
// ------------------------------------------------------------------------
// Withdraw Eth from the traders balance
// ------------------------------------------------------------------------
function withdrawEth(address _sender) public {
require(msg.sender == _sender);
uint balance = eth_balance[msg.sender];
eth_balance[msg.sender] = 0;
msg.sender.transfer(balance);
}
// ------------------------------------------------------------------------
// Withdraw Tokens from the traders balance
// ------------------------------------------------------------------------
function withdrawToken(address _token, address _sender) public {
require(msg.sender == _sender);
uint balance = token_balance[_token][msg.sender];
token_balance[_token][_sender] = 0;
ERC20Interface(_token).transfer(_sender, balance);
}
// ------------------------------------------------------------------------
// Allows the owner to withdraw Eth from the fees pool
// ------------------------------------------------------------------------
function withdrawFees() public onlyOwner {
uint fee_amount = fees_pool;
fees_pool = 0;
owner.transfer(fee_amount);
}
// ------------------------------------------------------------------------
// Open or close the exchange
// ------------------------------------------------------------------------
function setIsExchangeOpen(bool status) public onlyOwner {
is_exchange_open = status;
}
// ------------------------------------------------------------------------
// Called to place sell orders, so that the tokens
// can be transferred to the exchange
// ------------------------------------------------------------------------
function receiveApproval(address _from, uint _token, address _tokenContract, bytes _data) public {
if(!ERC20Interface(_tokenContract).transferFrom(_from, this, _token)) {
revert();
}
place_sell_order(_from, _tokenContract, _token, bytesToUint(_data));
}
// ------------------------------------------------------------------------
// Closes the exchange for good,
// to call flush and close in final version and repay everyone
// ------------------------------------------------------------------------
function close() public onlyOwner {
selfdestruct(owner);
}
// ------------------------------------------------------------------------
// Used to convert the data receives as argument in receiveApproval.
// Used to pass the limit in the sell order, e.g. 0x10 = limit of 1 wei
// ------------------------------------------------------------------------
function bytesToUint(bytes b) public pure returns (uint){
uint number;
for(uint i=0;i<b.length;i++){
number = number + uint(b[b.length-1-i])*(10**i);
}
return number;
}
// ------------------------------------------------------------------------
// Only during test phase or to be updated for not allowing transferToken
// of client's token
// ------------------------------------------------------------------------
function transferToken(address _tokenAddress, address _to, uint _token) private onlyOwner {
ERC20Interface(_tokenAddress).transferFrom(this, _to, _token);
}
// ------------------------------------------------------------------------
// Management of the tokens listed on the exchange
// ------------------------------------------------------------------------
function addToken(address tokenAddress) public onlyOwner {
if(is_token_listed[tokenAddress] == false) {
token_list_array.push(tokenAddress);
listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol();
is_token_listed[tokenAddress] = true;
} else {
listed_tokens[tokenAddress] = ERC20Interface(tokenAddress).symbol();
}
}
// ------------------------------------------------------------------------
// Getters and setters for web3 interface
// ------------------------------------------------------------------------
// Tokens
function getTokenListLength() constant public returns(uint) {
return token_list_array.length;
}
function getTokenAddress(uint pos) constant public returns(address) {
return token_list_array[pos];
}
function getTokenSymbol(address tokenAddress) constant public returns(string) {
return listed_tokens[tokenAddress];
}
//Info
function getPriceLength(address tokenAddress) constant public returns(uint) {
return last_price[tokenAddress].length;
}
function getLastPrice(address tokenAddress) constant public returns(uint) {
return last_price[tokenAddress][last_price[tokenAddress].length-1];
}
function getPrice(address tokenAddress, uint pos) constant public returns(uint) {
return last_price[tokenAddress][pos];
}
function getVolumeLength(address tokenAddress) constant public returns(uint) {
return volume[tokenAddress].length;
}
function getLastVolume(address tokenAddress) constant public returns(uint) {
return volume[tokenAddress][volume[tokenAddress].length-1];
}
function getVolume(address tokenAddress, uint pos) constant public returns(uint) {
return volume[tokenAddress][pos];
}
// Executions
function getOrderExecutionLength(address _token, bytes32 _orderId) constant public returns(uint) {
return my_executions[_token][_orderId].length;
}
function getExecutionsLength(address _token) constant public returns(uint) {
return execution_list[_token].length;
}
function getExecutionId(address _token, uint _pos) constant public returns(uint) {
return execution_list[_token][_pos];
}
function getOrderExecutionId(address _token, bytes32 _orderId, uint _pos) constant public returns(uint) {
return my_executions[_token][_orderId][_pos];
}
function getExecutionBlockNr(address _token, bytes32 _execId) constant public returns(uint) {
return executions[_token][_execId].block_nr;
}
function getExecutionType(address _token, bytes32 _execId) constant public returns(bool) {
return executions[_token][_execId].order_type;
}
function getExecutionBuyOrderId(address _token, bytes32 _execId) constant public returns(bytes32) {
return executions[_token][_execId].buy_order_id;
}
function getExecutionSellOrderId(address _token, bytes32 _execId) constant public returns(bytes32) {
return executions[_token][_execId].sell_order_id;
}
function getExecutionTokenAmount(address _token, bytes32 _execId) constant public returns(uint) {
return executions[_token][_execId].exec_amount;
}
function getExecutionPrice(address _token, bytes32 _execId) constant public returns(uint) {
return executions[_token][_execId].price;
}
function getExecutionTimestamp(address _token, bytes32 _execId) constant public returns(uint) {
return executions[_token][_execId].timestamp;
}
// Orders
function getBuyOrderBlockNr(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].block_nr;
}
function getSellOrderBlockNr(address _token, bytes32 _orderId) constant public returns (uint) {
return sell_orders[_token][_orderId].block_nr;
}
function getBuyOrderFrom(address _token, bytes32 _orderId) constant public returns (address) {
return buy_orders[_token][_orderId].from;
}
function getSellOrderFrom(address _token, bytes32 _orderId) constant public returns (address) {
return sell_orders[_token][_orderId].from;
}
function getBuyOrderEthSent(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].eth_left;
}
function getBuyOrderEthLeft(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].eth_left;
}
function getBuyOrderTokenAmount(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].token_amount;
}
function getBuyOrderTokenLeft(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].token_left;
}
function getSellOrderTokenAmount(address _token, bytes32 _orderId) constant public returns (uint) {
return sell_orders[_token][_orderId].token_amount;
}
function getSellOrderTokenLeft(address _token, bytes32 _orderId) constant public returns (uint) {
return sell_orders[_token][_orderId].token_left;
}
function getBuyOrderEthPriceLimit(address _token, bytes32 _orderId) constant public returns (uint) {
return buy_orders[_token][_orderId].limit;
}
function getSellOrderEthPriceLimit(address _token, bytes32 _orderId) constant public returns (uint) {
return sell_orders[_token][_orderId].limit;
}
function getPreviousBuyOrder(address _token, bytes32 _orderId) constant public returns (bytes32) {
return buy_orders[_token][_orderId].previous_order;
}
function getPreviousSellOrder(address _token, bytes32 _orderId) constant public returns (bytes32) {
return sell_orders[_token][_orderId].previous_order;
}
function getNextBuyOrder(address _token, bytes32 _orderId) constant public returns (bytes32) {
return buy_orders[_token][_orderId].next_order;
}
function getNextSellOrder(address _token, bytes32 _orderId) constant public returns (bytes32) {
return sell_orders[_token][_orderId].next_order;
}
function isBuyOrderCancelled(address _token, bytes32 _orderId) constant public returns (bool) {
return buy_orders[_token][_orderId].cancelled;
}
function isSellOrderCancelled(address _token, bytes32 _orderId) constant public returns (bool) {
return sell_orders[_token][_orderId].cancelled;
}
function isBuyOrderExecuted(address _token, bytes32 _orderId) constant public returns (bool) {
return buy_orders[_token][_orderId].executed;
}
function isSellOrderExecuted(address _token, bytes32 _orderId) constant public returns (bool) {
return sell_orders[_token][_orderId].executed;
}
function getMyBuyOrdersLength(address _token, address from) constant public returns (uint) {
return my_buy_orders[_token][from].length;
}
function getMyBuyOrders(address _token, address from, uint position) constant public returns(uint) {
return my_buy_orders[_token][from][position];
}
function getMySellOrdersLength(address _token, address from) constant public returns (uint) {
return my_sell_orders[_token][from].length;
}
function getMySellOrders(address _token, address from, uint position) constant public returns(uint) {
return my_sell_orders[_token][from][position];
}
// Various utils
function max(uint a, uint b) internal pure returns (uint) {
if(a >= b)
return a;
else
return b;
}
function min(uint a, uint b) internal pure returns (uint) {
if(a <= b)
return a;
else
return b;
}
}
| update ordersupdate executionFee processingConsider an order as executed if the token amount left is zeroor if the eth amount left is smaller than 10000000000 wei (0.00000001 ETH) | function settlement(address _token, bytes32 _exec_id) internal {
uint trx_volume = executions[_token][_exec_id].exec_amount *
executions[_token][_exec_id].price /
(10**uint(ERC20Interface(_token).decimals()));
volume[_token].push(trx_volume);
uint fee_payment;
uint payment;
buy_orders[_token][first_buy_order_id[_token]].token_left -= executions[_token][_exec_id].exec_amount;
sell_orders[_token][first_sell_order_id[_token]].token_left -= executions[_token][_exec_id].exec_amount;
buy_orders[_token][first_buy_order_id[_token]].eth_left -= trx_volume;
my_executions[_token][first_buy_order_id[_token]].push(uint(_exec_id));
my_executions[_token][first_sell_order_id[_token]].push(uint(_exec_id));
fee_payment = trx_volume * fees / 10000;
payment = trx_volume - fee_payment;
token_balance[_token][getBuyOrderFrom(_token, executions[_token][_exec_id].buy_order_id)] += executions[_token][_exec_id].exec_amount;
eth_balance[getSellOrderFrom(_token, executions[_token][_exec_id].sell_order_id)] += payment;
fees_pool += fee_payment;
emit Executed(_token, _exec_id);
if(buy_orders[_token][first_buy_order_id[_token]].token_left == 0 ||
buy_orders[_token][first_buy_order_id[_token]].eth_left < 10000000000) {
buy_orders[_token][first_buy_order_id[_token]].executed = true;
eth_balance[getBuyOrderFrom(_token, executions[_token][_exec_id].buy_order_id)] += buy_orders[_token][first_buy_order_id[_token]].eth_left;
buy_orders[_token][first_buy_order_id[_token]].eth_left = 0;
first_buy_order_id[_token] = buy_orders[_token][first_buy_order_id[_token]].next_order;
buy_orders[_token][first_buy_order_id[_token]].previous_order = bytes32(0);
buy_orders[_token][executions[_token][_exec_id].buy_order_id].next_order = bytes32(0);
}
if(sell_orders[_token][first_sell_order_id[_token]].token_left == 0) {
sell_orders[_token][first_sell_order_id[_token]].executed = true;
first_sell_order_id[_token] = sell_orders[_token][first_sell_order_id[_token]].next_order;
sell_orders[_token][first_sell_order_id[_token]].previous_order = bytes32(0);
sell_orders[_token][executions[_token][_exec_id].sell_order_id].next_order = bytes32(0);
}
}
| 12,920,432 | [
1,
2725,
11077,
2725,
4588,
14667,
4929,
9054,
3585,
392,
1353,
487,
7120,
309,
326,
1147,
3844,
2002,
353,
3634,
280,
309,
326,
13750,
3844,
2002,
353,
10648,
2353,
2130,
12648,
732,
77,
261,
20,
18,
9449,
1611,
512,
2455,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
26319,
806,
12,
2867,
389,
2316,
16,
1731,
1578,
389,
4177,
67,
350,
13,
2713,
288,
203,
203,
3639,
2254,
433,
92,
67,
9491,
273,
26845,
63,
67,
2316,
6362,
67,
4177,
67,
350,
8009,
4177,
67,
8949,
380,
203,
5411,
26845,
63,
67,
2316,
6362,
67,
4177,
67,
350,
8009,
8694,
342,
7010,
5411,
261,
2163,
636,
11890,
12,
654,
39,
3462,
1358,
24899,
2316,
2934,
31734,
1435,
10019,
203,
3639,
3940,
63,
67,
2316,
8009,
6206,
12,
313,
92,
67,
9491,
1769,
203,
3639,
2254,
14036,
67,
9261,
31,
203,
3639,
2254,
5184,
31,
203,
203,
3639,
30143,
67,
9972,
63,
67,
2316,
6362,
3645,
67,
70,
9835,
67,
1019,
67,
350,
63,
67,
2316,
65,
8009,
2316,
67,
4482,
3947,
26845,
63,
67,
2316,
6362,
67,
4177,
67,
350,
8009,
4177,
67,
8949,
31,
203,
3639,
357,
80,
67,
9972,
63,
67,
2316,
6362,
3645,
67,
87,
1165,
67,
1019,
67,
350,
63,
67,
2316,
65,
8009,
2316,
67,
4482,
3947,
26845,
63,
67,
2316,
6362,
67,
4177,
67,
350,
8009,
4177,
67,
8949,
31,
203,
3639,
30143,
67,
9972,
63,
67,
2316,
6362,
3645,
67,
70,
9835,
67,
1019,
67,
350,
63,
67,
2316,
65,
8009,
546,
67,
4482,
3947,
433,
92,
67,
9491,
31,
203,
203,
3639,
3399,
67,
4177,
6170,
63,
67,
2316,
6362,
3645,
67,
70,
9835,
67,
1019,
67,
350,
63,
67,
2316,
65,
8009,
6206,
12,
11890,
24899,
4177,
67,
350,
10019,
203,
3639,
3399,
67,
4177,
6170,
63,
67,
2316,
6362,
3645,
2
] |
pragma solidity 0.5.12;
import "./Handler.sol";
import "./interface/IUSR.sol";
import "./library/ReentrancyGuard.sol";
contract USRHandler is Handler, ReentrancyGuard {
address public USR;
struct InterestDetails {
uint256 totalUnderlyingBalance; // Total underlying balance including interest
uint256 interest; // Total interest
}
// Based on underlying token, get current interest details
mapping(address => InterestDetails) public interestDetails;
constructor(address _dTokenController, address _USR) public {
initialize(_dTokenController, _USR);
}
// --- Init ---
// This function is used with contract proxy, do not modify this function.
function initialize(address _dTokenController, address _USR) public {
super.initialize(_dTokenController);
initReentrancyStatus();
USR = _USR;
}
function setUSR(address _USR) external auth {
USR = _USR;
}
/**
* @dev Authorized function to approves market and dToken to transfer handler's underlying token.
* @param _underlyingToken Token address to approve.
*/
function approve(address _underlyingToken, uint256 amount) public auth {
require(
IUSR(USR).underlyingToken() == _underlyingToken,
"approve: Do not support token!"
);
require(
doApprove(_underlyingToken, USR, amount),
"approve: Approve USR failed!"
);
super.approve(_underlyingToken, amount);
}
/**
* @dev Deposit token to market, only called by dToken contract.
* @param _underlyingToken Token to deposit.
* @return The actual deposited token amount.
*/
function deposit(address _underlyingToken, uint256 _amount)
external
whenNotPaused
auth
nonReentrant
returns (uint256)
{
require(
_amount > 0,
"deposit: Deposit amount should be greater than 0!"
);
address _USR = USR;
require(
IUSR(_USR).underlyingToken() == _underlyingToken,
"deposit: Do not support token!"
);
uint256 _MarketBalanceBefore = getRealBalance(_underlyingToken);
InterestDetails storage _details = interestDetails[_underlyingToken];
// Update the stored interest with the market balance after the mint
uint256 _interest = _MarketBalanceBefore.sub(
_details.totalUnderlyingBalance
);
_details.interest = _details.interest.add(_interest);
// Mint all the token balance of the handler,
// which should be the exact deposit amount normally,
// but there could be some unexpected transfers before.
uint256 _handlerBalance = IERC20(_underlyingToken).balanceOf(
address(this)
);
IUSR(_USR).mint(address(this), _handlerBalance);
// including unexpected transfers.
uint256 _MarketBalanceAfter = getRealBalance(_underlyingToken);
// Store the latest real balance.
_details.totalUnderlyingBalance = _MarketBalanceAfter;
uint256 _changedAmount = _MarketBalanceAfter.sub(_MarketBalanceBefore);
// return a smaller value as unexpected transfers were also included.
return _changedAmount > _amount ? _amount : _changedAmount;
}
/**
* @dev Withdraw token from market, but only for dToken contract.
* @param _underlyingToken Token to withdraw.
* @param _amount Token amount to withdraw.
* @return The actual withdrown token amount.
*/
function withdraw(address _underlyingToken, uint256 _amount)
external
whenNotPaused
auth
nonReentrant
returns (uint256)
{
require(
_amount > 0,
"withdraw: Withdraw amount should be greater than 0!"
);
address _USR = USR;
require(
IUSR(_USR).underlyingToken() == _underlyingToken,
"withdraw: Do not support token!"
);
uint256 _handlerBalanceBefore = IERC20(_underlyingToken).balanceOf(
address(this)
);
uint256 _MarketBalanceBefore = getRealBalance(_underlyingToken);
InterestDetails storage _details = interestDetails[_underlyingToken];
// Update the stored interest with the market balance after the redeem
uint256 _interest = _MarketBalanceBefore.sub(
_details.totalUnderlyingBalance
);
_details.interest = _details.interest.add(_interest);
// Redeem all or just the amount of underlying token
if (_amount == uint256(-1)) {
IUSR(_USR).redeem(
address(this),
IERC20(_USR).balanceOf(address(this))
);
} else {
IUSR(_USR).redeemUnderlying(address(this), _amount);
}
uint256 _handlerBalanceAfter = IERC20(_underlyingToken).balanceOf(
address(this)
);
uint256 _changedAmount = _handlerBalanceAfter.sub(
_handlerBalanceBefore
);
// including unexpected transfers.
uint256 _MarketBalanceAfter = getRealBalance(_underlyingToken);
// Store the latest real balance.
_details.totalUnderlyingBalance = _MarketBalanceAfter;
// return a smaller value.
return _changedAmount > _amount ? _amount : _changedAmount;
}
/**
* @dev Total balance with any accumulated interest for _underlyingToken belonging to handler
* @param _underlyingToken Token to get balance.
*/
function getRealBalance(address _underlyingToken) public returns (uint256) {
_underlyingToken;
return IUSR(USR).balanceOfUnderlying(address(this));
}
/**
* @dev The maximum withdrawable _underlyingToken in the market.
* @param _underlyingToken Token to get liquidity.
*/
function getRealLiquidity(address _underlyingToken)
public
returns (uint256)
{
return getRealBalance(_underlyingToken);
}
/***************************************************/
/*** View Interfaces For Backwards compatibility ***/
/***************************************************/
/**
* @dev Total balance with any accumulated interest for `_underlyingToken` belonging to `handler`.
* @param _underlyingToken Token to get balance.
*/
function getBalance(address _underlyingToken) external returns (uint256) {
return getRealBalance(_underlyingToken);
}
/**
* @dev The maximum withdrawable amount of token `_underlyingToken` in the market.
* @param _underlyingToken Token to get liquidity.
*/
function getLiquidity(address _underlyingToken) external returns (uint256) {
return getRealLiquidity(_underlyingToken);
}
}
| --- Init --- This function is used with contract proxy, do not modify this function. | function initialize(address _dTokenController, address _USR) public {
super.initialize(_dTokenController);
initReentrancyStatus();
USR = _USR;
}
| 12,699,012 | [
1,
6062,
4378,
9948,
1220,
445,
353,
1399,
598,
6835,
2889,
16,
741,
486,
5612,
333,
445,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4046,
12,
2867,
389,
72,
1345,
2933,
16,
1758,
389,
27984,
13,
1071,
288,
203,
3639,
2240,
18,
11160,
24899,
72,
1345,
2933,
1769,
203,
3639,
1208,
426,
8230,
12514,
1482,
5621,
203,
3639,
587,
10090,
273,
389,
27984,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// /$$$$$$ /$$$$$$$ /$$
// /$$$_ $$ | $$__ $$ |__/
// | $$$$\ $$ /$$ /$$| $$ \ $$ /$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$ /$$$$$$ /$$ /$$$$$$$
// | $$ $$ $$| $$ /$$/| $$ | $$ /$$__ $$ /$$__ $$ /$$__ $$ /$$_____/ /$$__ $$| $$| $$__ $$
// | $$\ $$$$ \ $$$$/ | $$ | $$| $$ \ $$| $$ \ $$| $$$$$$$$| $$ | $$ \ $$| $$| $$ \ $$
// | $$ \ $$$ >$$ $$ | $$ | $$| $$ | $$| $$ | $$| $$_____/| $$ | $$ | $$| $$| $$ | $$
// | $$$$$$/ /$$/\ $$| $$$$$$$/| $$$$$$/| $$$$$$$| $$$$$$$| $$$$$$$| $$$$$$/| $$| $$ | $$
// \______/ |__/ \__/|_______/ \______/ \____ $$ \_______/ \_______/ \______/ |__/|__/ |__/
// /$$ \ $$
// | $$$$$$/
// \______/
//
// Official OxDogecoin website: http://0xdogecoin.com
// '0xDogecoin' contract
// Mineable ERC20 Token using Proof Of Work
//
// Symbol : 0xDoge
// Name : 0xDogecoin
// Total supply: 1 000 000 000 (1 Billion)
// Decimals : 8
//
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// 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;
}
}
library ExtendedMath {
//return the smaller of the two inputs (a or b)
function limitLessThan(uint a, uint b) internal pure returns (uint c) {
if(a > b) return b;
return a;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
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);
}
// ----------------------------------------------------------------------------
// 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;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
interface EIP918Interface {
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success);
function getChallengeNumber() public constant returns (bytes32);
function getMiningDifficulty() public constant returns (uint);
function getMiningTarget() public constant returns (uint);
function getMiningReward() public constant returns (uint);
event Mint(address indexed from, uint reward_amount, uint epochCount, bytes32 newChallengeNumber);
}
// ----------------------------------------------------------------------------
// Mineable ERC918 / ERC20 Token
// ----------------------------------------------------------------------------
contract _0xDogecoin is ERC20Interface, Owned, EIP918Interface {
using SafeMath for uint;
using ExtendedMath for uint;
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public latestDifficultyPeriodStarted;
uint public epochCount; //number of 'blocks' mined
uint public _BLOCKS_PER_READJUSTMENT = 512;
//a little number and a big number
uint public _MINIMUM_TARGET = 2**16;
uint public _MAXIMUM_TARGET = 2**234;
uint public miningTarget;
bytes32 public challengeNumber; //generate a new one when a new reward is minted
uint public rewardEra;
uint public maxSupplyForEra;
address public lastRewardTo;
uint public lastRewardAmount;
uint public lastRewardEthBlockNumber;
bool locked = false;
mapping(bytes32 => bytes32) solutionForChallenge;
uint public tokensMinted;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function _0xDogecoin() public onlyOwner{
symbol = "0xDoge";
name = "0xDogecoin";
decimals = 8;
_totalSupply = 1000000000 * 10**uint(decimals);
if(locked) revert();
locked = true;
tokensMinted = 0;
rewardEra = 0;
maxSupplyForEra = _totalSupply.div(2);
miningTarget = _MAXIMUM_TARGET;
latestDifficultyPeriodStarted = block.number;
_startNewMiningEpoch();
}
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) {
//the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks
bytes32 digest = keccak256(challengeNumber, msg.sender, nonce );
//the challenge digest must match the expected
if (digest != challenge_digest) revert();
//the digest must be smaller than the target
if(uint256(digest) > miningTarget) revert();
//only allow one reward for each challenge
bytes32 solution = solutionForChallenge[challengeNumber];
solutionForChallenge[challengeNumber] = digest;
if(solution != 0x0) revert(); //prevent the same answer from awarding twice
uint reward_amount = getMiningReward();
balances[msg.sender] = balances[msg.sender].add(reward_amount);
tokensMinted = tokensMinted.add(reward_amount);
//Cannot mint more tokens than there are
assert(tokensMinted <= maxSupplyForEra);
//set readonly diagnostics data
lastRewardTo = msg.sender;
lastRewardAmount = reward_amount;
lastRewardEthBlockNumber = block.number;
_startNewMiningEpoch();
Mint(msg.sender, reward_amount, epochCount, challengeNumber );
return true;
}
//a new 'block' to be mined
function _startNewMiningEpoch() internal {
//if max supply for the era will be exceeded next reward round then enter the new era before that happens
//40 is the final reward era, almost all tokens minted
//once the final era is reached, more tokens will not be given out because the assert function
if( tokensMinted.add(getMiningReward()) > maxSupplyForEra && rewardEra < 39)
{
rewardEra = rewardEra + 1;
}
//set the next minted supply at which the era will change
// total supply is 100000000000000000 because of 8 decimal places
maxSupplyForEra = _totalSupply - _totalSupply.div( 2**(rewardEra + 1));
epochCount = epochCount.add(1);
//every so often, readjust difficulty. Dont readjust when deploying
if(epochCount % _BLOCKS_PER_READJUSTMENT == 0)
{
_reAdjustDifficulty();
}
//make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks
//do this last since this is a protection mechanism in the mint() function
challengeNumber = block.blockhash(block.number - 1);
}
//readjust the target by 5 percent
function _reAdjustDifficulty() internal {
uint ethBlocksSinceLastDifficultyPeriod = block.number - latestDifficultyPeriodStarted;
//assume 360 ethereum blocks per hour
//we want miners to spend 2 minutes to mine each 'block', about 12 ethereum blocks = one 0xDoge epoch
uint epochsMined = _BLOCKS_PER_READJUSTMENT;
uint targetEthBlocksPerDiffPeriod = epochsMined * 12; //should be 12 times slower than ethereum
//if there were less eth blocks passed in time than expected
if( ethBlocksSinceLastDifficultyPeriod < targetEthBlocksPerDiffPeriod )
{
uint excess_block_pct = (targetEthBlocksPerDiffPeriod.mul(100)).div( ethBlocksSinceLastDifficultyPeriod );
uint excess_block_pct_extra = excess_block_pct.sub(100).limitLessThan(1000);
// If there were 5% more blocks mined than expected then this is 5. If there were 100% more blocks mined than expected then this is 100.
//make it harder
miningTarget = miningTarget.sub(miningTarget.div(2000).mul(excess_block_pct_extra)); //by up to 50 %
}else{
uint shortage_block_pct = (ethBlocksSinceLastDifficultyPeriod.mul(100)).div( targetEthBlocksPerDiffPeriod );
uint shortage_block_pct_extra = shortage_block_pct.sub(100).limitLessThan(1000); //always between 0 and 1000
//make it easier
miningTarget = miningTarget.add(miningTarget.div(2000).mul(shortage_block_pct_extra)); //by up to 50 %
}
latestDifficultyPeriodStarted = block.number;
if(miningTarget < _MINIMUM_TARGET) //very difficult
{
miningTarget = _MINIMUM_TARGET;
}
if(miningTarget > _MAXIMUM_TARGET) //very easy
{
miningTarget = _MAXIMUM_TARGET;
}
}
//this is a recent ethereum block hash, used to prevent pre-mining future blocks
function getChallengeNumber() public constant returns (bytes32) {
return challengeNumber;
}
//the number of zeroes the digest of the PoW solution requires. Auto adjusts
function getMiningDifficulty() public constant returns (uint) {
return _MAXIMUM_TARGET.div(miningTarget);
}
function getMiningTarget() public constant returns (uint) {
return miningTarget;
}
//reward is cut in half every reward era (as tokens are mined)
function getMiningReward() public constant returns (uint) {
//every reward era, the reward amount halves.
return (5000 * 10**uint(decimals) ).div( 2**rewardEra ) ;
}
//help debug mining software
function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
return digest;
}
//help debug mining software
function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// 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 returns (bool success) {
balances[msg.sender] = balances[msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(msg.sender, to, tokens);
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 returns (bool success) {
balances[from] = balances[from].sub(tokens);
allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens);
balances[to] = balances[to].add(tokens);
Transfer(from, to, tokens);
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 {
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);
}
} | help debug mining software | function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) {
bytes32 digest = keccak256(challenge_number,msg.sender,nonce);
if(uint256(digest) > testTarget) revert();
return (digest == challenge_digest);
}
| 14,012,414 | [
1,
5201,
1198,
1131,
310,
17888,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1377,
445,
866,
49,
474,
16135,
12,
11890,
5034,
7448,
16,
1731,
1578,
12948,
67,
10171,
16,
1731,
1578,
12948,
67,
2696,
16,
2254,
1842,
2326,
13,
1071,
1476,
1135,
261,
6430,
2216,
13,
288,
203,
1850,
1731,
1578,
5403,
273,
417,
24410,
581,
5034,
12,
25092,
67,
2696,
16,
3576,
18,
15330,
16,
12824,
1769,
203,
1850,
309,
12,
11890,
5034,
12,
10171,
13,
405,
1842,
2326,
13,
15226,
5621,
203,
1850,
327,
261,
10171,
422,
12948,
67,
10171,
1769,
203,
3639,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.22 <0.7.0;
/**
* @title Designing a voting contract
* @dev Implements voting process for voting by students to decide Scholarship Winner(s)
*/
contract Scholarship {
struct Student {
uint vote_possession; // Number of vote tickets possessed by each student. Vote is either assigned by Professor or is accumulated by receiving tickets from other students
bool voteAssigned; // State of whether student being assigned vote ticket by professor, to determine whether the address belongs to a valid student
uint voteCasted_count; // Number of times of voting, with maximum of 3
uint timeOfFirstVoteCast; // Time between first vote casted by each student and Deadline, to help decide the earliest voter. The first voter will have the largest value.
}
address payable public professor; // The address of the Professor
uint public scholarship; // Scholarship money to be allocated after voting
uint public deadline; // Deadline of scholarship voting
bool public isDeadlineSet; // To check whether Deadline set before voting starts
mapping(address => Student) public students; // Each student's address is mapped to the student structured data with student's voting details
address payable [] public voteAssignedList; // List (array) of students assigned 1 vote ticket by Professor
address payable [] public winningStudent; // List (array) of scholarship winning student(s) BY VOTE COUNT
uint public numberOfStudentsVoted = 0; // Number of students voted, initialized to 0
address payable public earliestVoteCastedStudent; // The First student who voted
uint public timeOfEarliestVoteCasted = 0; // Time between the First vote casted by the Earliest voter and the Deadline, initialized to 0
uint public mostVotedStudentVote_Count = 1; // The vote count of the student(s) who got the greatest number of vote tickets. Initialing this variable
// to 1 is to prevent the case where students having 0 vote ticket to become stored in the winningStudent array.
// This is just for a clean and general way of obtaining the true winningStudent array.
// Initiating the contract
constructor() public payable{
professor = msg.sender; // Professor is the owner of the contract
scholarship = msg.value; // The scholarship money from Professor
}
modifier mustBeProfessor{
require(msg.sender == professor, "only Professor can do this");
_;
}
// (Requirement 2) - At the beginning, Professor will assign 1 vote ticket to each student and therefore setting the student list
// (in case this contract may be deployed in an external environment)
function AssignVotes(address payable _student) public mustBeProfessor{
require(_student != professor, "Professor cannot assign vote ticket to Professor"); // Only students can be assigned vote ticket
require(students[_student].voteAssigned==false, "student already assigned 1 vote ticket" ); // To avoid duplication of assignment of vote ticket to a student
students[_student].vote_possession=1; // Only 1 vote ticket to be assigned by Professor to each student
voteAssignedList.push(_student); // The array maintains a list of students assigned 1 vote ticket by the Professor
// and this list is therefore a list of VALID students defined by the Professor
students[_student].voteAssigned=true; // Setting the student as vote assigned
}
// (Requirement 1) - The function below is for Professor to initiatialise voting process by setting the Deadline for students to select and vote the winner(s).
// The function gives the choice for the Professor to input the time to deadline, say 10 minutes, in seconds
function DeadlineToInitialise(uint timeToDeadline) public mustBeProfessor{
require(!isDeadlineSet, "Deadline already set, cannot be resetted again"); // Preventing double setting the deadline by Professor
require(timeToDeadline > 0, "Has not inputted deadline yet"); // Reminding the Professor to input before pressing button
deadline = now + timeToDeadline ; // Setting deadline variable to be the current time + the time to deadline
isDeadlineSet = true ; // Setting flag as true after Deadline has been set
}
// Making sure the time is within the voting period between the setting of Deadline and Deadline itself
modifier withinDeadlinePeriod{
require(isDeadlineSet, "Professor has not initialise voting by setting deadline");
require(deadline > now, "Deadline passed, cannot vote anymore");
_;
}
// Restricting voting to only valid candidates ie students in class assigned a vote ticket by the Professor
// (in case this contract may be deployed in an external environment, this is to prevent scholarship to be given to outsiders)
modifier mustBeValidStudent(address payable toBeIdentified){
require(students[toBeIdentified].voteAssigned==true, "Cannot vote for an addressee not assigned vote ticket by the Professor, ie this person is not a valid student in class" );
_;
}
// (Requirement 3) - The function below allows students to vote for other students with maximum voting chance of 3 times only during the period before Deadline.
// At each voting chance, the voting student can decide to give >= 1 vote tickets to the candidate student as long as he or she has sufficient tickets in possession.
function vote(address payable candidate, uint tickets) public withinDeadlinePeriod mustBeValidStudent(candidate){
require(tickets > 0, "Has not inputted number of tickets"); // Remind students to input number of vote tickets
require(students[msg.sender].vote_possession >= tickets, "Has not enough or no tickets to vote"); // Only students with sufficient tickets can vote. This also prevents Professor or other outsiders to vote.
require(candidate != msg.sender, "Students cannot vote for themselves"); // Requirement 4 does not allow students to vote for themselves.
require(students[msg.sender].voteCasted_count < 3, "Students cannot vote more than 3 times"); // Requirement 3 condition
students[msg.sender].vote_possession -= tickets; // Reducing the voter's tickets by the number of tickets used for this vote chance
// Registering the time of the voter's first voting action
if (students[msg.sender].voteCasted_count == 0){
students[msg.sender].timeOfFirstVoteCast = deadline - now ;
}
students[msg.sender].voteCasted_count += 1; // Recording how many vote chance has been used by the voter
students[candidate].vote_possession += tickets; // Increasing the tickets of the candidate by the number of tickets received from voter
}
// Making sure that vote counting, deciding the winner and transferring scholarship can only be done after deadline passed
modifier mustPassedDeadline{
require(deadline < now, "deadline has not passed yet, voting is still in progress");
_;
}
// (Requirement 4, 5 and 6) - The MAIN function below is to allow the Professor to operate and start vote count, to calculate sufficient voting occurrence or not,
// to determine the first voter, to decide whether there is a winner and to give out scholarship, after Deadline. This main function calls other functions.
function winningScholar() public mustBeProfessor mustPassedDeadline{
// The 'for loop' will go through the array of students that have been assigned a vote ticket by Professor, namely all the valid students
for (uint p = 0; p < voteAssignedList.length; p++){
calcNumberOfStudentsVoted(voteAssignedList[p]); // Call the function to count the number of students voted and get the total number of students voted
// by the end of this 'for loop'
calcListOfWinningStudents(voteAssignedList[p]); // Call the function to check the number of vote tickets possessed by each student and find out the winning student(s)
// with the greatest number of vote tickets by the end of this 'for loop'
calcEarliestVoteCastedStudent(voteAssignedList[p]); // Call the function to check the time of the first vote by each student and find out the student
// who voted first by the end of this 'for loop'
}
giveScholarship(); // Call the function to decide the winner(s) and transfer scholarship(s) accordingly
}
// (Requirement 5) - The function below allows the counting of how many students have voted. This helps to decide on condition
// whether more than half of students have not voted.
function calcNumberOfStudentsVoted(address payable _student) private{
if (students[_student].voteCasted_count > 0) {
numberOfStudentsVoted += 1;
}
}
// (Vote Count and Requirement 4) - The function below finds out the student(s) with the greatest number of vote tickets and also
// allowing for Requirement 4 (see below 'else case'). The function records the winning student(s) in the winningStudent array.
function calcListOfWinningStudents(address payable _student) private{
// The 'if case' here is where the student has voted before, therefore all his or her vote tickets will be counted, including the initial assigned ticket.
if (students[_student].voteCasted_count > 0){
// To compare the vote tickets possessed by each student with the number of tickets possessed by the currently winning student
// and to update the maximum number of tickets recorded and revise the winning student record for student with more tickets
if (students[_student].vote_possession > mostVotedStudentVote_Count) {
mostVotedStudentVote_Count = students[_student].vote_possession;
delete winningStudent; // Reseting the winningStudent array
winningStudent.push(_student);
}else{
// This case is for recording students with the same highest number of vote tickets
if (students[_student].vote_possession == mostVotedStudentVote_Count) {
winningStudent.push(_student); // No need to reset array this time since there are more than 1 winner in this case
}
}
}else{
// The 'else case' here is where the parameter voteCasted_out of a student equals 0, which means that the student did not vote for anyone.
// Requirement 4 disallows a student to vote himself or herself.
// If he/she has not voted for anyone, his/her initial assigned ticket will be invalid after the deadline.
// Therefore the vote_possession is reduced by 1 to remove the initial ticket in the count, before performing the comparison and any record update.
if ((students[_student].vote_possession - 1) > mostVotedStudentVote_Count) {
mostVotedStudentVote_Count = students[_student].vote_possession - 1;
delete winningStudent;
winningStudent.push(_student);
}else{
if ((students[_student].vote_possession - 1) == mostVotedStudentVote_Count) {
winningStudent.push(_student);
}
}
}
}
// (Requirement 5) - The function below identifies and keeps record of the first student who voted i.e. the student who voted at a time furthest from Deadline
function calcEarliestVoteCastedStudent(address payable _student) private{
if (students[_student].timeOfFirstVoteCast > timeOfEarliestVoteCasted) { // Compare the first vote of each student with the prevailing earliest vote recorded
timeOfEarliestVoteCasted = students[_student].timeOfFirstVoteCast; // Time of the earliest vote recorded in the timeOfEarliestVoteCasted variable
earliestVoteCastedStudent = _student; // Student of the earliest vote cast recorded in the earliestVoteCastedStudent variable
}
}
// (Requirement 5 and 6) - The function below decides the winner(s) of the scholarship(s) and making transfer accordingly. I have added a condition that
// if there is NO voting by any students, no scholarship will be given out.
function giveScholarship() private{
require (0 < numberOfStudentsVoted, "There was NO voting by any student. No scholarship would be given out");
// Requirment 5 conditions the case where more than half of the students have NOT voted, ie less than half of students have voted,
// the scholarship will go to the student who voted first. I made use of BASIS POINTS in the comparison of the 'if clause'.
// The total student population is the set of valid students assigned a single vote ticket by the Professor.
if ( numberOfStudentsVoted * 10000 / voteAssignedList.length < 5000 ){
giveToFirstVote();
}else{
// Otherwise, scholarship will go to the Vote Winner(s)
giveToVoteWinners();
}
}
// (Requirement 5) Case of Invalid Voting - transferring scholarship to the student who first voted
function giveToFirstVote() private{
delete winningStudent; // In this case, no winning student by voting
earliestVoteCastedStudent.transfer(scholarship); // Student of the earliest vote cast recorded gets the scholarship
}
// (Requirement 6) Case of Valid Voting - transferring scholarship(s) to the student(s) with the highest number of vote tickets
function giveToVoteWinners() private{
if (winningStudent.length<2){
// Case of a single student winning the most vote tickets
winningStudent[0].transfer(scholarship);
}else{
// Case of multiple students with the same number of winning vote tickets, the scholarship will be divided
// in equal shares for these winning students
for (uint i=0; i<winningStudent.length; i++){
winningStudent[i].transfer(scholarship/winningStudent.length);
}
}
}
}
| Scholarship money to be allocated after voting
| uint public scholarship; | 998,968 | [
1,
55,
343,
355,
976,
625,
15601,
358,
506,
11977,
1839,
331,
17128,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2254,
1071,
18551,
355,
976,
625,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
// SPDX-Licence-Identifier: GPL-3.0
pragma solidity >=0.7.0 < 0.9.0;
contract structs {
struct listaEstudiantes{
string aula;
uint cantidad;
}
//muetras los datos enviados
listaEstudiantes public escuelaa = listaEstudiantes("A", 30);
mapping (uint => uint) public PromedioAlumno; //(ID alumno => promedioGeneral)
function nuevoAula(string memory _aula, uint _cantidad) public view returns (listaEstudiantes memory){
return listaEstudiantes(_aula, _cantidad);
}
function modificar(uint _cantidad) public returns(listaEstudiantes memory){
escuelaa.cantidad = _cantidad;
return escuelaa;
}
function setMapping(uint _id, uint _promedio) public{
PromedioAlumno[_id] = _promedio;
}
} | (ID alumno => promedioGeneral)
| mapping (uint => uint) public PromedioAlumno; | 1,836,577 | [
1,
12,
734,
524,
755,
83,
516,
450,
2937,
1594,
12580,
13,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
2874,
261,
11890,
516,
2254,
13,
1071,
17552,
329,
1594,
1067,
755,
83,
31,
225,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/1/0xBcc031eD992666Bc04931dE28d7744DE5C199Ea9/sources/BAGIE.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Black Wagie","BAGIE") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(
0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D
);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
excludeFromMaxTransaction(address(uniswapV2Pair), true);
_setAutomatedMarketMakerPair(address(uniswapV2Pair), true);
uint256 _buyMarketingFee = 3;
uint256 _buyLiquidityFee = 0;
uint256 _buyDevFee = 3;
uint256 _sellMarketingFee = 3;
uint256 _sellLiquidityFee = 0;
uint256 _sellDevFee = 3;
uint256 totalSupply = 1_000_000_000 * 1e18;
buyMarketingFee = _buyMarketingFee;
buyLiquidityFee = _buyLiquidityFee;
buyDevFee = _buyDevFee;
buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee;
sellMarketingFee = _sellMarketingFee;
sellLiquidityFee = _sellLiquidityFee;
sellDevFee = _sellDevFee;
sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee;
excludeFromFees(owner(), true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(address(this), true);
excludeFromMaxTransaction(address(0xdead), true);
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
_mint(msg.sender, totalSupply);
| 9,180,659 | [
1,
10157,
628,
8843,
310,
1656,
281,
578,
7999,
943,
2492,
3844,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
3885,
1435,
4232,
39,
3462,
2932,
13155,
678,
346,
1385,
15937,
38,
1781,
8732,
7923,
288,
203,
3639,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
389,
318,
291,
91,
438,
58,
22,
8259,
273,
467,
984,
291,
91,
438,
58,
22,
8259,
3103,
12,
203,
5411,
374,
92,
27,
69,
26520,
72,
4313,
5082,
38,
24,
71,
42,
25,
5520,
27,
5520,
72,
42,
22,
39,
25,
72,
37,
7358,
24,
71,
26,
6162,
42,
3247,
5482,
40,
203,
3639,
11272,
203,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
24899,
318,
291,
91,
438,
58,
22,
8259,
3631,
638,
1769,
203,
3639,
640,
291,
91,
438,
58,
22,
8259,
273,
389,
318,
291,
91,
438,
58,
22,
8259,
31,
203,
203,
3639,
640,
291,
91,
438,
58,
22,
4154,
273,
467,
984,
291,
91,
438,
58,
22,
1733,
24899,
318,
291,
91,
438,
58,
22,
8259,
18,
6848,
10756,
203,
5411,
263,
2640,
4154,
12,
2867,
12,
2211,
3631,
389,
318,
291,
91,
438,
58,
22,
8259,
18,
59,
1584,
44,
10663,
203,
3639,
4433,
1265,
2747,
3342,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
3639,
389,
542,
22932,
690,
3882,
278,
12373,
4154,
12,
2867,
12,
318,
291,
91,
438,
58,
22,
4154,
3631,
638,
1769,
203,
203,
3639,
2254,
5034,
389,
70,
9835,
3882,
21747,
14667,
273,
890,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
48,
18988,
24237,
14667,
273,
374,
31,
203,
3639,
2254,
5034,
389,
70,
9835,
8870,
2
] |
./partial_match/3/0xf51456e564bb2c16dcA44E83504bD216C0D19D79/sources/ManagerFactory.sol | solhint-disable-next-line avoid-low-level-calls pass along failure message from delegatecall and revert. solhint-disable-next-line no-inline-assembly return eip-1167 code to write it to spawned contract runtime. solhint-disable-next-line no-inline-assembly | {
(bool success, ) = template.delegatecall(initializationCalldata);
if (!success) {
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
abi.encodePacked(
bytes10(0x363d3d373d3d3d363d73),
template,
bytes15(0x5af43d82803e903d91602b57fd5bf3)
);
assembly {
}
}
| 5,082,707 | [
1,
18281,
11317,
17,
8394,
17,
4285,
17,
1369,
4543,
17,
821,
17,
2815,
17,
12550,
1342,
7563,
5166,
883,
628,
7152,
1991,
471,
15226,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
327,
425,
625,
17,
20562,
27,
981,
358,
1045,
518,
358,
12560,
329,
6835,
3099,
18,
3704,
11317,
17,
8394,
17,
4285,
17,
1369,
1158,
17,
10047,
17,
28050,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
288,
203,
3639,
261,
6430,
2216,
16,
262,
273,
1542,
18,
22216,
1991,
12,
6769,
1588,
1477,
892,
1769,
203,
3639,
309,
16051,
4768,
13,
288,
203,
5411,
19931,
288,
203,
7734,
327,
892,
3530,
12,
20,
16,
374,
16,
327,
13178,
554,
10756,
203,
7734,
15226,
12,
20,
16,
327,
13178,
554,
10756,
203,
5411,
289,
203,
3639,
289,
203,
203,
5411,
24126,
18,
3015,
4420,
329,
12,
203,
7734,
1731,
2163,
12,
20,
92,
23,
4449,
72,
23,
72,
6418,
23,
72,
23,
72,
23,
72,
23,
4449,
72,
9036,
3631,
203,
7734,
1542,
16,
203,
7734,
1731,
3600,
12,
20,
92,
25,
1727,
8942,
72,
11149,
3672,
23,
73,
29,
4630,
72,
29,
2313,
3103,
70,
10321,
8313,
25,
17156,
23,
13,
203,
5411,
11272,
203,
203,
3639,
19931,
288,
203,
3639,
289,
203,
565,
289,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableMapUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "contracts/interfaces/apwine/tokens/IFutureYieldToken.sol";
import "contracts/interfaces/apwine/IFuture.sol";
import "contracts/interfaces/apwine/IRegistry.sol";
import "contracts/interfaces/apwine/utils/IAPWineNaming.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
/**
* @title Controller contract
* @notice The controller dictates the future mechanisms and serves as an interface for main user interaction with futures
*/
contract Controller is Initializable, AccessControlUpgradeable {
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using SafeMathUpgradeable for uint256;
/* ACR Roles*/
bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE");
/* Attributes */
IRegistry public registry;
mapping(uint256 => uint256) private nextPeriodSwitchByDuration;
mapping(uint256 => uint256) private unlockClaimableFactorByDuration; // represented as x/1000
EnumerableSetUpgradeable.UintSet private durations;
mapping(uint256 => EnumerableSetUpgradeable.AddressSet) private futuresByDuration;
mapping(uint256 => uint256) private periodIndexByDurations;
EnumerableSetUpgradeable.AddressSet private pausedFutures;
/* Events */
event PlatformRegistered(address _platformControllerAddress);
event PlatformUnregistered(address _platformControllerAddress);
event NextPeriodSwitchSet(uint256 _periodDuration, uint256 _nextSwitchTimestamp);
event FutureRegistered(address _newFutureAddress);
event FutureUnregistered(address _future);
event NewUnlockClaimableFactor(uint256 _periodDuration, uint256 _newYieldUnlockFactor);
event StartingDelaySet(uint256 _startingDelay);
/* PlatformController Settings */
uint256 public STARTING_DELAY;
/* Modifiers */
modifier futureIsValid(address _future) {
require(registry.isRegisteredFuture(_future), "incorrect future address");
_;
}
/* Initializer */
/**
* @notice Initializer of the Controller contract
* @param _admin the address of the admin
*/
function initialize(address _admin, address _registry) public initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(ADMIN_ROLE, _admin);
registry = IRegistry(_registry);
}
/**
* @notice Change the delay for starting a new period
* @param _startingDelay the new delay (+-) to start the next period
*/
function setPeriodStartingDelay(uint256 _startingDelay) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
STARTING_DELAY = _startingDelay;
emit StartingDelaySet(_startingDelay);
}
/**
* @notice Set the next period switch timestamp for the future with corresponding duration
* @param _periodDuration the period duration
* @param _nextPeriodTimestamp the next period switch timestamp
*/
function setNextPeriodSwitchTimestamp(uint256 _periodDuration, uint256 _nextPeriodTimestamp) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set next period timestamp");
nextPeriodSwitchByDuration[_periodDuration] = _nextPeriodTimestamp;
emit NextPeriodSwitchSet(_periodDuration, _nextPeriodTimestamp);
}
/**
* @notice Set a new factor for the portion of the yield that is claimable when withdrawing funds during an ongoing period
* @param _periodDuration the duration of the periods
* @param _claimableYieldFactor the portion of the yield that is claimable
*/
function setUnlockClaimableFactor(uint256 _periodDuration, uint256 _claimableYieldFactor) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not allowed to set the unlock yield factor");
unlockClaimableFactorByDuration[_periodDuration] = _claimableYieldFactor;
emit NewUnlockClaimableFactor(_periodDuration, _claimableYieldFactor);
}
/* User Methods */
/**
* @notice Register an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be registered to
* @param _amount the amount to register
*/
function register(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).register(msg.sender, _amount);
require(ERC20(IFuture(_future).getIBTAddress()).transferFrom(msg.sender, _future, _amount), "invalid amount");
}
/**
* @notice Unregister an amount of IBT from the sender to the corresponding future
* @param _future the address of the future to be unregistered from
* @param _amount the amount to unregister
*/
function unregister(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).unregister(msg.sender, _amount);
}
/**
* @notice Withdraw deposited funds from APWine
* @param _future the address of the future to withdraw the IBT from
* @param _amount the amount to withdraw
*/
function withdrawLockFunds(address _future, uint256 _amount) public futureIsValid(_future) {
IFuture(_future).withdrawLockFunds(msg.sender, _amount);
}
/**
* @notice Claim FYT of the msg.sender
* @param _future the future from which to claim the FYT
*/
function claimFYT(address _future) public futureIsValid(_future) {
IFuture(_future).claimFYT(msg.sender);
}
/**
* @notice Register the sender to the corresponding platformController
* @param _user the address of the user
* @param futuresAddresses the addresses of the futures to claim the FYT from
*/
function claimSelectedYield(address _user, address[] memory futuresAddresses) public {
for (uint256 i = 0; i < futuresAddresses.length; i++) {
require(registry.isRegisteredFuture(futuresAddresses[i]), "Incorrect future address");
IFuture(futuresAddresses[i]).claimFYT(_user);
}
}
/* User Getter */
/**
* @notice Get the list of futures from which a user can claim FYT
* @param _user the user to check
*/
function getFuturesWithClaimableFYT(address _user) external view returns (address[] memory) {
address[] memory selectedFutures = new address[](registry.futureCount());
uint8 index = 0;
for (uint256 i = 0; i < registry.futureCount(); i++) {
if (IFuture(registry.getFutureAt(i)).hasClaimableFYT(_user)) {
selectedFutures[i] = registry.getFutureAt(i);
index += 1;
}
}
return selectedFutures;
}
/* Getter */
/**
* @notice Getter for the registry address of the protocol
* @return the address of the protocol registry
*/
function getRegistryAddress() external view returns (address) {
return address(registry);
}
/**
* @notice Getter for the symbol of the APWine IBT of one future
* @param _ibtSymbol the IBT of the external protocol
* @param _platform the external protocol name
* @param _periodDuration the duration of the periods for the future
* @return the generated symbol of the APWine IBT
*/
function getFutureIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) public view returns (string memory) {
return IAPWineNaming(registry.getNamingUtils()).genIBTSymbol(_ibtSymbol, _platform, _periodDuration);
}
/**
* @notice Getter for the symbol of the FYT of one future
* @param _apwibtSymbol the APWine IBT symbol for this future
* @param _periodDuration the duration of the periods for this future
* @return the generated symbol of the FYT
*/
function getFYTSymbol(string memory _apwibtSymbol, uint256 _periodDuration) public view returns (string memory) {
return
IAPWineNaming(registry.getNamingUtils()).genFYTSymbolFromIBT(
uint8(periodIndexByDurations[_periodDuration]),
_apwibtSymbol
);
}
/**
* @notice Getter for the period index depending on the period duration of the future
* @param _periodDuration the duration of the periods
* @return the period index
*/
function getPeriodIndex(uint256 _periodDuration) public view returns (uint256) {
return periodIndexByDurations[_periodDuration];
}
/**
* @notice Getter for the beginning timestamp of the next period for the futures with a defined period duration
* @param _periodDuration the duration of the periods
* @return the timestamp of the beginning of the next period
*/
function getNextPeriodStart(uint256 _periodDuration) public view returns (uint256) {
return nextPeriodSwitchByDuration[_periodDuration];
}
/**
* @notice Getter for the factor of claimable yield when unlocking
* @param _periodDuration the duration of the periods
* @return the factor of the claimable yield of the last period
*/
function getUnlockYieldFactor(uint256 _periodDuration) public view returns (uint256) {
return unlockClaimableFactorByDuration[_periodDuration];
}
/**
* @notice Getter for the list of future durations registered in the contract
* @return the list of future durations
*/
function getDurations() public view returns (uint256[] memory) {
uint256[] memory durationsList = new uint256[](durations.length());
for (uint256 i = 0; i < durations.length(); i++) {
durationsList[i] = durations.at(i);
}
return durationsList;
}
/**
* @notice Getter for the futures by period duration
* @param _periodDuration the period duration of the futures to return
*/
function getFuturesWithDuration(uint256 _periodDuration) public view returns (address[] memory) {
uint256 listLength = futuresByDuration[_periodDuration].length();
address[] memory filteredFutures = new address[](listLength);
for (uint256 i = 0; i < listLength; i++) {
filteredFutures[i] = futuresByDuration[_periodDuration].at(i);
}
return filteredFutures;
}
/* Future admin methods */
/**
* @notice Register a newly created future in the registry
* @param _newFuture the address of the new future
*/
function registerNewFuture(address _newFuture) public {
require(
hasRole(ADMIN_ROLE, msg.sender) || registry.isRegisteredFutureFactory(msg.sender),
"Caller cannot register a future"
);
registry.addFuture(_newFuture);
uint256 futureDuration = IFuture(_newFuture).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.add(futureDuration);
futuresByDuration[futureDuration].add(_newFuture);
emit FutureRegistered(_newFuture);
}
/**
* @notice Unregister a future from the registry
* @param _future the address of the future to unregister
*/
function unregisterFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
registry.removeFuture(_future);
uint256 futureDuration = IFuture(_future).PERIOD_DURATION();
if (!durations.contains(futureDuration)) durations.remove(futureDuration);
futuresByDuration[futureDuration].remove(_future);
emit FutureUnregistered(_future);
}
/**
* @notice Start all futures that have a defined period duration to synchronize them
* @param _periodDuration the period duration of the futures to start
*/
function startFuturesByPeriodDuration(uint256 _periodDuration) public {
for (uint256 i = 0; i < futuresByDuration[_periodDuration].length(); i++) {
if (!pausedFutures.contains(futuresByDuration[_periodDuration].at(i))) {
IFuture(futuresByDuration[_periodDuration].at(i)).startNewPeriod();
}
}
nextPeriodSwitchByDuration[_periodDuration] = nextPeriodSwitchByDuration[_periodDuration].add(_periodDuration);
periodIndexByDurations[_periodDuration] = periodIndexByDurations[_periodDuration].add(1);
}
/* Security functions */
/**
* @notice Interrupt a future avoiding news registrations
* @param _future the address of the future to pause
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function pauseFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).pausePeriods();
pausedFutures.add(_future);
}
/**
* @notice Resume a future that has been paused
* @param _future the address of the future to resume
* @dev should only be called in extraordinary situations by the admin of the contract
*/
function resumeFuture(address _future) public {
require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not an admin");
IFuture(_future).resumePeriods();
pausedFutures.remove(_future);
}
}
// 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(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../GSN/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;
}
pragma solidity 0.7.6;
import "contracts/interfaces/ERC20.sol";
interface IFutureYieldToken is ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) external;
/**
* @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) external;
/**
* @dev Creates `amount` new tokens for `to`.
*
* See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(address to, uint256 amount) external;
}
pragma solidity 0.7.6;
interface IFuture {
struct Registration {
uint256 startIndex;
uint256 scaledBalance;
}
/**
* @notice Getter for the PAUSE future parameter
* @return true if new periods are paused, false otherwise
*/
function PAUSED() external view returns (bool);
/**
* @notice Getter for the PERIOD future parameter
* @return returns the period duration of the future
*/
function PERIOD_DURATION() external view returns (uint256);
/**
* @notice Getter for the PLATFORM_NAME future parameter
* @return returns the platform of the future
*/
function PLATFORM_NAME() external view returns (uint256);
/**
* @notice Initializer
* @param _controller the address of the controller
* @param _ibt the address of the corresponding IBT
* @param _periodDuration the length of the period (in days)
* @param _platformName the name of the platform and tools
* @param _deployerAddress the future deployer address
* @param _admin the address of the ACR admin
*/
function initialize(
address _controller,
address _ibt,
uint256 _periodDuration,
string memory _platformName,
address _deployerAddress,
address _admin
) external;
/**
* @notice Set future wallet address
* @param _futureVault the address of the new future wallet
* @dev needs corresponding permissions for sender
*/
function setFutureVault(address _futureVault) external;
/**
* @notice Set futureWallet address
* @param _futureWallet the address of the new futureWallet
* @dev needs corresponding permissions for sender
*/
function setFutureWallet(address _futureWallet) external;
/**
* @notice Set liquidity gauge address
* @param _liquidityGauge the address of the new liquidity gauge
* @dev needs corresponding permissions for sender
*/
function setLiquidityGauge(address _liquidityGauge) external;
/**
* @notice Set apwibt address
* @param _apwibt the address of the new apwibt
* @dev used only for exceptional purpose
*/
function setAPWIBT(address _apwibt) external;
/**
* @notice Sender registers an amount of IBT for the next period
* @param _user address to register to the future
* @param _amount amount of IBT to be registered
* @dev called by the controller only
*/
function register(address _user, uint256 _amount) external;
/**
* @notice Sender unregisters an amount of IBT for the next period
* @param _user user addresss
* @param _amount amount of IBT to be unregistered
*/
function unregister(address _user, uint256 _amount) external;
/**
* @notice Sender unlocks the locked funds corresponding to their apwIBT holding
* @param _user the user address
* @param _amount amount of funds to unlocked
* @dev will require a transfer of FYT of the ongoing period corresponding to the funds unlocked
*/
function withdrawLockFunds(address _user, uint256 _amount) external;
/**
* @notice Send the user their owed FYT (and apwIBT if there are some claimable)
* @param _user address of the user to send the FYT to
*/
function claimFYT(address _user) external;
/**
* @notice Start a new period
* @dev needs corresponding permissions for sender
*/
function startNewPeriod() external;
/**
* @notice Check if a user has unclaimed FYT
* @param _user the user to check
* @return true if the user can claim some FYT, false otherwise
*/
function hasClaimableFYT(address _user) external view returns (bool);
/**
* @notice Check if a user has unclaimed apwIBT
* @param _user the user to check
* @return true if the user can claim some apwIBT, false otherwise
*/
function hasClaimableAPWIBT(address _user) external view returns (bool);
/**
* @notice Getter for user registered amount
* @param _user user to return the registered funds of
* @return the registered amount, 0 if no registrations
* @dev the registration can be older than the next period
*/
function getRegisteredAmount(address _user) external view returns (uint256);
/**
* @notice Getter for user IBT amount that is unlockable
* @param _user user to unlock the IBT from
* @return the amount of IBT the user can unlock
*/
function getUnlockableFunds(address _user) external view returns (uint256);
/**
* @notice Getter for yield that is generated by the user funds during the current period
* @param _user user to check the unrealized yield of
* @return the yield (amount of IBT) currently generated by the locked funds of the user
*/
function getUnrealisedYield(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of apwIBT that the user can claim
* @param _user the user to check the claimable apwIBT of
* @return the amount of apwIBT claimable by the user
*/
function getClaimableAPWIBT(address _user) external view returns (uint256);
/**
* @notice Getter for the amount of FYT that the user can claim for a certain period
* @param _user user to check the check the claimable FYT of
* @param _periodID period ID to check the claimable FYT of
* @return the amount of FYT claimable by the user for this period ID
*/
function getClaimableFYTForPeriod(address _user, uint256 _periodID) external view returns (uint256);
/**
* @notice Getter for next period index
* @return next period index
* @dev index starts at 1
*/
function getNextPeriodIndex() external view returns (uint256);
/**
* @notice Getter for controller address
* @return the controller address
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for future wallet address
* @return future wallet address
*/
function getFutureVaultAddress() external view returns (address);
/**
* @notice Getter for futureWallet address
* @return futureWallet address
*/
function getFutureWalletAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge address
* @return liquidity gauge address
*/
function getLiquidityGaugeAddress() external view returns (address);
/**
* @notice Getter for the IBT address
* @return IBT address
*/
function getIBTAddress() external view returns (address);
/**
* @notice Getter for future apwIBT address
* @return apwIBT address
*/
function getAPWIBTAddress() external view returns (address);
/**
* @notice Getter for FYT address of a particular period
* @param _periodIndex period index
* @return FYT address
*/
function getFYTofPeriod(uint256 _periodIndex) external view returns (address);
/* Admin functions*/
/**
* @notice Pause registrations and the creation of new periods
*/
function pausePeriods() external;
/**
* @notice Resume registrations and the creation of new periods
*/
function resumePeriods() external;
}
pragma solidity 0.7.6;
pragma experimental ABIEncoderV2;
interface IRegistry {
/**
* @notice Initializer of the contract
* @param _admin the address of the admin of the contract
*/
function initialize(address _admin) external;
/* Setters */
/**
* @notice Setter for the treasury address
* @param _newTreasury the address of the new treasury
*/
function setTreasury(address _newTreasury) external;
/**
* @notice Setter for the gauge controller address
* @param _newGaugeController the address of the new gauge controller
*/
function setGaugeController(address _newGaugeController) external;
/**
* @notice Setter for the controller address
* @param _newController the address of the new controller
*/
function setController(address _newController) external;
/**
* @notice Setter for the APW token address
* @param _newAPW the address of the APW token
*/
function setAPW(address _newAPW) external;
/**
* @notice Setter for the proxy factory address
* @param _proxyFactory the address of the new proxy factory
*/
function setProxyFactory(address _proxyFactory) external;
/**
* @notice Setter for the liquidity gauge address
* @param _liquidityGaugeLogic the address of the new liquidity gauge logic
*/
function setLiquidityGaugeLogic(address _liquidityGaugeLogic) external;
/**
* @notice Setter for the APWine IBT logic address
* @param _APWineIBTLogic the address of the new APWine IBT logic
*/
function setAPWineIBTLogic(address _APWineIBTLogic) external;
/**
* @notice Setter for the APWine FYT logic address
* @param _FYTLogic the address of the new APWine FYT logic
*/
function setFYTLogic(address _FYTLogic) external;
/**
* @notice Setter for the maths utils address
* @param _mathsUtils the address of the new math utils
*/
function setMathsUtils(address _mathsUtils) external;
/**
* @notice Setter for the naming utils address
* @param _namingUtils the address of the new naming utils
*/
function setNamingUtils(address _namingUtils) external;
/**
* @notice Getter for the controller address
* @return the address of the controller
*/
function getControllerAddress() external view returns (address);
/**
* @notice Getter for the treasury address
* @return the address of the treasury
*/
function getTreasuryAddress() external view returns (address);
/**
* @notice Getter for the gauge controller address
* @return the address of the gauge controller
*/
function getGaugeControllerAddress() external view returns (address);
/**
* @notice Getter for the DAO address
* @return the address of the DAO that has admin rights on the APW token
*/
function getDAOAddress() external returns (address);
/**
* @notice Getter for the APW token address
* @return the address the APW token
*/
function getAPWAddress() external view returns (address);
/**
* @notice Getter for the vesting contract address
* @return the vesting contract address
*/
function getVestingAddress() external view returns (address);
/**
* @notice Getter for the proxy factory address
* @return the proxy factory address
*/
function getProxyFactoryAddress() external view returns (address);
/**
* @notice Getter for liquidity gauge logic address
* @return the liquidity gauge logic address
*/
function getLiquidityGaugeLogicAddress() external view returns (address);
/**
* @notice Getter for APWine IBT logic address
* @return the APWine IBT logic address
*/
function getAPWineIBTLogicAddress() external view returns (address);
/**
* @notice Getter for APWine FYT logic address
* @return the APWine FYT logic address
*/
function getFYTLogicAddress() external view returns (address);
/**
* @notice Getter for math utils address
* @return the math utils address
*/
function getMathsUtils() external view returns (address);
/**
* @notice Getter for naming utils address
* @return the naming utils address
*/
function getNamingUtils() external view returns (address);
/* Future factory */
/**
* @notice Register a new future factory in the registry
* @param _futureFactory the address of the future factory contract
* @param _futureFactoryName the name of the future factory
*/
function addFutureFactory(address _futureFactory, string memory _futureFactoryName) external;
/**
* @notice Getter to check if a future factory is registered
* @param _futureFactory the address of the future factory contract to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFutureFactory(address _futureFactory) external view returns (bool);
/**
* @notice Getter for the future factory registered at an index
* @param _index the index of the future factory to return
* @return the address of the corresponding future factory
*/
function getFutureFactoryAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future factories registered
* @return the number of future factory registered
*/
function futureFactoryCount() external view returns (uint256);
/**
* @notice Getter for name of a future factory contract
* @param _futureFactory the address of a future factory
* @return the name of the corresponding future factory contract
*/
function getFutureFactoryName(address _futureFactory) external view returns (string memory);
/* Future platform */
/**
* @notice Register a new future platform in the registry
* @param _futureFactory the address of the future factory
* @param _futurePlatformName the name of the future platform
* @param _future the address of the future contract logic
* @param _futureWallet the address of the future wallet contract logic
* @param _futureVault the name of the future vault contract logic
*/
function addFuturePlatform(
address _futureFactory,
string memory _futurePlatformName,
address _future,
address _futureWallet,
address _futureVault
) external;
/**
* @notice Getter to check if a future platform is registered
* @param _futurePlatformName the name of the future platform to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuturePlatform(string memory _futurePlatformName) external view returns (bool);
/**
* @notice Getter for the future platform contracts
* @param _futurePlatformName the name of the future platform
* @return the addresses of 0) the future logic 1) the future wallet logic 2) the future vault logic
*/
function getFuturePlatform(string memory _futurePlatformName) external view returns (address[3] memory);
/**
* @notice Getter the total count of future platftroms registered
* @return the number of future platforms registered
*/
function futurePlatformsCount() external view returns (uint256);
/**
* @notice Getter the list of platforms names registered
* @return the list of platform names registered
*/
function getFuturePlatformNames() external view returns (string[] memory);
/**
* @notice Remove a future platform from the registry
* @param _futurePlatformName the name of the future platform to remove from the registry
*/
function removeFuturePlatform(string memory _futurePlatformName) external;
/* Futures */
/**
* @notice Add a future to the registry
* @param _future the address of the future to add to the registry
*/
function addFuture(address _future) external;
/**
* @notice Remove a future from the registry
* @param _future the address of the future to remove from the registry
*/
function removeFuture(address _future) external;
/**
* @notice Getter to check if a future is registered
* @param _future the address of the future to check the registration of
* @return true if it is, false otherwise
*/
function isRegisteredFuture(address _future) external view returns (bool);
/**
* @notice Getter for the future registered at an index
* @param _index the index of the future to return
* @return the address of the corresponding future
*/
function getFutureAt(uint256 _index) external view returns (address);
/**
* @notice Getter for number of future registered
* @return the number of future registered
*/
function futureCount() external view returns (uint256);
}
pragma solidity 0.7.6;
interface IAPWineNaming {
/**
* @notice generate the symbol of the FYT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbol(
uint8 _index,
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the FYT symbol from the apwIBT
* @param _index the index of the current period
* @param _ibtSymbol the symbol of the IBT
* @return the symbol for the FYT
* @dev i.e 30D-AAVE-ADAI-2
*/
function genFYTSymbolFromIBT(uint8 _index, string memory _ibtSymbol) external pure returns (string memory);
/**
* @notice generate the apwIBT symbol
* @param _ibtSymbol the symbol of the IBT of the future
* @param _platform the platform name
* @param _periodDuration the period duration
* @return the symbol for the apwIBT
* @dev i.e 30D-AAVE-ADAI
*/
function genIBTSymbol(
string memory _ibtSymbol,
string memory _platform,
uint256 _periodDuration
) external pure returns (string memory);
/**
* @notice generate the period denominator
* @param _periodDuration the period duration
* @return the period denominator
* @dev i.e 30D
*/
function getPeriodDurationDenominator(uint256 _periodDuration) external pure returns (string memory);
}
// 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, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.7.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ERC20 is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external returns (string memory);
/**
* @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() external returns (uint8);
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// 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);
} | * @notice Register the sender to the corresponding platformController @param _user the address of the user @param futuresAddresses the addresses of the futures to claim the FYT from/ | function claimSelectedYield(address _user, address[] memory futuresAddresses) public {
for (uint256 i = 0; i < futuresAddresses.length; i++) {
require(registry.isRegisteredFuture(futuresAddresses[i]), "Incorrect future address");
IFuture(futuresAddresses[i]).claimFYT(_user);
}
}
| 13,427,555 | [
1,
3996,
326,
5793,
358,
326,
4656,
4072,
2933,
225,
389,
1355,
326,
1758,
434,
326,
729,
225,
15583,
7148,
326,
6138,
434,
326,
15583,
358,
7516,
326,
478,
61,
56,
628,
19,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
7516,
7416,
16348,
12,
2867,
389,
1355,
16,
1758,
8526,
3778,
15583,
7148,
13,
1071,
288,
203,
3639,
364,
261,
11890,
5034,
277,
273,
374,
31,
277,
411,
15583,
7148,
18,
2469,
31,
277,
27245,
288,
203,
5411,
2583,
12,
9893,
18,
291,
10868,
4118,
12,
74,
10945,
7148,
63,
77,
65,
3631,
315,
16268,
3563,
1758,
8863,
203,
5411,
467,
4118,
12,
74,
10945,
7148,
63,
77,
65,
2934,
14784,
42,
61,
56,
24899,
1355,
1769,
203,
3639,
289,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
./partial_match/56/0xfE7B02D0B10e83F943051e4ED36aEeF9BB7c7C51/sources/ReferralRewardsType4.sol | @dev Returns claimed and unclaimed user's reward. @param _user Address of the user. @return _reward User's reward. | function getReward(address _user)
public
view
virtual
returns (uint256 _reward)
{
UserInfo storage user = userInfo[_user];
_reward = user.reward.add(getPendingReward(_user, false));
}
| 11,320,666 | [
1,
1356,
7516,
329,
471,
6301,
80,
4581,
329,
729,
1807,
19890,
18,
225,
389,
1355,
5267,
434,
326,
729,
18,
327,
389,
266,
2913,
2177,
1807,
19890,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
445,
4170,
359,
1060,
12,
2867,
389,
1355,
13,
203,
3639,
1071,
203,
3639,
1476,
203,
3639,
5024,
203,
3639,
1135,
261,
11890,
5034,
389,
266,
2913,
13,
203,
565,
288,
203,
3639,
25003,
2502,
729,
273,
16753,
63,
67,
1355,
15533,
203,
3639,
389,
266,
2913,
273,
729,
18,
266,
2913,
18,
1289,
12,
588,
8579,
17631,
1060,
24899,
1355,
16,
629,
10019,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
/**
*Submitted for verification at Etherscan.io on 2020-03-17
*/
pragma solidity ^0.5.15;
// https://github.com/makerdao/dss/blob/master/src/jug.sol
contract JugAbstract {
function drip(bytes32) external returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotAbstract {
function drip() external returns (uint256);
function dsr() public view returns (uint256);
function chi() public view returns (uint256);
function rho() public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vat.sol
contract VatAbstract {
function dai(address) public view returns (uint256);
function sin(address) public view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/vow.sol
contract VowAbstract {
function sin(uint256) public view returns (uint256);
function Sin() public view returns (uint256);
function Ash() public view returns (uint256);
function bump() public view returns (uint256);
function hump() public view returns (uint256);
function flap() external returns (uint256);
function heal(uint256) external;
}
// https://github.com/makerdao/sai/blob/master/src/pit.sol
contract GemPitAbstract {
function burn(address) public;
}
// https://github.com/dapphub/ds-token/blob/master/src/token.sol
contract DSTokenAbstract {
function balanceOf(address) external view returns (uint256);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol
contract PotHelper {
PotAbstract pa;
constructor(address pot) public {
pa = PotAbstract(pot);
}
// https://github.com/makerdao/dss/blob/master/src/pot.sol#L79
uint256 constant ONE = 10 ** 27;
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = mul(x, y) / ONE;
}
function rpow(uint x, uint n, uint base) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := base} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := base } default { z := x }
let half := div(base, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, base)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, base)
}
}
}
}
}
// View function for calculating value of chi iff drip() is called in the same block.
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
if (now == pa.rho()) return pa.chi();
return rmul(rpow(pa.dsr(), now - pa.rho(), ONE), pa.chi());
}
// Pass the Pot Abstract for additional operations
function pot() public view returns (PotAbstract) { //inject PUBLIC FUNC TO EXTERNAL
return pa;
}
}
// 1111111 1=111)) HADAIKEN
//
// Optimized contract for performing some or all of the functions that
// keep Multi-Collateral Dai running.
contract Hadaiken {
address constant internal PIT = address(0x69076e44a9C70a67D5b79d95795Aba299083c275);
address constant internal MKR = address(0x9f8F72aA9304c8B593d555F12eF6589cC3A579A2);
address constant internal JUG = address(0x19c0976f590D67707E62397C87829d896Dc0f1F1);
address constant internal POT = address(0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7);
address constant internal VAT = address(0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B);
address constant internal VOW = address(0xA950524441892A31ebddF91d3cEEFa04Bf454466);
GemPitAbstract constant internal pit = GemPitAbstract(PIT);
DSTokenAbstract constant internal gem = DSTokenAbstract(MKR);
JugAbstract constant internal jug = JugAbstract(JUG);
PotAbstract constant internal pot = PotAbstract(POT);
VowAbstract constant internal vow = VowAbstract(VOW);
VatAbstract constant internal vat = VatAbstract(VAT);
PotHelper internal poth;
bytes32 constant internal ETH_A = bytes32("ETH-A");
bytes32 constant internal BAT_A = bytes32("BAT-A");
bytes32 constant internal USDC_A = bytes32("USDC-A");
constructor() public {
poth = new PotHelper(POT);
}
// Raw System Debt
function _rawSysDebt() internal view returns (uint256) {
return (vat.sin(VOW) - vow.Sin() - vow.Ash());
}
function rawSysDebt() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _rawSysDebt();
}
function _sysSurplusThreshold() internal view returns (uint256) {
return (vat.sin(VOW) + vow.bump() + vow.hump());
}
function sysSurplusThreshold() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return _sysSurplusThreshold();
}
// Saves you money.
function heal() public { //inject PUBLIC FUNC TO EXTERNAL
_heal();
}
// Returns the amount of debt healed if you're curious about that sort of thing.
function healStat() public returns (uint256 sd) { //inject PUBLIC FUNC TO EXTERNAL
sd = _rawSysDebt();
_heal();
}
// No return here. I want to save gas and who cares.
function _heal() internal {
vow.heal(_rawSysDebt());
}
// Return the new chi value after drip.
function drip() public returns (uint256 chi) { //inject PUBLIC FUNC TO EXTERNAL
chi = pot.drip();
_dripIlks();
}
// Returns a simulated chi value
function drop() public view returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
return poth.drop();
}
function _dripPot() internal {
pot.drip();
}
function dripIlks() public { //inject PUBLIC FUNC TO EXTERNAL
_dripIlks();
}
function _dripIlks() internal {
jug.drip(ETH_A);
jug.drip(BAT_A);
jug.drip(USDC_A);
}
function kickable() public view returns (bool) { //inject PUBLIC FUNC TO EXTERNAL
return _kickable();
}
// Can we bump an auction?
function _kickable() internal view returns (bool) {
// Assume heal is called prior to kick.
// require(vat.dai(address(this)) >= add(add(vat.sin(address(this)), bump), hump), "Vow/insufficient-surplus");
// require(sub(sub(vat.sin(address(this)), Sin), Ash) == 0, "Vow/debt-not-zero");
return (vat.dai(VOW) >= _sysSurplusThreshold());
}
// Burn all of the MKR in the Sai Pit
function finishhim() public returns (uint256 burned) { //inject PUBLIC FUNC TO EXTERNAL
burned = gem.balanceOf(PIT);
_finishhim();
}
function _finishhim() internal {
pit.burn(MKR);
}
// Kick off an auction and return the auction ID
function ccccombobreaker() public returns (uint256) { //inject PUBLIC FUNC TO EXTERNAL
_heal(); // Flap requires debt == 0
return vow.flap();
}
// Kick off an auction and throw away id
function _ccccombobreaker() internal {
vow.flap();
}
// Kitchen sink. Call this early and often.
function hadaiken() public { //inject PUBLIC FUNC TO EXTERNAL
_dripPot(); // Update the chi
_dripIlks(); // Updates the Ilk rates
_heal(); // Cancel out system debt with system surplus
if (_kickable()) { _ccccombobreaker(); } // Start an auction
}
} | Returns the amount of debt healed if you're curious about that sort of thing. | sd = _rawSysDebt();
| 7,265,610 | [
1,
1356,
326,
3844,
434,
18202,
88,
3904,
18931,
309,
1846,
4565,
662,
22774,
2973,
716,
1524,
434,
7757,
18,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
3639,
8349,
273,
389,
1899,
12712,
758,
23602,
5621,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
pragma solidity >=0.4.11 <0.7.0;
import "./RoyaltyComputation.sol";
import "./Verification.sol";
import "./DecentralizedOracle.sol";
import "./RoyaltyComputation.sol";
contract Aggregator {
address public royaltyComputationContract;
Verification verif;
DecentralizedOracle decOracle;
RoyaltyComputation royComp;
string testData;
uint exchangeRate;
uint usageTime;
function setVerif(address _verif) public {
verif = Verification(_verif);
usageTime = verif.getDataInt();
}
function setDecOracle(address _dec) public {
decOracle = DecentralizedOracle(_dec);
exchangeRate = decOracle.getEuroExchange();
}
function setRoyaltyComputation(address _roy) public {
royComp = RoyaltyComputation(_roy);
}
// function Aggregator(address _verif, address _decOracle) {
// verif = Verification(_verif);
// testData = verif.getTestData();
// }
struct ParameterDescriptor{
uint paramId;
address sourceContract;
bool isPublic;
bool isPrivate;
}
struct RoyaltyParameter{
ParameterDescriptor param;
bool isAvailable;
string rawData;
}
function getExchangeRate() public returns (uint) {
return exchangeRate;
}
function getTestData() public returns (string) {
return testData;
}
function getUsageTime() public returns(uint) {
return usageTime;
}
function triggerRoyaltyComputation() public {
emit AllRoyaltyParamAvailable("Triggering royalty computation", block.timestamp);
// royComp.setUsageTime(usageTime);
usageTime = verif.getDataInt();
exchangeRate = decOracle.getEuroExchange();
// trigger royalty computation after params are updated
royComp.triggerComputation(exchangeRate, usageTime);
}
event AllRoyaltyParamAvailable(string msg, uint256 timestamp);
uint[] public royaltyParameterIds;
mapping(uint => ParameterDescriptor) royaltyParametersDescriptors;
mapping(uint => RoyaltyParameter) royaltyParams;
function areAllParamAvailable() private returns(bool) {
emit AllRoyaltyParamAvailable("Aggregator finished collecting royalty parameters.", block.timestamp);
// address adr = 0xD9BF44c40F097815caA9c9BEc87B762d87Fc2074;
// RoyaltyComputation r = RoyaltyComputation(adr);
// r.computeRoyalty();
return true;
}
function isParamAvailable(uint paramId) private returns(bool available){
return true;
}
function requestParameter(uint paramId) private returns(string param){
return "";
}
} | function Aggregator(address _verif, address _decOracle) { verif = Verification(_verif); testData = verif.getTestData(); } | struct ParameterDescriptor{
uint paramId;
address sourceContract;
bool isPublic;
bool isPrivate;
}
| 953,430 | [
1,
915,
10594,
639,
12,
2867,
389,
502,
430,
16,
1758,
389,
4924,
23601,
13,
288,
377,
1924,
430,
273,
26961,
24899,
502,
430,
1769,
377,
1842,
751,
273,
1924,
430,
18,
588,
4709,
751,
5621,
289,
2,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
1,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0,
0
] | [
1,
565,
1958,
5498,
3187,
95,
203,
3639,
2254,
579,
548,
31,
203,
3639,
1758,
1084,
8924,
31,
203,
3639,
1426,
19620,
31,
203,
3639,
1426,
30911,
31,
203,
565,
289,
203,
203,
2,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100,
-100
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.