file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
./full_match/1/0x9858e47BCbBe6fBAC040519B02d7cd4B2C470C66/sources/contracts/vault/OETHZapper.sol | Deposit SFRXETH to the vault and receive OETH in return amount Amount of SFRXETH to deposit minOETH Minimum amount of OETH to receive return Amount of OETH sent to user/ | function depositSFRXETH(uint256 amount, uint256 minOETH)
external
returns (uint256)
{
sfrxeth.redeem(amount, address(this), msg.sender);
emit Zap(msg.sender, address(sfrxeth), amount);
return _mint(address(frxeth), minOETH);
}
| 8,424,415 |
./full_match/80001/0x12424AE8c81855f9433FdAa3eedcF63411CA4966/sources/contracts/Forest.sol | / caller should not have a token | function safeMint(string memory uri) public {
require(
balanceOf(msg.sender) == 0,
"ERC721: caller already has a token"
);
uint256 tokenId = _tokenIdCounter.current();
_tokenIdCounter.increment();
_safeMint(msg.sender, tokenId);
_setTokenURI(tokenId, uri);
}
| 5,607,688 |
/* Proposal.sol */
pragma solidity >=0.4.0 <0.7.0;
import "../contracts/Person.sol";
import "../contracts/UserManager.sol";
import "../contracts/Set.sol";
import "../contracts/VotingToken.sol";
import "../contracts/TransactionDataSet.sol";
/* <Summary>
This contract manages one active proposal: Pays for proposal, Adds indicated
trade partners, finds random voters, manages transaction data, casts votes,
tallies votes, and give rewards
*/
contract Proposal {
using Set for Set.AddressData; // Set of addresses
using VotingToken for VotingToken.Token; // Voting token
// Struct full of transaction data
using TransactionDataSet for TransactionDataSet.DataSet;
// Map of lists of transaction data. [voter] -> list of data
mapping (address => TransactionDataSet.DataSet[]) transactionDataSets;
// Map of voting tokens. [voter] -> voting token
mapping (address => VotingToken.Token) votingtokens;
Set.AddressData voters; // Addresses who are eligible to vote
Set.AddressData archivedVoters; // Archived voters from past proposals
address[] haveTradedWith; // all of old accounts trading partners
address public lastOtherPartner; // Last randomly selected voter
uint numberOfVoters; // Number of required voters
uint public price; // Price of the account recovery
uint startTime; // The start of voting
uint8 VotingTokensCreated; // Number of Voting tokens created
uint8 randomVoterVetos = 3; // Number of vetos left
bool paided; // If the user has paid yet
constructor(uint _price) public {
price = _price; // Price of the proposal
}
// Allows the new account to pay for the proposal
function Pay(Person _newAccount) external {
require(_newAccount.balance() >= price, "Not Enough funds for this Proposal");
_newAccount.decreaseBalance(price); // Removes money from the new account
paided = true; // The proposal has been paid for
}
function AddTradePartners(address _newAccount, address _oldAccount,
address[] calldata _tradePartners, address[] calldata _archivedVoters,
TransactionManager TMI, ProposalManager PMI) external {
// Checks that the new account has paid
require(paided, "This proposal has not been paid for yet");
// Creates the archivedVoters set
for (uint i = 0; i < _archivedVoters.length; i++){
archivedVoters.insert(_archivedVoters[i]);
}
// Checks given trade partners and sets them as voters
for (uint i = 0; i < _tradePartners.length; i++){ // For each given partner
// The new account can not be a voter
if (_newAccount != _tradePartners[i]){
// Checks if the trade partner is black listed
if (!PMI.getBlacklistedAccount(_tradePartners[i])){
// Makes sure they are actually trade partners
if (TMI.NumberOfTransactions(_oldAccount, _tradePartners[i]) > 0){
// Voter was a voter in a past proposal for this account
if (!archivedVoters.contains(_tradePartners[i])){
// Has not already been indicated as a trade partner
if (!voters.contains(_tradePartners[i])){
// Make the trade partner a voter
voters.insert(_tradePartners[i]);
}
}
}
}
}
}
/*
// Requires at least 3 indicated valid voters
require(voters.getValuesLength() >= 2,
"Invalid Number of indicated trade partners");
*/
// Requires a maximum of 3 invlaid indicated trade partners
require(_tradePartners.length - voters.getValuesLength() < 3,
"You indicated too many invalid trade partners");
// Sets the required number of voters
numberOfVoters = voters.getValuesLength() * 2;
if (numberOfVoters < 5){ // Requires at least 5 voters
numberOfVoters = 5;
}
// Finds all of the old accounts's trade partners
address[] memory _haveTradedWith = TMI.getHaveTradedWith(_oldAccount);
// Checks if these trade partners are valid to be randomly selected voters
for (uint i = 0; i < _haveTradedWith.length; i++){ // For each address
// The new account can not be a voter
if (_newAccount != _haveTradedWith[i]){
// The were not already indicated as a voter
if (!voters.contains(_haveTradedWith[i])){
// They were not a voter in a past proposal for this account
if (!archivedVoters.contains(_haveTradedWith[i]) ){
// This address is an eligible voter
haveTradedWith.push(_haveTradedWith[i]);
}
}
}
}
require(haveTradedWith.length >= numberOfVoters - voters.getValuesLength(),
"Invalid number of other trade partners");
// Find the first randomly selected voter
RandomTradingPartner(true);
randomVoterVetos++;
}
// Adds last randomly selected voter and finds the next one
function RandomTradingPartner(bool _veto) public {
require(numberOfVoters != 0,
"Trade partners have not been added to this yet proposal");
// The new account remembers their transaction with this account
if (!_veto){
// This voter has not already been added to be a voter
require(!voters.contains(lastOtherPartner), "Already added that address");
// Makes the selected trade partner a voter
voters.insert(lastOtherPartner);
}else{
randomVoterVetos--;
}
// Select another trade partner randomly
if (voters.getValuesLength() != numberOfVoters){ // Needs to find more partners
require(randomVoterVetos >= 0,
"Can not veto any more randomly selected voters");
require(haveTradedWith.length >= numberOfVoters - voters.getValuesLength(),
"Can not veto this voter because there is not enough trade partners left");
// Finds a random index in the haveTradedWith array
uint index = random(lastOtherPartner, haveTradedWith.length);
// Finds the randomly selected trade partner
lastOtherPartner = haveTradedWith[index];
// Remove this trade partner from the list
for (uint i = index; i < haveTradedWith.length - 1; i++){
haveTradedWith[i] = haveTradedWith[i+1]; // Shift other address
}
delete haveTradedWith[haveTradedWith.length-1]; // Remove address
haveTradedWith.length--; // Reduce size
}
}
// Add set of data for a give transaction for a give voter
function AddTransactionDataSet(address _voter, uint _timeStamp, uint _amount,
string calldata _description, string calldata _importantNotes,
string calldata _location, string calldata _itemsInTrade) external {
// If this is the first set transaction data being added for this voter
if (transactionDataSets[_voter].length == 0){
// Create a voting token for this voter
votingtokens[_voter] = VotingToken.Token(0, false, false);
VotingTokensCreated++;
// If all voters are able to vote now
if (VotingTokensCreated == voters.getValuesLength()){
startTime = block.timestamp; // Start the timer on the voters
}
}
// Create the data set and add it to the list for this voter
transactionDataSets[_voter].push(TransactionDataSet.DataSet(
_description, _importantNotes, _location, _itemsInTrade,
_timeStamp, _amount));
}
// View public information on a set of data for a transaction
function ViewPublicInformation( address _voter, uint i)
external view returns (uint, uint) {
// Require that all voters are able to voter
require(VotingTokensCreated == voters.getValuesLength(),
"Have not created all the VotingTokens");
// Return transaction data
return transactionDataSets[_voter][i].ViewPublicInformation();
}
// View private information on a set of data for a transaction
function ViewPrivateInformation( address _voter, uint i)
external view returns (string memory, string memory,
string memory, string memory) {
// Require that all voters are able to voter
require(VotingTokensCreated == voters.getValuesLength(),
"Have not created all the VotingTokens");
// Return transaction data
return transactionDataSets[_voter][i].ViewPrivateInformation();
}
// Casts a vote
function CastVote(address _voter, bool choice) external {
// Require that all voters are able to voter
require(VotingTokensCreated == voters.getValuesLength(),
"Have not created all the VotingTokens");
votingtokens[_voter].CastVote(_voter, choice); // Casts the vote
}
// Give rewards to voters and return the outcome of the vote
function ConcludeProposal(uint vetoTime, UserManager UMI) external returns (int){
// Require that all voters are able to voter
require(VotingTokensCreated == voters.getValuesLength(),
"Have not created all the VotingTokens");
// Require that enough time has passed for the old account to veto an attack
if (vetoTime > block.timestamp - startTime){
return -1;
}
uint total = 0; // Total number of votes
uint yeses = 0; // Total number of yesses
uint totalTimeToVote = 0; // Total time used to vote
// Counts votes and find the time required for all voters to vote
for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters
// Get voting token for voter
VotingToken.Token storage temp = votingtokens[voters.getValue(i)];
// Incroment totalTimeToVote by the amount of time used by the voter
totalTimeToVote += temp.getVotedTime();
// Count votes
if (temp.getVoted()){ // They are a voter and they voted
total++; // Incroment the total number of votes
if (temp.getVote()){ // They are a voter and they voted yes
yeses++; // Incroment the number of yesses
}
}
}
// Requires a certain number of voters to vote before concluding the vote
if (total < (numberOfVoters*3)/4){
// If enough time has passed allow a revote
if (block.timestamp - startTime > 172800){
return 60;
}
return -2; // Require more votes
}
bool outcome = (100*yeses) / total >= 66; // The outcome of the vote
// Factors used in determining the requare for voters
uint participationFactor = 2; // Participation factor
uint correctionFactor = 2; // Correction factor
uint timeFactor = 1; // Time factor
// Average time used to vote
uint averageTimeToVote = totalTimeToVote / total;
// Rewards voters
for (uint i = 0; i < voters.getValuesLength(); i++) { // Goes through all voters
// Get voting token for voter
VotingToken.Token storage temp = votingtokens[voters.getValue(i)];
if (temp.getVoted()){ // If the voter has voted
// Reward for participating
uint amount = (price / participationFactor) / total;
// They voted correctly
if (outcome == temp.getVote()){
if (outcome){ // Yes was the correct vote
// Reward for voting correctly
amount += (price / correctionFactor) / yeses;
}else{ // No was the correct vote
// Reward for voting correctly
amount += (price / correctionFactor) / (total-yeses);
}
}
// Reward based on the time used to vote
// If they took less time than average they gain more money
amount += (averageTimeToVote - temp.getVotedTime()) / timeFactor;
if (amount > 0){ // The user actually did get a reward
// Increases balance of the voter
UMI.getUser(voters.getValue(i)).increaseBalance(amount);
}
}
}
return int((100*yeses) / total); // Return outcome of vote
}
// Generate random number using an address
function random(address address1, uint size) private view returns (uint8) {
return uint8(uint256(keccak256(abi.encodePacked(block.timestamp,
block.difficulty, address1, gasleft()))) % size);
// return uint8(uint256(keccak256(abi.encodePacked(block.difficulty, block.coinbase, address1, gasleft()))) % size);
}
// Return voters
function getVoters() external view returns (address[] memory){
return voters.getValues();
}
// Returns true is an address is a voter
function ContainsVoter(address _voter) external view returns (bool) {
return voters.contains(_voter);
}
}
| Returns true is an address is a voter | function ContainsVoter(address _voter) external view returns (bool) {
return voters.contains(_voter);
}
| 12,962,386 |
./full_match/4/0x80628b28F0a553cdc8e54603ed1a7B67e9d98a50/sources/AirnextToken.sol | Validation du gros transfert par les administrateurs wallets. 2 administrateurs sur 3 doient valider la transactions. | function validateTransfer(address _sender, address _recipient) external returns(bool) {
Latency storage thisBigTransfers = BigTransfers[_sender][_recipient];
require (thisBigTransfers._amount > 0, 'Ligne de tableau non valide');
require (msg.sender == addressAdminAirnext || msg.sender == addressTokenSale || msg.sender == addressTeam);
require (block.timestamp <= thisBigTransfers.loading);
require (thisBigTransfers.TransferEvent[msg.sender] == false);
thisBigTransfers.TransferEvent[msg.sender] = true;
bool adminAirnextValidation = thisBigTransfers.TransferEvent[addressAdminAirnext];
bool tokenSaleValidation = thisBigTransfers.TransferEvent[addressTokenSale];
bool tokenTeamValidation = thisBigTransfers.TransferEvent[addressTeam];
if( adminAirnextValidation && tokenSaleValidation || tokenTeamValidation && tokenSaleValidation || tokenTeamValidation && adminAirnextValidation )
{
thisBigTransfers.completed = true;
transferLatency(_sender, _recipient);
return true;
}
else if (block.timestamp <= thisBigTransfers.loading && (adminAirnextValidation || tokenTeamValidation || tokenSaleValidation))
{
thisBigTransfers.currState = State.PENDING;
thisBigTransfers.completed = false;
return true;
}
else {
thisBigTransfers.completed = false;
return false;
}
}
| 13,363,326 |
./partial_match/11155111/0x107438fD11D77f0531AedBACe08162802effe8ca/sources/project_/contracts/GeneralConsumer.sol | solhint-disable-line no-inline-assembly | function stringToBytes32(string memory source) private pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
| 3,533,515 |
./full_match/1/0xFE828d5c2cc4BfF59D5BEa660Dd8c61639F5016c/sources/contracts/Mech.sol | Disassembles(burn) a Mech NFT and return back Parts NFTs Params - `blockNumberLimit`: a transaction should end before blockNumberLimit - `parts`: Part tokenId list that will be transferred to the owner after a Mech is disassembled - `tokenId`: a Mech NFT tokenId. msgSender should be the owner of this token - `signature`: signature to validate all parameters/ payment | function disassemble(
uint256 blockNumberLimit,
uint256[] calldata parts,
uint256 tokenId,
bytes calldata signature) external payable nonReentrant {
require(ownerOf(tokenId) == _msgSender(), "Sender does not own a Mech");
require(block.number <= blockNumberLimit, "Transaction has expired");
require(validateDisassemble(blockNumberLimit, _msgSender(), tokenId, signature), "Invalid signature");
bytes32 partsKey = generateUniqueMechKey(parts);
require(tokenId == getMechTokenId(partsKey), "Part hash value does not match with a Mech tokenId");
checkPayment(disassemblePrice);
_burn(tokenId);
for (uint i=0; i< parts.length; i++) {
partContract.safeTransferFrom(address(this), _msgSender(), parts[i]);
}
emit Disassembled(_msgSender(), tokenId, parts);
}
| 16,559,904 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Address } from "@openzeppelin/contracts/utils/Address.sol";
import { BoringMath, BoringMath128 } from "./libraries/boring/BoringMath.sol";
import { BoringOwnable } from "./libraries/boring/BoringOwnable.sol";
import { BoringERC20 } from "./libraries/boring/BoringERC20.sol";
import { IRewarder } from "./interfaces/sushi/IRewarder.sol";
import { IMasterChefV2 } from "./interfaces/sushi/IMasterChefV2.sol";
import "hardhat/console.sol";
contract ALCXRewarder is IRewarder, BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
IERC20 private immutable rewardToken;
IMasterChefV2 private immutable MC_V2;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
uint256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accTokenPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
uint256[] public poolIds;
/// @notice Info of each pool.
mapping(uint256 => PoolInfo) public poolInfo;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 totalAllocPoint;
uint256 public tokenPerBlock;
uint256 private constant ACC_TOKEN_PRECISION = 1e12;
event PoolAdded(uint256 indexed pid, uint256 allocPoint);
event PoolSet(uint256 indexed pid, uint256 allocPoint);
event PoolUpdated(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accTokenPerShare);
event OnReward(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event RewardRateUpdated(uint256 oldRate, uint256 newRate);
modifier onlyMCV2 {
require(msg.sender == address(MC_V2), "ALCXRewarder::onlyMCV2: only MasterChef V2 can call this function.");
_;
}
constructor(
IERC20 _rewardToken,
uint256 _tokenPerBlock,
IMasterChefV2 _MCV2
) public {
require(Address.isContract(address(_rewardToken)), "ALCXRewarder: reward token must be a valid contract");
require(Address.isContract(address(_MCV2)), "ALCXRewarder: MasterChef V2 must be a valid contract");
rewardToken = _rewardToken;
tokenPerBlock = _tokenPerBlock;
MC_V2 = _MCV2;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _pid Pid on MCV2
function addPool(uint256 _pid, uint256 allocPoint) public onlyOwner {
require(poolInfo[_pid].lastRewardBlock == 0, "ALCXRewarder::add: cannot add existing pool");
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolInfo[_pid] = PoolInfo({
allocPoint: allocPoint.to64(),
lastRewardBlock: lastRewardBlock.to64(),
accTokenPerShare: 0
});
poolIds.push(_pid);
emit PoolAdded(_pid, allocPoint);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
function setPool(uint256 _pid, uint256 _allocPoint) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
emit PoolSet(_pid, _allocPoint);
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = MC_V2.lpToken(pid).balanceOf(address(MC_V2));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;
pool.accTokenPerShare = pool.accTokenPerShare.add(
(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit PoolUpdated(pid, pool.lastRewardBlock, lpSupply, pool.accTokenPerShare);
}
}
/// @notice Update reward variables for all pools
/// @dev Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) public {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @dev Sets the distribution reward rate. This will also update all of the pools.
/// @param _tokenPerBlock The number of tokens to distribute per block
function setRewardRate(uint256 _tokenPerBlock, uint256[] calldata _pids) external onlyOwner {
massUpdatePools(_pids);
uint256 oldRate = tokenPerBlock;
tokenPerBlock = _tokenPerBlock;
emit RewardRateUpdated(oldRate, _tokenPerBlock);
}
function onSushiReward(
uint256 pid,
address _user,
address to,
uint256,
uint256 lpToken
) external override onlyMCV2 {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][_user];
uint256 pending;
// if user had deposited
if (user.amount > 0) {
pending = (user.amount.mul(pool.accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
rewardToken.safeTransfer(to, pending);
}
user.amount = lpToken;
user.rewardDebt = user.rewardDebt.add(pending);
emit OnReward(_user, pid, pending, to);
}
function pendingTokens(
uint256 pid,
address user,
uint256
) external view override returns (IERC20[] memory rewardTokens, uint256[] memory rewardAmounts) {
IERC20[] memory _rewardTokens = new IERC20[](1);
_rewardTokens[0] = (rewardToken);
uint256[] memory _rewardAmounts = new uint256[](1);
_rewardAmounts[0] = pendingToken(pid, user);
return (_rewardTokens, _rewardAmounts);
}
/// @notice View function to see pending Token
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingToken(uint256 _pid, address _user) public view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokenPerShare = pool.accTokenPerShare;
uint256 lpSupply = MC_V2.lpToken(_pid).balanceOf(address(MC_V2));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokenReward = blocks.mul(tokenPerBlock).mul(pool.allocPoint) / totalAllocPoint;
accTokenPerShare = accTokenPerShare.add(tokenReward.mul(ACC_TOKEN_PRECISION) / lpSupply);
}
pending = (user.amount.mul(accTokenPerShare) / ACC_TOKEN_PRECISION).sub(user.rewardDebt);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library 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;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.2;
/**
* @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);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath::add: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath::sub: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath::mul: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath::to128: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath::to64: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath::to32: uint32 Overflow");
c = uint32(a);
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128.
library BoringMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a + b) >= b, "BoringMath128::add: Add Overflow");
}
function sub(uint128 a, uint128 b) internal pure returns (uint128 c) {
require((c = a - b) <= a, "BoringMath128::sub: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint64.
library BoringMath64 {
function add(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a + b) >= b, "BoringMath64::add: Add Overflow");
}
function sub(uint64 a, uint64 b) internal pure returns (uint64 c) {
require((c = a - b) <= a, "BoringMath64::sub: Underflow");
}
}
/// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint32.
library BoringMath32 {
function add(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a + b) >= b, "BoringMath32::add: Add Overflow");
}
function sub(uint32 a, uint32 b) internal pure returns (uint32 c) {
require((c = a - b) <= a, "BoringMath32::sub: Underflow");
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
// Audit on 5-Jan-2021 by Keno and BoringCrypto
// Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol
// Edited by BoringCrypto
contract BoringOwnableData {
address public owner;
address public pendingOwner;
}
contract BoringOwnable is BoringOwnableData {
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/// @notice `owner` defaults to msg.sender on construction.
constructor() public {
owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner.
/// Can only be invoked by the current `owner`.
/// @param newOwner Address of the new owner.
/// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`.
/// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise.
function transferOwnership(
address newOwner,
bool direct,
bool renounce
) public onlyOwner {
if (direct) {
// Checks
require(newOwner != address(0) || renounce, "BoringOwnable::transferOwnership: zero address");
// Effects
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
pendingOwner = address(0);
} else {
// Effects
pendingOwner = newOwner;
}
}
/// @notice Needs to be called by `pendingOwner` to claim ownership.
function claimOwnership() public {
address _pendingOwner = pendingOwner;
// Checks
require(msg.sender == _pendingOwner, "BoringOwnable::claimOwnership: caller != pending owner");
// Effects
emit OwnershipTransferred(owner, _pendingOwner);
owner = _pendingOwner;
pendingOwner = address(0);
}
/// @notice Only allows the `owner` to execute the function.
modifier onlyOwner() {
require(msg.sender == owner, "BoringOwnable::onlyOwner: caller is not the owner");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// solhint-disable avoid-low-level-calls
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
function returnDataToString(bytes memory data) internal pure returns (string memory) {
if (data.length >= 64) {
return abi.decode(data, (string));
} else if (data.length == 32) {
uint8 i = 0;
while (i < 32 && data[i] != 0) {
i++;
}
bytes memory bytesArray = new bytes(i);
for (i = 0; i < 32 && data[i] != 0; i++) {
bytesArray[i] = data[i];
}
return string(bytesArray);
} else {
return "???";
}
}
/// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token symbol.
function safeSymbol(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.name version which returns '???' as fallback string.
/// @param token The address of the ERC-20 token contract.
/// @return (string) Token name.
function safeName(IERC20 token) internal view returns (string memory) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME));
return success ? returnDataToString(data) : "???";
}
/// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value.
/// @param token The address of the ERC-20 token contract.
/// @return (uint8) Token decimals.
function safeDecimals(IERC20 token) internal view returns (uint8) {
(bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS));
return success && data.length == 32 ? abi.decode(data, (uint8)) : 18;
}
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20::safeTransfer: transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) =
address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"BoringERC20::safeTransferFrom: transfer failed"
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../../libraries/boring/BoringERC20.sol";
interface IRewarder {
using BoringERC20 for IERC20;
function onSushiReward(
uint256 pid,
address user,
address recipient,
uint256 sushiAmount,
uint256 newLpAmount
) external;
function pendingTokens(
uint256 pid,
address user,
uint256 sushiAmount
) external view returns (IERC20[] memory, uint256[] memory);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../libraries/boring/BoringERC20.sol";
interface IMasterChefV2 {
using BoringERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below.
}
function lpToken(uint256 pid) external view returns (IERC20);
function poolInfo(uint256 pid) external view returns (PoolInfo memory);
function totalAllocPoint() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.9.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "hardhat/console.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { ReentrancyGuard } from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { StakingPools } from "./StakingPools.sol";
import { FixedPointMath } from "./libraries/math/FixedPointMath.sol";
import { IMintableERC20 } from "./interfaces/token/ERC20/IMintableERC20.sol";
import { Pool } from "./libraries/pools/Pool.sol";
import { Stake } from "./libraries/pools/Stake.sol";
import "hardhat/console.sol";
/// @title StakingPools
// ___ __ __ _ ___ __ _
// / _ | / / ____ / / ___ __ _ (_) __ __ / _ \ ____ ___ ___ ___ ___ / /_ ___ (_)
// / __ | / / / __/ / _ \/ -_) / ' \ / / \ \ / / ___/ / __// -_) (_-</ -_) / _ \/ __/ (_-< _
// /_/ |_|/_/ \__/ /_//_/\__/ /_/_/_//_/ /_\_\ /_/ /_/ \__/ /___/\__/ /_//_/\__/ /___/(_)
//
// _______..___________. ___ __ ___ __ .__ __. _______ .______ ______ ______ __ _______.
// / || | / \ | |/ / | | | \ | | / _____| | _ \ / __ \ / __ \ | | / |
// | (----``---| |----` / ^ \ | ' / | | | \| | | | __ | |_) | | | | | | | | | | | | (----`
// \ \ | | / /_\ \ | < | | | . ` | | | |_ | | ___/ | | | | | | | | | | \ \
// .----) | | | / _____ \ | . \ | | | |\ | | |__| | | | | `--' | | `--' | | `----..----) |
// |_______/ |__| /__/ \__\ |__|\__\ |__| |__| \__| \______| | _| \______/ \______/ |_______||_______/
///
/// @dev A contract which allows users to stake to farm tokens.
///
/// This contract was inspired by Chef Nomi's 'MasterChef' contract which can be found in this
/// repository: https://github.com/sushiswap/sushiswap.
contract StakingPools is ReentrancyGuard {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeERC20 for IERC20;
using SafeMath for uint256;
using Stake for Stake.Data;
event PendingGovernanceUpdated(address pendingGovernance);
event GovernanceUpdated(address governance);
event RewardRateUpdated(uint256 rewardRate);
event PoolRewardWeightUpdated(uint256 indexed poolId, uint256 rewardWeight);
event PoolCreated(uint256 indexed poolId, IERC20 indexed token);
event TokensDeposited(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensWithdrawn(address indexed user, uint256 indexed poolId, uint256 amount);
event TokensClaimed(address indexed user, uint256 indexed poolId, uint256 amount);
/// @dev The token which will be minted as a reward for staking.
IMintableERC20 public reward;
/// @dev The address of the account which currently has administrative capabilities over this contract.
address public governance;
address public pendingGovernance;
/// @dev Tokens are mapped to their pool identifier plus one. Tokens that do not have an associated pool
/// will return an identifier of zero.
mapping(IERC20 => uint256) public tokenPoolIds;
/// @dev The context shared between the pools.
Pool.Context private _ctx;
/// @dev A list of all of the pools.
Pool.List private _pools;
/// @dev A mapping of all of the user stakes mapped first by pool and then by address.
mapping(address => mapping(uint256 => Stake.Data)) private _stakes;
constructor(IMintableERC20 _reward, address _governance) public {
require(_governance != address(0), "StakingPools: governance address cannot be 0x0");
reward = _reward;
governance = _governance;
}
/// @dev A modifier which reverts when the caller is not the governance.
modifier onlyGovernance() {
require(msg.sender == governance, "StakingPools: only governance");
_;
}
/// @dev Sets the governance.
///
/// This function can only called by the current governance.
///
/// @param _pendingGovernance the new pending governance.
function setPendingGovernance(address _pendingGovernance) external onlyGovernance {
require(_pendingGovernance != address(0), "StakingPools: pending governance address cannot be 0x0");
pendingGovernance = _pendingGovernance;
emit PendingGovernanceUpdated(_pendingGovernance);
}
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "StakingPools: only pending governance");
address _pendingGovernance = pendingGovernance;
governance = _pendingGovernance;
emit GovernanceUpdated(_pendingGovernance);
}
/// @dev Sets the distribution reward rate.
///
/// This will update all of the pools.
///
/// @param _rewardRate The number of tokens to distribute per second.
function setRewardRate(uint256 _rewardRate) external onlyGovernance {
_updatePools();
_ctx.rewardRate = _rewardRate;
emit RewardRateUpdated(_rewardRate);
}
/// @dev Creates a new pool.
///
/// The created pool will need to have its reward weight initialized before it begins generating rewards.
///
/// @param _token The token the pool will accept for staking.
///
/// @return the identifier for the newly created pool.
function createPool(IERC20 _token) external onlyGovernance returns (uint256) {
require(tokenPoolIds[_token] == 0, "StakingPools: token already has a pool");
uint256 _poolId = _pools.length();
_pools.push(
Pool.Data({
token: _token,
totalDeposited: 0,
rewardWeight: 0,
accumulatedRewardWeight: FixedPointMath.uq192x64(0),
lastUpdatedBlock: block.number
})
);
tokenPoolIds[_token] = _poolId + 1;
emit PoolCreated(_poolId, _token);
return _poolId;
}
/// @dev Sets the reward weights of all of the pools.
///
/// @param _rewardWeights The reward weights of all of the pools.
function setRewardWeights(uint256[] calldata _rewardWeights) external onlyGovernance {
require(_rewardWeights.length == _pools.length(), "StakingPools: weights length mismatch");
_updatePools();
uint256 _totalRewardWeight = _ctx.totalRewardWeight;
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
uint256 _currentRewardWeight = _pool.rewardWeight;
if (_currentRewardWeight == _rewardWeights[_poolId]) {
continue;
}
// FIXME
_totalRewardWeight = _totalRewardWeight.sub(_currentRewardWeight).add(_rewardWeights[_poolId]);
_pool.rewardWeight = _rewardWeights[_poolId];
emit PoolRewardWeightUpdated(_poolId, _rewardWeights[_poolId]);
}
_ctx.totalRewardWeight = _totalRewardWeight;
}
/// @dev Stakes tokens into a pool.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function deposit(uint256 _poolId, uint256 _depositAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_deposit(_poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function withdraw(uint256 _poolId, uint256 _withdrawAmount) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function claim(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
}
/// @dev Claims all rewards from a pool and then withdraws all staked tokens.
///
/// @param _poolId the pool to exit from.
function exit(uint256 _poolId) external nonReentrant {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_stake.update(_pool, _ctx);
_claim(_poolId);
_withdraw(_poolId, _stake.totalDeposited);
}
/// @dev Gets the rate at which tokens are minted to stakers for all pools.
///
/// @return the reward rate.
function rewardRate() external view returns (uint256) {
return _ctx.rewardRate;
}
/// @dev Gets the total reward weight between all the pools.
///
/// @return the total reward weight.
function totalRewardWeight() external view returns (uint256) {
return _ctx.totalRewardWeight;
}
/// @dev Gets the number of pools that exist.
///
/// @return the pool count.
function poolCount() external view returns (uint256) {
return _pools.length();
}
/// @dev Gets the token a pool accepts.
///
/// @param _poolId the identifier of the pool.
///
/// @return the token.
function getPoolToken(uint256 _poolId) external view returns (IERC20) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.token;
}
/// @dev Gets the total amount of funds staked in a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the total amount of staked or deposited tokens.
function getPoolTotalDeposited(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.totalDeposited;
}
/// @dev Gets the reward weight of a pool which determines how much of the total rewards it receives per block.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward weight.
function getPoolRewardWeight(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.rewardWeight;
}
/// @dev Gets the amount of tokens per block being distributed to stakers for a pool.
///
/// @param _poolId the identifier of the pool.
///
/// @return the pool reward rate.
function getPoolRewardRate(uint256 _poolId) external view returns (uint256) {
Pool.Data storage _pool = _pools.get(_poolId);
return _pool.getRewardRate(_ctx);
}
/// @dev Gets the number of tokens a user has staked into a pool.
///
/// @param _account The account to query.
/// @param _poolId the identifier of the pool.
///
/// @return the amount of deposited tokens.
function getStakeTotalDeposited(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.totalDeposited;
}
/// @dev Gets the number of unclaimed reward tokens a user can claim from a pool.
///
/// @param _account The account to get the unclaimed balance of.
/// @param _poolId The pool to check for unclaimed rewards.
///
/// @return the amount of unclaimed reward tokens a user has in a pool.
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256) {
Stake.Data storage _stake = _stakes[_account][_poolId];
return _stake.getUpdatedTotalUnclaimed(_pools.get(_poolId), _ctx);
}
/// @dev Updates all of the pools.
function _updatePools() internal {
for (uint256 _poolId = 0; _poolId < _pools.length(); _poolId++) {
Pool.Data storage _pool = _pools.get(_poolId);
_pool.update(_ctx);
}
}
/// @dev Stakes tokens into a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId the pool to deposit tokens into.
/// @param _depositAmount the amount of tokens to deposit.
function _deposit(uint256 _poolId, uint256 _depositAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.add(_depositAmount);
_stake.totalDeposited = _stake.totalDeposited.add(_depositAmount);
_pool.token.safeTransferFrom(msg.sender, address(this), _depositAmount);
emit TokensDeposited(msg.sender, _poolId, _depositAmount);
}
/// @dev Withdraws staked tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to withdraw staked tokens from.
/// @param _withdrawAmount The number of tokens to withdraw.
function _withdraw(uint256 _poolId, uint256 _withdrawAmount) internal {
Pool.Data storage _pool = _pools.get(_poolId);
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
_pool.totalDeposited = _pool.totalDeposited.sub(_withdrawAmount);
_stake.totalDeposited = _stake.totalDeposited.sub(_withdrawAmount);
_pool.token.safeTransfer(msg.sender, _withdrawAmount);
emit TokensWithdrawn(msg.sender, _poolId, _withdrawAmount);
}
/// @dev Claims all rewarded tokens from a pool.
///
/// The pool and stake MUST be updated before calling this function.
///
/// @param _poolId The pool to claim rewards from.
///
/// @notice use this function to claim the tokens from a corresponding pool by ID.
function _claim(uint256 _poolId) internal {
Stake.Data storage _stake = _stakes[msg.sender][_poolId];
uint256 _claimAmount = _stake.totalUnclaimed;
_stake.totalUnclaimed = 0;
reward.mint(msg.sender, _claimAmount);
emit TokensClaimed(msg.sender, _poolId, _claimAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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].
*/
contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
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
pragma solidity ^0.6.12;
library FixedPointMath {
uint256 public constant DECIMALS = 18;
uint256 public constant SCALAR = 10**DECIMALS;
struct uq192x64 {
uint256 x;
}
function fromU256(uint256 value) internal pure returns (uq192x64 memory) {
uint256 x;
require(value == 0 || (x = value * SCALAR) / SCALAR == value);
return uq192x64(x);
}
function maximumValue() internal pure returns (uq192x64 memory) {
return uq192x64(uint256(-1));
}
function add(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) {
uint256 x;
require((x = self.x + value.x) >= self.x);
return uq192x64(x);
}
function add(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) {
return add(self, fromU256(value));
}
function sub(uq192x64 memory self, uq192x64 memory value) internal pure returns (uq192x64 memory) {
uint256 x;
require((x = self.x - value.x) <= self.x);
return uq192x64(x);
}
function sub(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) {
return sub(self, fromU256(value));
}
function mul(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) {
uint256 x;
require(value == 0 || (x = self.x * value) / value == self.x);
return uq192x64(x);
}
function div(uq192x64 memory self, uint256 value) internal pure returns (uq192x64 memory) {
require(value != 0);
return uq192x64(self.x / value);
}
function cmp(uq192x64 memory self, uq192x64 memory value) internal pure returns (int256) {
if (self.x < value.x) {
return -1;
}
if (self.x > value.x) {
return 1;
}
return 0;
}
function decode(uq192x64 memory self) internal pure returns (uint256) {
return self.x / SCALAR;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import { IDetailedERC20 } from "./IDetailedERC20.sol";
interface IMintableERC20 is IDetailedERC20 {
function mint(address _recipient, uint256 _amount) external;
function burnFrom(address account, uint256 amount) external;
function lowerHasMinted(uint256 amount) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { FixedPointMath } from "../math/FixedPointMath.sol";
import { IDetailedERC20 } from "../../interfaces/token/ERC20/IDetailedERC20.sol";
import "hardhat/console.sol";
/// @title Pool
///
/// @dev A library which provides the Pool data struct and associated functions.
library Pool {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using Pool for Pool.List;
using SafeMath for uint256;
struct Context {
uint256 rewardRate;
uint256 totalRewardWeight;
}
struct Data {
IERC20 token;
uint256 totalDeposited;
uint256 rewardWeight;
FixedPointMath.uq192x64 accumulatedRewardWeight;
uint256 lastUpdatedBlock;
}
struct List {
Data[] elements;
}
/// @dev Updates the pool.
///
/// @param _ctx the pool context.
function update(Data storage _data, Context storage _ctx) internal {
_data.accumulatedRewardWeight = _data.getUpdatedAccumulatedRewardWeight(_ctx);
_data.lastUpdatedBlock = block.number;
}
/// @dev Gets the rate at which the pool will distribute rewards to stakers.
///
/// @param _ctx the pool context.
///
/// @return the reward rate of the pool in tokens per block.
function getRewardRate(Data storage _data, Context storage _ctx) internal view returns (uint256) {
// console.log("get reward rate");
// console.log(uint(_data.rewardWeight));
// console.log(uint(_ctx.totalRewardWeight));
// console.log(uint(_ctx.rewardRate));
return _ctx.rewardRate.mul(_data.rewardWeight).div(_ctx.totalRewardWeight);
}
/// @dev Gets the accumulated reward weight of a pool.
///
/// @param _ctx the pool context.
///
/// @return the accumulated reward weight.
function getUpdatedAccumulatedRewardWeight(Data storage _data, Context storage _ctx)
internal
view
returns (FixedPointMath.uq192x64 memory)
{
if (_data.totalDeposited == 0) {
return _data.accumulatedRewardWeight;
}
uint256 _elapsedTime = block.number.sub(_data.lastUpdatedBlock);
if (_elapsedTime == 0) {
return _data.accumulatedRewardWeight;
}
uint256 _rewardRate = _data.getRewardRate(_ctx);
uint256 _distributeAmount = _rewardRate.mul(_elapsedTime);
if (_distributeAmount == 0) {
return _data.accumulatedRewardWeight;
}
FixedPointMath.uq192x64 memory _rewardWeight =
FixedPointMath.fromU256(_distributeAmount).div(_data.totalDeposited);
return _data.accumulatedRewardWeight.add(_rewardWeight);
}
/// @dev Adds an element to the list.
///
/// @param _element the element to add.
function push(List storage _self, Data memory _element) internal {
_self.elements.push(_element);
}
/// @dev Gets an element from the list.
///
/// @param _index the index in the list.
///
/// @return the element at the specified index.
function get(List storage _self, uint256 _index) internal view returns (Data storage) {
return _self.elements[_index];
}
/// @dev Gets the last element in the list.
///
/// This function will revert if there are no elements in the list.
///ck
/// @return the last element in the list.
function last(List storage _self) internal view returns (Data storage) {
return _self.elements[_self.lastIndex()];
}
/// @dev Gets the index of the last element in the list.
///
/// This function will revert if there are no elements in the list.
///
/// @return the index of the last element.
function lastIndex(List storage _self) internal view returns (uint256) {
uint256 _length = _self.length();
return _length.sub(1, "Pool.List: list is empty");
}
/// @dev Gets the number of elements in the list.
///
/// @return the number of elements.
function length(List storage _self) internal view returns (uint256) {
return _self.elements.length;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import { Math } from "@openzeppelin/contracts/math/Math.sol";
import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { FixedPointMath } from "../math/FixedPointMath.sol";
import { IDetailedERC20 } from "../../interfaces/token/ERC20/IDetailedERC20.sol";
import { Pool } from "./Pool.sol";
import "hardhat/console.sol";
/// @title Stake
///
/// @dev A library which provides the Stake data struct and associated functions.
library Stake {
using FixedPointMath for FixedPointMath.uq192x64;
using Pool for Pool.Data;
using SafeMath for uint256;
using Stake for Stake.Data;
struct Data {
uint256 totalDeposited;
uint256 totalUnclaimed;
FixedPointMath.uq192x64 lastAccumulatedWeight;
}
function update(
Data storage _self,
Pool.Data storage _pool,
Pool.Context storage _ctx
) internal {
_self.totalUnclaimed = _self.getUpdatedTotalUnclaimed(_pool, _ctx);
_self.lastAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx);
}
function getUpdatedTotalUnclaimed(
Data storage _self,
Pool.Data storage _pool,
Pool.Context storage _ctx
) internal view returns (uint256) {
FixedPointMath.uq192x64 memory _currentAccumulatedWeight = _pool.getUpdatedAccumulatedRewardWeight(_ctx);
FixedPointMath.uq192x64 memory _lastAccumulatedWeight = _self.lastAccumulatedWeight;
if (_currentAccumulatedWeight.cmp(_lastAccumulatedWeight) == 0) {
return _self.totalUnclaimed;
}
uint256 _distributedAmount =
_currentAccumulatedWeight.sub(_lastAccumulatedWeight).mul(_self.totalDeposited).decode();
return _self.totalUnclaimed.add(_distributedAmount);
}
}
// 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;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IDetailedERC20 is IERC20 {
function name() external returns (string memory);
function symbol() external returns (string memory);
function decimals() external returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../../Domain.sol";
import "../../../interfaces/token/ERC20/IDetailedERC20.sol";
import "hardhat/console.sol";
// solhint-disable no-inline-assembly
// solhint-disable not-rely-on-time
// Data part taken out for building of contracts that receive delegate calls
contract ERC20Data {
/// @notice owner > balance mapping.
mapping(address => uint256) public balanceOf;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
string public name;
string public symbol;
uint256 public decimals;
}
contract ERC20 is ERC20Data, Domain {
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/**
* @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 two 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;
}
/// @notice Transfers `amount` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param amount of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 amount) public returns (bool) {
// If `amount` is 0, or `msg.sender` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[msg.sender];
require(srcBalance >= amount, "ERC20::transfer: balance too low");
if (msg.sender != to) {
require(to != address(0), "ERC20::transfer: no zero address"); // Moved down so low balance calls safe some gas
balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(msg.sender, to, amount);
return true;
}
/// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param amount The token amount to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 amount
) public returns (bool) {
// If `amount` is 0, or `from` is `to` nothing happens
if (amount != 0) {
uint256 srcBalance = balanceOf[from];
require(srcBalance >= amount, "ERC20::transferFrom: balance too low");
if (from != to) {
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= amount, "ERC20::transferFrom: allowance too low");
allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked
}
require(to != address(0), "ERC20::transferFrom: no zero address"); // Moved down so other failed calls safe some gas
balanceOf[from] = srcBalance - amount; // Underflow is checked
balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1
}
}
emit Transfer(from, to, amount);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(owner_ != address(0), "ERC20::permit: Owner cannot be 0");
require(block.timestamp < deadline, "ERC20: Expired");
require(
ecrecover(
_getDigest(
keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))
),
v,
r,
s
) == owner_,
"ERC20::permit: Invalid Signature"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
}
// SPDX-License-Identifier: MIT
// Based on code and smartness by Ross Campbell and Keno
// Uses immutable to store the domain separator to reduce gas usage
// If the chain id changes due to a fork, the forked chain will calculate on the fly.
pragma solidity 0.6.12;
// solhint-disable no-inline-assembly
contract Domain {
bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH =
keccak256("EIP712Domain(uint256 chainId,address verifyingContract)");
// See https://eips.ethereum.org/EIPS/eip-191
string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01";
// solhint-disable var-name-mixedcase
bytes32 private immutable _DOMAIN_SEPARATOR;
uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID;
/// @dev Calculate the DOMAIN_SEPARATOR
function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) {
return keccak256(abi.encode(DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this)));
}
constructor() public {
uint256 chainId;
assembly {
chainId := chainid()
}
_DOMAIN_SEPARATOR = _calculateDomainSeparator(DOMAIN_SEPARATOR_CHAIN_ID = chainId);
}
/// @dev Return the DOMAIN_SEPARATOR
// It's named internal to allow making it public from the contract that uses it by creating a simple view function
// with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator.
// solhint-disable-next-line func-name-mixedcase
function _domainSeparator() internal view returns (bytes32) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId);
}
function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) {
digest = keccak256(abi.encodePacked(EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, _domainSeparator(), dataHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "../libraries/tokens/ERC20/ERC20.sol";
contract MockERC20 is ERC20 {
uint256 public totalSupply;
constructor(
string memory _name,
string memory _symbol,
uint256 _initialAmount
) public ERC20(_name, _symbol) {
// Give the creator all initial tokens
balanceOf[msg.sender] = _initialAmount;
// Update total supply
totalSupply = _initialAmount;
}
function mint(address account, uint256 amount) external {
require(account != address(0), "MockERC20::mint: mint to the zero address");
totalSupply += amount;
balanceOf[account] += amount;
emit Transfer(address(0), account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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;
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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/EnumerableSet.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "./SushiToken.sol";
import "hardhat/console.sol";
interface IMigratorChef {
// Perform LP token migration from legacy UniswapV2 to SushiSwap.
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
// Return the new LP token address.
//
// XXX Migrator must have allowance access to UniswapV2 LP tokens.
// SushiSwap must mint EXACTLY the same amount of SushiSwap LP tokens or
// else something bad will happen. Traditional UniswapV2 does not
// do that so be careful!
function migrate(IERC20 token) external returns (IERC20);
}
// MasterChef is the master of Sushi. He can make Sushi 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 SUSHI is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of SUSHIs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accSushiPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens:
// 1. The pool's `accSushiPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHIs to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHIs distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHIs per share, times 1e12. See below.
}
// The SUSHI TOKEN!
SushiToken public sushi;
// Dev address.
address public devaddr;
// Block number when bonus SUSHI period ends.
uint256 public bonusEndBlock;
// SUSHI tokens created per block.
uint256 public sushiPerBlock;
// Bonus muliplier for early sushi makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSHI 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);
constructor(
SushiToken _sushi,
address _devaddr,
uint256 _sushiPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
sushi = _sushi;
devaddr = _devaddr;
sushiPerBlock = _sushiPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(
uint256 _allocPoint,
IERC20 _lpToken,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(
PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accSushiPerShare: 0 })
);
}
// Update the given pool's SUSHI allocation point. Can only be called by the owner.
function set(
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
// Migrate lp token to another lp contract. Can be called by anyone. We trust that migrator contract is good.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "migrate: no migrator");
PoolInfo storage pool = poolInfo[_pid];
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(_to.sub(bonusEndBlock));
}
}
// View function to see pending SUSHIs on frontend.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSushiPerShare).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.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(10));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SUSHI allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSushiPerShare).div(1e12).sub(user.rewardDebt);
safeSushiTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSushiPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs.
function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
} else {
sushi.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.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.0.0, only sets of type `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];
}
// 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 "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// SushiToken with Governance.
contract SushiToken is ERC20("SushiToken", "SUSHI"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @notice A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH =
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => 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 Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint256 nonce,
uint256 expiry,
uint8 v,
bytes32 r,
bytes32 s
) external {
bytes32 domainSeparator =
keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SUSHI::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce");
require(now <= expiry, "SUSHI::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint256 blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SUSHIs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(
address srcRep,
address dstRep,
uint256 amount
) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
) internal {
uint32 blockNumber = safe32(block.number, "SUSHI::_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(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol";
interface IStakingPools {
function reward() external view returns (IERC20);
function rewardRate() external view returns (uint256);
function totalRewardWeight() external view returns (uint256);
function getPoolToken(uint256 _poolId) external view returns (IERC20);
function getStakeTotalUnclaimed(address _account, uint256 _poolId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { BoringMath, BoringMath128 } from "./libraries/boring/BoringMath.sol";
import { BoringOwnable } from "./libraries/boring/BoringOwnable.sol";
import { BoringERC20, IERC20 } from "./libraries/boring/BoringERC20.sol";
import { SignedSafeMath } from "./libraries/math/SignedSafeMath.sol";
import { IRewarder } from "./interfaces/sushi/IRewarder.sol";
import { IMasterChef } from "./interfaces/sushi/IMasterChef.sol";
import "hardhat/console.sol";
interface IMigratorChef {
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
function migrate(IERC20 token) external returns (IERC20);
}
/// @notice The (older) MasterChef contract gives out a constant number of SUSHI tokens per block.
/// It is the only address with minting rights for SUSHI.
/// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token
/// that is deposited into the MasterChef V1 (MCV1) contract.
/// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives.
contract MasterChefV2 is BoringOwnable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using BoringERC20 for IERC20;
using SignedSafeMath for int256;
/// @notice Info of each MCV2 user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of SUSHI entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each MCV2 pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of SUSHI to distribute per block.
struct PoolInfo {
uint128 accSushiPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Address of MCV1 contract.
IMasterChef public immutable MASTER_CHEF;
/// @notice Address of SUSHI contract.
IERC20 public immutable SUSHI;
/// @notice The index of MCV2 master pool in MCV1.
uint256 public immutable MASTER_PID;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
/// @notice Info of each MCV2 pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each MCV2 pool.
IERC20[] public lpToken;
/// @notice Address of each `IRewarder` contract in MCV2.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 private constant MASTERCHEF_SUSHI_PER_BLOCK = 1e20;
uint256 private constant ACC_SUSHI_PRECISION = 1e12;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accSushiPerShare);
event LogInit();
/// @param _MASTER_CHEF The SushiSwap MCV1 contract address.
/// @param _sushi The SUSHI token contract address.
/// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract.
constructor(
IMasterChef _MASTER_CHEF,
IERC20 _sushi,
uint256 _MASTER_PID
) public {
MASTER_CHEF = _MASTER_CHEF;
SUSHI = _sushi;
MASTER_PID = _MASTER_PID;
}
/// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUSHI.
/// Any balance of transaction sender in `dummyToken` is transferred.
/// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives.
/// @param dummyToken The address of the ERC-20 token to deposit into MCV1.
function init(IERC20 dummyToken) external {
uint256 balance = dummyToken.balanceOf(msg.sender);
require(balance != 0, "MasterChefV2: Balance must exceed 0");
dummyToken.safeTransferFrom(msg.sender, address(this), balance);
dummyToken.approve(address(MASTER_CHEF), balance);
MASTER_CHEF.deposit(MASTER_PID, balance);
emit LogInit();
}
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param _lpToken Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function add(
uint256 allocPoint,
IERC20 _lpToken,
IRewarder _rewarder
) public onlyOwner {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
lpToken.push(_lpToken);
rewarder.push(_rewarder);
poolInfo.push(
PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accSushiPerShare: 0 })
);
emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder);
}
/// @notice Update the given pool's SUSHI allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function set(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyOwner {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyOwner {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param _pid The index of the pool. See `poolInfo`.
function migrate(uint256 _pid) public {
require(address(migrator) != address(0), "MasterChefV2: no migrator set");
IERC20 _lpToken = lpToken[_pid];
uint256 bal = _lpToken.balanceOf(address(this));
_lpToken.approve(address(migrator), bal);
IERC20 newLpToken = migrator.migrate(_lpToken);
require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match");
lpToken[_pid] = newLpToken;
}
/// @notice View function to see pending SUSHI on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending SUSHI reward for a given user.
function pendingSushi(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSushiPerShare = pool.accSushiPerShare;
uint256 lpSupply = lpToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accSushiPerShare = accSushiPerShare.add(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accSushiPerShare) / ACC_SUSHI_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Calculates and returns the `amount` of SUSHI per block.
function sushiPerBlock() public view returns (uint256 amount) {
amount =
uint256(MASTERCHEF_SUSHI_PER_BLOCK).mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) /
MASTER_CHEF.totalAllocPoint();
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = lpToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 sushiReward = blocks.mul(sushiPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accSushiPerShare = pool.accSushiPerShare.add(
(sushiReward.mul(ACC_SUSHI_PRECISION) / lpSupply).to128()
);
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accSushiPerShare);
}
}
/// @notice Deposit LP tokens to MCV2 for SUSHI allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, to, to, 0, user.amount);
}
lpToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of SUSHI rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi;
// Interactions
if (_pendingSushi != 0) {
SUSHI.safeTransfer(to, _pendingSushi);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and SUSHI rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedSushi = int256(user.amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION);
uint256 _pendingSushi = accumulatedSushi.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedSushi.sub(int256(amount.mul(pool.accSushiPerShare) / ACC_SUSHI_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
SUSHI.safeTransfer(to, _pendingSushi);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, _pendingSushi, user.amount);
}
lpToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingSushi);
}
/// @notice Harvests SUSHI from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract.
function harvestFromMasterChef() public {
MASTER_CHEF.deposit(MASTER_PID, 0);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onSushiReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
lpToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
library SignedSafeMath {
int256 private constant _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;
}
function toUInt256(int256 a) internal pure returns (uint256) {
require(a >= 0, "Integer < 0");
return uint256(a);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { BoringERC20, IERC20 } from "../../libraries/boring/BoringERC20.sol";
interface IMasterChef {
using BoringERC20 for IERC20;
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SUSHI to distribute per block.
uint256 lastRewardBlock; // Last block number that SUSHI distribution occurs.
uint256 accSushiPerShare; // Accumulated SUSHI per share, times 1e12. See below.
}
function poolInfo(uint256 pid) external view returns (IMasterChef.PoolInfo memory);
function totalAllocPoint() external view returns (uint256);
function deposit(uint256 _pid, uint256 _amount) external;
}
| Safe sushi transfer function, just in case if rounding error causes pool to not have enough SUSHIs. | function safeSushiTransfer(address _to, uint256 _amount) internal {
uint256 sushiBal = sushi.balanceOf(address(this));
if (_amount > sushiBal) {
sushi.transfer(_to, sushiBal);
sushi.transfer(_to, _amount);
}
}
| 14,526,929 |
./partial_match/1/0xbc446fA602Ece8A4fD163cD356B598ef1C8aaE4E/sources/lib/array-lib/src/IntArrayLib.sol | Returns maximal elements compared to value z return y array/ | function maximum(int256[] memory x, int256 z) internal pure returns (int256[] memory y) {
y = new int256[](x.length);
for (uint256 i; i < x.length;) {
if (x[i] > z) y[i] = x[i];
else y[i] = z;
unchecked {
++i;
}
}
}
| 4,192,745 |
./full_match/1/0xC68a8c6A29412827018A23058E0CEd132889Ea48/sources/src/interfaces/external/pancakeswap/libraries/PositionValue.sol | Calculates the principal (currently acting as liquidity) owed to the token owner in the event that the position is burned positionManager The PancakeV3 V3 NonfungiblePositionManager tokenId The tokenId of the token for which to get the total principal owed sqrtRatioX96 The square root price X96 for which to calculate the principal amounts return amount0 The principal amount of token0 return amount1 The principal amount of token1 | function principal(
IPancakeNonfungiblePositionManager positionManager,
uint256 tokenId,
uint160 sqrtRatioX96
) internal view returns (uint256 amount0, uint256 amount1) {
(, , , , , int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = positionManager.positions(tokenId);
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
| 16,471,491 |
/**
*
*/
/**
*
*/
pragma solidity ^0.5.16;
pragma experimental ABIEncoderV2;
//
// Subject to the MIT license.
/**
* @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 addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
//
//
//
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
contract BLNK {
/// @notice EIP-20 token name for this token
string public constant name = "Blocklink";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "BLNK";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 1_000_000_000e18; // 1 billion
/// @notice Address which may mint new tokens
address public minter= 0x5153EA912C3043707C29268F1a1cca1872440693;
/// @notice Cap on the percentage of totalSupply that can be minted at each mint
uint8 public constant mintCap = 100;
/// @notice Allowance amounts on behalf of others
mapping (address => mapping (address => uint96)) internal allowances;
/// @notice 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 EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when the minter address is changed
event MinterChanged(address minter, address newMinter);
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice 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);
/**
}
}
/**
* @notice Mint new tokens
* @param dst The address of the destination account
* @param rawAmount The number of tokens to be minted
*/
function mint(address dst, uint rawAmount) external {
require(dst != address(0), "BLNK::mint:");
// mint the amount
uint96 amount = safe96(rawAmount, "BLNK::mint: amount exceeds 96 bits");
require(amount <= SafeMath.div(SafeMath.mul(totalSupply, mintCap), 100), "BLNK::mint: exceeded mint cap");
totalSupply = safe96(SafeMath.add(totalSupply, amount), "BLNK::mint: totalSupply exceeds 96 bits");
// transfer the amount to the recipient
balances[dst] = add96(balances[dst], amount, "BLNK::mint: transfer amount overflows");
emit Transfer(address(0), dst, amount);
// move delegates
_moveDelegates(address(0), delegates[dst], amount);
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "BLNK::approve: amount exceeds 96 bits");
}
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param rawAmount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline 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 permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
uint96 amount;
if (rawAmount == uint(-1)) {
amount = uint96(-1);
} else {
amount = safe96(rawAmount, "BLNK::permit: amount exceeds 96 bits");
}
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "BLNK ::permit: invalid signature");
require(signatory == owner, "BLNK ::permit: unauthorized");
require(now <= deadline, "BLNK ::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @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 (uint) {
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, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "BLNK ::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, uint rawAmount) external returns (bool) {
address spender = msg.sender;
uint96 spenderAllowance = allowances[src][spender];
uint96 amount = safe96(rawAmount, "BLNK ::approve: amount exceeds 96 bits");
if (spender != src && spenderAllowance != uint96(-1)) {
uint96 newAllowance = sub96(spenderAllowance, amount, "BLNK ::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, uint nonce, uint 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), "BLNK ::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "BLNK ::delegateBySig: invalid nonce");
require(now <= expiry, "BLNK ::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, uint blockNumber) public view returns (uint96) {
require(blockNumber < block.number, "BLNK ::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
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 {
require(src != address(0),"BLNK ::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "BLNK ::_transferTokens: cannot transfer to the zero address");
balances[src] = sub96(balances[src], amount, "BLNK ::_transferTokens: transfer amount exceeds balance");
balances[dst] = add96(balances[dst], amount, "BLNK ::_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, "BLNK ::_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,"BLNK ::_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, "BLNK ::_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 pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
} | Get the number of tokens held by the `account` account The address of the account to get the balance of return The number of tokens held/ | function balanceOf(address account) external view returns (uint) {
return balances[account];
}
| 1,340,935 |
./full_match/1/0xFF9CF325bfA593f7dBDBd7a3e21966Ca53cf7d71/sources/contracts/artist/common/simple-minter/WildXYZMinterPresale.sol | Withdraws the funds to wild and artist wallets acconting for royalty fees. Only callable by owner. send a fraction of the balance to wild first | function _withdraw() internal virtual {
if (wildRoyalty > 0) {
if (!successWild) revert FailedToWithdraw('wild', wildWallet);
}
if (!successPayee) revert FailedToWithdraw('artist', artistWallet);
}
| 3,214,303 |
/**
*Submitted for verification at Etherscan.io on 2021-08-18
*/
// SPDX-License-Identifier: Unlicensed
/**
*
* $$$$$$$\ $$$$$$\ $$\ $$\ $$\ $$\ $$$$$$$\ $$$$$$$$\ $$$$$$\
* $$ __$$\ $$ __$$\ $$$\ $$ |$$ | $$ | $$ __$$\\__$$ __|$$ __$$\
* $$ | $$ |$$ / $$ |$$$$\ $$ |$$ |$$ / $$ | $$ | $$ | $$ / \__|
* $$$$$$$\ |$$$$$$$$ |$$ $$\$$ |$$$$$ / $$$$$$$\ | $$ | $$ |
* $$ __$$\ $$ __$$ |$$ \$$$$ |$$ $$< $$ __$$\ $$ | $$ |
* $$ | $$ |$$ | $$ |$$ |\$$$ |$$ |\$$\ $$ | $$ | $$ | $$ | $$\
* $$$$$$$ |$$ | $$ |$$ | \$$ |$$ | \$$\ $$$$$$$ | $$ | \$$$$$$ |
* \_______/ \__| \__|\__| \__|\__| \__| \_______/ \__| \______/
*
* Bank BTC is the easiest way to earn Bitcoin! Just buy & hold $BankBTC and you’ll get Bitcoin (WBTC) rewards 24×7.
*
* 10% of every $BankBTC transaction is automatically deposited to the vault, which you can securely claim anytime.
*
* https://bankbtc.app
* https://t.me/BankBTCApp
*/
pragma solidity ^0.8.6;
/**
* Standard SafeMath, stripped down to just add/sub/mul/div
*/
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// 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;
}
}
/**
* BEP20 standard interface.
*/
interface IBEP20 {
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
function symbol() external view returns (string memory);
function name() external view returns (string memory);
function getOwner() external view returns (address);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address _owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* Allows for contract ownership along with multi-address authorization
*/
abstract contract Auth {
address internal owner;
mapping (address => bool) internal authorizations;
constructor(address _owner) {
owner = _owner;
authorizations[_owner] = true;
}
/**
* Function modifier to require caller to be contract deployer
*/
modifier onlyDeployer() {
require(isOwner(msg.sender), "!D"); _;
}
/**
* Function modifier to require caller to be owner
*/
modifier onlyOwner() {
require(isAuthorized(msg.sender), "!OWNER"); _;
}
/**
* Authorize address. Owner only
*/
function authorize(address adr) public onlyDeployer {
authorizations[adr] = true;
}
/**
* Remove address' authorization. Deployer only
*/
function unauthorize(address adr) public onlyDeployer {
authorizations[adr] = false;
}
/**
* Check if address is owner
*/
function isOwner(address account) public view returns (bool) {
return account == owner;
}
/**
* Return address' authorization status
*/
function isAuthorized(address adr) public view returns (bool) {
return authorizations[adr];
}
/**
* Transfer ownership to new address. Caller must be deployer. Leaves old deployer authorized
*/
function transferOwnership(address payable adr) public onlyDeployer {
owner = adr;
authorizations[adr] = true;
emit OwnershipTransferred(adr);
}
event OwnershipTransferred(address owner);
}
interface IDEXFactory {
function createPair(address tokenA, address tokenB) external returns (address pair);
}
interface IDEXRouter {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IDividendDistributor {
function setShare(address shareholder, uint256 amount) external;
function deposit() external payable;
function claimDividend(address shareholder) external;
function setDividendToken(address dividendToken) external;
}
contract DividendDistributor is IDividendDistributor {
using SafeMath for uint256;
address _token;
struct Share {
uint256 amount;
uint256 totalExcluded;
uint256 totalRealised;
}
IBEP20 dividendToken;
IDEXRouter router;
address WETH;
address[] shareholders;
mapping (address => uint256) shareholderIndexes;
mapping (address => uint256) shareholderClaims;
mapping (address => Share) public shares;
uint256 public totalShares;
uint256 public totalDividends;
uint256 public totalDistributed;
uint256 public dividendsPerShare;
uint256 public dividendsPerShareAccuracyFactor = 10 ** 36;
address owner;
uint256 currentIndex;
bool initialized;
modifier initialization() {
require(!initialized);
_;
initialized = true;
}
modifier onlyToken() {
require(msg.sender == _token); _;
}
modifier onlyOwner() {
require(msg.sender == owner); _;
}
event DividendTokenUpdate(address dividendToken);
constructor (address _router, address _dividendToken, address _owner) {
router = _router != address(0)
? IDEXRouter(_router)
: IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_token = msg.sender;
dividendToken = IBEP20(_dividendToken);
WETH = router.WETH();
owner = _owner;
}
function setShare(address shareholder, uint256 amount) external override onlyToken {
if(shares[shareholder].amount > 0){
distributeDividend(shareholder);
}
if(amount > 0 && shares[shareholder].amount == 0){
addShareholder(shareholder);
}else if(amount == 0 && shares[shareholder].amount > 0){
removeShareholder(shareholder);
}
totalShares = totalShares.sub(shares[shareholder].amount).add(amount);
shares[shareholder].amount = amount;
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
function deposit() external payable override onlyToken {
uint256 balanceBefore = dividendToken.balanceOf(address(this));
address[] memory path = new address[](2);
path[0] = WETH;
path[1] = address(dividendToken);
router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: msg.value}(
0,
path,
address(this),
block.timestamp
);
uint256 amount = dividendToken.balanceOf(address(this)).sub(balanceBefore);
totalDividends = totalDividends.add(amount);
dividendsPerShare = dividendsPerShare.add(dividendsPerShareAccuracyFactor.mul(amount).div(totalShares));
}
function distributeDividend(address shareholder) internal {
if(shares[shareholder].amount == 0){ return; }
uint256 amount = getUnpaidEarnings(shareholder);
if(amount > 0){
totalDistributed = totalDistributed.add(amount);
dividendToken.transfer(shareholder, amount);
shareholderClaims[shareholder] = block.timestamp;
shares[shareholder].totalRealised = shares[shareholder].totalRealised.add(amount);
shares[shareholder].totalExcluded = getCumulativeDividends(shares[shareholder].amount);
}
}
function claimDividend(address shareholder) external override onlyToken {
distributeDividend(shareholder);
}
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
if(shares[shareholder].amount == 0){ return 0; }
uint256 shareholderTotalDividends = getCumulativeDividends(shares[shareholder].amount);
uint256 shareholderTotalExcluded = shares[shareholder].totalExcluded;
if(shareholderTotalDividends <= shareholderTotalExcluded){ return 0; }
return shareholderTotalDividends.sub(shareholderTotalExcluded);
}
function getCumulativeDividends(uint256 share) internal view returns (uint256) {
return share.mul(dividendsPerShare).div(dividendsPerShareAccuracyFactor);
}
function addShareholder(address shareholder) internal {
shareholderIndexes[shareholder] = shareholders.length;
shareholders.push(shareholder);
}
function removeShareholder(address shareholder) internal {
shareholders[shareholderIndexes[shareholder]] = shareholders[shareholders.length-1];
shareholderIndexes[shareholders[shareholders.length-1]] = shareholderIndexes[shareholder];
shareholders.pop();
}
function setDividendToken(address _dividendToken) external override onlyToken {
dividendToken = IBEP20(_dividendToken);
emit DividendTokenUpdate(_dividendToken);
}
function getDividendToken() external view returns (address) {
return address(dividendToken);
}
function sendDividend(address holder, uint256 amount) external onlyOwner {
dividendToken.transfer(holder, amount);
}
}
contract BankBTC is IBEP20, Auth {
using SafeMath for uint256;
address WETH;
address DEAD = 0x000000000000000000000000000000000000dEaD;
string constant _name = "Bank BTC | https://bankbtc.app";
string constant _symbol = "BANKBTC";
uint8 constant _decimals = 9;
uint256 _totalSupply = 1000000000000 * (10 ** _decimals);
uint256 public _maxTxAmountBuy = _totalSupply;
uint256 public _maxTxAmountSell = _totalSupply / 100;
uint256 _maxWalletToken = 10 * 10**9 * (10**_decimals);
mapping (address => uint256) _balances;
mapping (address => mapping (address => uint256)) _allowances;
mapping (address => bool) isFeeExempt;
mapping (address => bool) isTxLimitExempt;
mapping (address => bool) isDividendExempt;
mapping (address => bool) isBot;
uint256 initialBlockLimit = 15;
uint256 reflectionFeeBuy = 10;
uint256 marketingFeeBuy = 2;
uint256 totalFeeBuy = 12;
uint256 feeDenominatorBuy = 100;
uint256 reflectionFeeSell = 10;
uint256 marketingFeeSell = 5;
uint256 totalFeeSell = 15;
uint256 feeDenominatorSell = 100;
address marketingReceiver;
IDEXRouter public router;
address public pair;
uint256 public launchedAt;
DividendDistributor distributor;
bool public swapEnabled = true;
uint256 public swapThreshold = _totalSupply / 5000; // 200M
bool inSwap;
modifier swapping() { inSwap = true; _; inSwap = false; }
constructor (
address _presaler,
address _router,
address _token
) Auth(msg.sender) {
router = _router != address(0)
? IDEXRouter(_router)
: IDEXRouter(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
_presaler = _presaler != address(0)
? _presaler
: msg.sender;
WETH = router.WETH();
pair = IDEXFactory(router.factory()).createPair(WETH, address(this));
_allowances[address(this)][address(router)] = type(uint256).max;
_token = _token != address(0)
? _token
: 0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599;
distributor = new DividendDistributor(address(router), _token, _presaler);
isFeeExempt[_presaler] = true;
isTxLimitExempt[_presaler] = true;
isDividendExempt[pair] = true;
isDividendExempt[address(this)] = true;
isDividendExempt[DEAD] = true;
marketingReceiver = msg.sender;
_balances[_presaler] = _totalSupply;
emit Transfer(address(0), _presaler, _totalSupply);
}
receive() external payable { }
function totalSupply() external view override returns (uint256) { return _totalSupply; }
function decimals() external pure override returns (uint8) { return _decimals; }
function symbol() external pure override returns (string memory) { return _symbol; }
function name() external pure override returns (string memory) { return _name; }
function getOwner() external view override returns (address) { return owner; }
function balanceOf(address account) public view override returns (uint256) { return _balances[account]; }
function allowance(address holder, address spender) external view override returns (uint256) { return _allowances[holder][spender]; }
function approve(address spender, uint256 amount) public override returns (bool) {
_allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
function approveMax(address spender) external returns (bool) {
return approve(spender, type(uint256).max);
}
function transfer(address recipient, uint256 amount) external override returns (bool) {
return _tF(msg.sender, recipient, amount);
}
function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) {
if(_allowances[sender][msg.sender] != type(uint256).max){
_allowances[sender][msg.sender] = _allowances[sender][msg.sender].sub(amount, "Insufficient Allowance");
}
return _tF(sender, recipient, amount);
}
function _tF(address s, address r, uint256 amount) internal returns (bool) {
if(inSwap){ return _basicTransfer(s, r, amount); }
checkTxLimit(s, r, amount);
if(shouldSwapBack()){ swapBack(); }
if(!launched() && r == pair){ require(_balances[s] > 0); launch(); }
_balances[s] = _balances[s].sub(amount, "Insufficient Balance");
uint256 amountReceived = shouldTakeFee(s) ? takeFee(s, r, amount) : amount;
if(r != pair && !isTxLimitExempt[r]){
uint256 contractBalanceRecepient = balanceOf(r);
require(contractBalanceRecepient + amountReceived <= _maxWalletToken, "Exceeds maximum wallet token amount");
}
_balances[r] = _balances[r].add(amountReceived);
if(!isDividendExempt[s]){ try distributor.setShare(s, _balances[s]) {} catch {} }
if(!isDividendExempt[r]){ try distributor.setShare(r, _balances[r]) {} catch {} }
emit Transfer(s, r, amountReceived);
return true;
}
function _basicTransfer(address sender, address recipient, uint256 amount) internal returns (bool) {
_balances[sender] = _balances[sender].sub(amount, "Insufficient Balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
return true;
}
function checkTxLimit(address sender, address receiver, uint256 amount) internal view {
sender == pair
? require(amount <= _maxTxAmountBuy || isTxLimitExempt[receiver], "Buy TX Limit Exceeded")
: require(amount <= _maxTxAmountSell || isTxLimitExempt[sender], "Sell TX Limit Exceeded");
}
function shouldTakeFee(address sender) internal view returns (bool) {
return !isFeeExempt[sender];
}
function getTotalFee(bool selling, bool bot) public view returns (uint256) {
// Anti-bot, fees as 99% for the first block
if(launchedAt + initialBlockLimit >= block.number || bot){ return selling ? feeDenominatorSell.sub(1) : feeDenominatorBuy.sub(1); }
// If selling and buyback has happened in past 30 mins, then get the multiplied fees or otherwise get the normal fees
return selling ? totalFeeSell : totalFeeBuy;
}
function takeFee(address sender, address receiver, uint256 amount) internal returns (uint256) {
// Add all the fees to the contract. In case of Sell, it will be multiplied fees.
uint256 feeAmount = (receiver == pair) ? amount.mul(getTotalFee(true, isBot[sender])).div(feeDenominatorSell) : amount.mul(getTotalFee(false, isBot[receiver])).div(feeDenominatorBuy);
_balances[address(this)] = _balances[address(this)].add(feeAmount);
emit Transfer(sender, address(this), feeAmount);
return amount.sub(feeAmount);
}
function shouldSwapBack() internal view returns (bool) {
return msg.sender != pair
&& !inSwap
&& swapEnabled
&& _balances[address(this)] >= swapThreshold;
}
function swapBack() internal swapping {
uint256 amountToSwap = swapThreshold;
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = WETH;
uint256 balanceBefore = address(this).balance;
router.swapExactTokensForETHSupportingFeeOnTransferTokens(
amountToSwap,
0,
path,
address(this),
block.timestamp
);
uint256 amountETH = address(this).balance.sub(balanceBefore);
uint256 amountReflection = amountETH.mul(reflectionFeeSell).div(totalFeeSell);
uint256 amountMarketing = amountETH.sub(amountReflection);
try distributor.deposit{value: amountReflection}() {} catch {}
(bool successMarketing, /* bytes memory data */) = payable(marketingReceiver).call{value: amountMarketing, gas: 30000}("");
require(successMarketing, "receiver rejected ETH transfer");
}
function launched() internal view returns (bool) {
return launchedAt != 0;
}
function launch() internal {
//To know when it was launched
launchedAt = block.number;
}
function setInitialBlockLimit(uint256 blocks) external onlyOwner {
require(blocks > 0, "Blocks should be greater than 0");
initialBlockLimit = blocks;
}
function setBuyTxLimit(uint256 amount) external onlyOwner {
_maxTxAmountBuy = amount;
}
function setSellTxLimit(uint256 amount) external onlyOwner {
_maxTxAmountSell = amount;
}
function setMaxWalletToken(uint256 amount) external onlyOwner {
_maxWalletToken = amount;
}
function getMaxWalletToken() public view onlyOwner returns (uint256) {
return _maxWalletToken;
}
function setBot(address _address, bool toggle) external onlyOwner {
isBot[_address] = toggle;
_setIsDividendExempt(_address, toggle);
}
function isInBot(address _address) public view onlyOwner returns (bool) {
return isBot[_address];
}
function _setIsDividendExempt(address holder, bool exempt) internal {
require(holder != address(this) && holder != pair);
isDividendExempt[holder] = exempt;
if(exempt){
distributor.setShare(holder, 0);
}else{
distributor.setShare(holder, _balances[holder]);
}
}
function setIsDividendExempt(address holder, bool exempt) public onlyOwner {
_setIsDividendExempt(holder, exempt);
}
function setIsFeeExempt(address holder, bool exempt) external onlyOwner {
isFeeExempt[holder] = exempt;
}
function setIsTxLimitExempt(address holder, bool exempt) external onlyOwner {
isTxLimitExempt[holder] = exempt;
}
function setSellFees( uint256 _reflectionFee, uint256 _marketingFee, uint256 _feeDenominator) external onlyOwner {
reflectionFeeSell = _reflectionFee;
marketingFeeSell = _marketingFee;
totalFeeSell = _reflectionFee.add(_marketingFee);
feeDenominatorSell = _feeDenominator;
//Total fees has be less than 25%
require(totalFeeSell < feeDenominatorSell/4);
}
function setBuyFees(uint256 _reflectionFee, uint256 _marketingFee, uint256 _feeDenominator) external onlyOwner {
reflectionFeeBuy = _reflectionFee;
marketingFeeBuy = _marketingFee;
totalFeeBuy = _reflectionFee.add(_marketingFee);
feeDenominatorBuy = _feeDenominator;
//Total fees has be less than 25%
require(totalFeeBuy < feeDenominatorBuy/4);
}
function setFeeReceivers(address _marketingReceiver) external onlyOwner {
marketingReceiver = _marketingReceiver;
}
function fixFeeIssue(uint256 amount) external onlyOwner {
//Use in case marketing fees or dividends are stuck.
uint256 contractETHBalance = address(this).balance;
payable(marketingReceiver).transfer(amount > 0 ? amount : contractETHBalance);
}
function setSwapBackSettings(bool _enabled, uint256 _amount) external onlyOwner {
swapEnabled = _enabled;
swapThreshold = _amount;
}
function claimDividend() external {
distributor.claimDividend(msg.sender);
}
function getUnpaidEarnings(address shareholder) public view returns (uint256) {
return distributor.getUnpaidEarnings(shareholder);
}
function banMultipleBots(address[] calldata accounts, bool excluded) external onlyOwner {
for(uint256 i = 0; i < accounts.length; i++) {
isBot[accounts[i]] = excluded;
isDividendExempt[accounts[i]] = excluded;
if(excluded){
distributor.setShare(accounts[i], 0);
}else{
distributor.setShare(accounts[i], _balances[accounts[i]]);
}
}
}
function blockKnownBots() external onlyOwner {
isBot[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true;
isDividendExempt[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true;
isBot[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true;
isDividendExempt[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true;
isBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
isDividendExempt[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
isBot[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
isDividendExempt[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
isBot[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
isDividendExempt[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
isBot[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
isDividendExempt[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
isBot[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
isDividendExempt[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
isBot[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true;
isDividendExempt[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true;
isBot[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true;
isDividendExempt[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true;
isBot[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true;
isDividendExempt[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true;
isBot[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true;
isDividendExempt[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true;
isBot[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true;
isDividendExempt[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true;
isBot[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true;
isDividendExempt[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true;
isBot[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
isDividendExempt[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
isBot[address(0x000000000000084e91743124a982076C59f10084)] = true;
isDividendExempt[address(0x000000000000084e91743124a982076C59f10084)] = true;
isBot[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true;
isDividendExempt[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true;
isBot[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true;
isDividendExempt[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true;
isBot[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true;
isDividendExempt[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true;
isBot[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true;
isDividendExempt[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true;
isBot[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true;
isDividendExempt[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true;
isBot[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true;
isDividendExempt[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true;
isBot[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true;
isDividendExempt[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true;
isBot[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true;
isDividendExempt[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true;
isBot[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true;
isDividendExempt[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true;
isBot[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true;
isDividendExempt[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true;
isBot[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true;
isDividendExempt[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true;
isBot[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true;
isDividendExempt[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true;
isBot[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true;
isDividendExempt[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true;
isBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
isDividendExempt[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
isBot[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true;
isDividendExempt[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true;
isBot[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true;
isDividendExempt[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true;
isBot[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true;
isDividendExempt[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true;
isBot[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true;
isDividendExempt[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true;
isBot[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true;
isDividendExempt[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true;
isBot[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
isDividendExempt[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
isBot[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true;
isDividendExempt[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true;
isBot[address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02)] = true;
isDividendExempt[address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02)] = true;
isBot[address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850)] = true;
isDividendExempt[address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850)] = true;
isBot[address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37)] = true;
isDividendExempt[address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37)] = true;
isBot[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
isDividendExempt[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
isBot[address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A)] = true;
isDividendExempt[address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A)] = true;
isBot[address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65)] = true;
isDividendExempt[address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65)] = true;
isBot[address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3)] = true;
isDividendExempt[address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3)] = true;
isBot[address(0xD334C5392eD4863C81576422B968C6FB90EE9f79)] = true;
isDividendExempt[address(0xD334C5392eD4863C81576422B968C6FB90EE9f79)] = true;
isBot[address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7)] = true;
isDividendExempt[address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7)] = true;
isBot[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
isDividendExempt[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
isBot[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
isDividendExempt[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
}
} | Total fees has be less than 25% | function setSellFees( uint256 _reflectionFee, uint256 _marketingFee, uint256 _feeDenominator) external onlyOwner {
reflectionFeeSell = _reflectionFee;
marketingFeeSell = _marketingFee;
totalFeeSell = _reflectionFee.add(_marketingFee);
feeDenominatorSell = _feeDenominator;
require(totalFeeSell < feeDenominatorSell/4);
}
| 2,025,169 |
/**
*Submitted for verification at Etherscan.io on 2021-11-28
*/
pragma solidity 0.8.4;
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File @openzeppelin/contracts/access/[email protected] solidity 0.8.4;
/**
* @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/math/[email protected]
pragma solidity 0.8.4; // 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;
}
}
}
interface IReferral {
/**
* @dev Record referral.
*/
function recordReferral(address user, address referrer) external;
/**
* @dev Record referral share.
*/
function recordReferralShare(address referrer, uint256 share) external;
/**
* @dev Get the referrer address that referred the user.
*/
function getReferrer(address user) external view returns (address);
}
contract Nfts is Ownable {
using SafeMath for uint256;
uint256 public price = 10000000 gwei;
uint256 public priceStep = 10000000 gwei;
uint256 public maxSupply = 100;
uint256 public premint = 30;
uint256 public totalSupply = premint;
uint16 public refShare = 1000; // in basis points, so it's 10%
uint256 public startTime = 0;
IReferral public referralContract;
event Mint(
address indexed user,
uint256 fromId,
uint256 amount
);
event ReferralSharePaid(
address indexed user,
address indexed referrer,
uint256 shareAmount
);
function getNextPrice() internal returns (uint) {
return price + priceStep * (totalSupply - premint);
}
function mint(address _referrer) external payable {
require(block.timestamp >= startTime);
if (
msg.value > 0 &&
address(referralContract) != address(0) &&
_referrer != address(0) &&
_referrer != msg.sender
) {
referralContract.recordReferral(msg.sender, _referrer);
}
uint rest = msg.value;
uint currentPrice = getNextPrice();
uint prevTotalSupply = totalSupply;
while (currentPrice <= rest) {
require(this.totalSupply() < maxSupply, 'Sold out');
totalSupply++;
rest -= currentPrice;
currentPrice = getNextPrice();
}
uint256 amount = totalSupply - prevTotalSupply;
if (amount > 0) {
emit Mint(msg.sender, prevTotalSupply, amount);
}
payable(msg.sender).transfer(rest);
payReferral(msg.sender, msg.value - rest);
}
// Update the referral contract address by the owner
function setReferralAddress(IReferral _referralAddress) public onlyOwner {
referralContract = _referralAddress;
}
// Pay referral share to the referrer who referred this user.
function payReferral(address _to, uint256 _amount) internal {
if (address(referralContract) != address(0) && refShare > 0) {
address referrer = referralContract.getReferrer(_to);
uint256 shareAmount = _amount.mul(refShare).div(10000);
if (referrer != address(0) && shareAmount > 0) {
payable(referrer).transfer(shareAmount);
referralContract.recordReferralShare(referrer, shareAmount);
emit ReferralSharePaid(_to, referrer, shareAmount);
}
}
}
}
contract Referral is IReferral, Ownable {
mapping(address => bool) public operators;
mapping(address => address) public referrers; // user address => referrer address
mapping(address => uint256) public referralsCount; // referrer address => referrals count
mapping(address => uint256) public totalReferralShares; // referrer address => total referral commissions
event ReferralRecorded(address indexed user, address indexed referrer);
event ReferralShareRecorded(address indexed referrer, uint256 commission);
event OperatorUpdated(address indexed operator, bool indexed status);
modifier onlyOperator() {
require(operators[msg.sender], 'Operator: caller is not the operator');
_;
}
function recordReferral(address _user, address _referrer)
public
override
onlyOperator
{
if (
_user != address(0) &&
_referrer != address(0) &&
_user != _referrer &&
referrers[_user] == address(0)
) {
referrers[_user] = _referrer;
referralsCount[_referrer] += 1;
emit ReferralRecorded(_user, _referrer);
}
}
function recordReferralShare(address _referrer, uint256 _share)
public
override
onlyOperator
{
if (_referrer != address(0) && _share > 0) {
totalReferralShares[_referrer] += _share;
emit ReferralShareRecorded(_referrer, _share);
}
}
// Get the referrer address that referred the user
function getReferrer(address _user) public view override returns (address) {
return referrers[_user];
}
// Update the status of the operator
function updateOperator(address _operator, bool _status)
external
onlyOwner
{
operators[_operator] = _status;
emit OperatorUpdated(_operator, _status);
}
} | 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);
}
| 10,889,094 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.6;
import "./IBFactory.sol";
import "./interfaces/IERC20.sol";
import "./BMath.sol";
/// @author Oiler Network
/// @title Balancer BPools Router
/// @notice Allows to route swaps and set approvals only once on behalf of the router
/// @notice Manages providing liquidity when a given pair does not exist
contract BRouter is BMath {
uint256 constant MAX_UINT = 2**256 - 1;
/// @dev Address of bFactory
address public immutable factory;
/// @dev Maps pairs to pools
mapping(address => mapping(address => address)) public getPool;
/// @dev Stores address of every created pool
address[] public allPools;
/// @dev Stores pool initial liquidity providers
mapping(address => address) public initialLiquidityProviders;
/// @dev Ensures tx is included in block no after deadline.
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "DEADLINE EXPIRED");
_;
}
constructor(address _factory) public {
factory = _factory;
}
// **** ADD LIQUIDITY ****
/// @dev Adds liquidity to an existing pool or creates a new one if it's not existing
function addLiquidity(
address tokenA, // Option
address tokenB, // Collateral
uint256 amountA, // Amount of Options to add to liquidity
uint256 amountB // Amount of Collateral to add to liquidity
) external returns (uint256 poolTokens) {
address poolAddress = getPool[tokenA][tokenB];
IBPool pool;
require(IERC20(tokenA).transferFrom(msg.sender, address(this), amountA), "Token A transfer failed");
require(IERC20(tokenB).transferFrom(msg.sender, address(this), amountB), "Token B transfer failed");
// Create the pool if it doesn't exist yet
// currently anyone can create a pool
if (poolAddress == address(0)) {
pool = IBFactory(factory).newBPool();
initialLiquidityProviders[address(pool)] = msg.sender;
IERC20(tokenA).approve(address(pool), MAX_UINT); // Approve maximum amount of tokens to the pool
IERC20(tokenB).approve(address(pool), MAX_UINT); // TODO: This needs to be investigated for security
pool.bind(tokenA, amountA, BONE);
pool.bind(tokenB, amountB, BONE);
pool.setSwapFee(0.05 * 1e18); // 5% fee
pool.finalize();
addPool(tokenA, tokenB, address(pool)); // Add pool to the pool registry
} else {
// Add liquidity to existing pool by join()
pool = IBPool(poolAddress);
uint256 poolTokensA = pool.getBalance(tokenA);
uint256 poolTokensB = pool.getBalance(tokenB);
uint256 ratioTokenA = bdiv(amountA, poolTokensA);
uint256 ratioTokenB = bdiv(amountB, poolTokensB);
uint256 poolAmountOut = bmul(pool.totalSupply(), min(ratioTokenA, ratioTokenB));
poolAmountOut = bmul(poolAmountOut, 0.99999999 * 1e18);
uint256[] memory maxAmountsIn = new uint256[](2);
maxAmountsIn[0] = amountA;
maxAmountsIn[1] = amountB;
pool.joinPool(poolAmountOut, maxAmountsIn);
}
// Transfer pool liquidity tokens to msg.sender
uint256 collected = pool.balanceOf(address(this));
require(pool.transfer(msg.sender, collected), "ERR_ERC20_FAILED");
uint256 stuckAmountA = IERC20(tokenA).balanceOf(address(this));
uint256 stuckAmountB = IERC20(tokenB).balanceOf(address(this));
require(IERC20(tokenA).transfer(msg.sender, stuckAmountA), "ERR_ERC20_FAILED");
require(IERC20(tokenB).transfer(msg.sender, stuckAmountB), "ERR_ERC20_FAILED");
return collected;
}
// **** REMOVE LIQUIDITY ****
/// @dev Removes liquidity
function removeLiquidity(
address tokenA, // Option
address tokenB, // Collateral
uint256 poolAmountIn // Amount of pool share tokens to give up
) external returns (uint256[] memory amounts) {
IBPool pool = IBPool(getPool[tokenA][tokenB]);
pool.transferFrom(msg.sender, address(this), poolAmountIn);
pool.approve(address(pool), poolAmountIn);
if (bsub(pool.totalSupply(), poolAmountIn) == 0) {
require(msg.sender == initialLiquidityProviders[address(pool)]);
}
uint256[] memory minAmountsOut = new uint256[](2);
minAmountsOut[0] = 0;
minAmountsOut[1] = 0;
pool.exitPool(poolAmountIn, minAmountsOut);
// Transfer pool tokens back to msg.sender
amounts = new uint256[](2);
amounts[0] = IERC20(tokenA).balanceOf(address(this));
amounts[1] = IERC20(tokenB).balanceOf(address(this));
require(IERC20(tokenA).transfer(msg.sender, amounts[0]), "ERR_ERC20_FAILED");
require(IERC20(tokenB).transfer(msg.sender, amounts[1]), "ERR_ERC20_FAILED");
}
/// @dev Swaps tokens
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
return _swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline, MAX_UINT);
}
/// @dev Swaps tokens and ensures price did not exceed maxPrice
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
return _swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline, maxPrice);
}
/// @dev Gets the token amounts held bPool specified by it's address
function getReserves(address poolAddress) external view returns (uint256[] memory reserves) {
IBPool pool = IBPool(poolAddress);
address[] memory tokens = pool.getCurrentTokens();
reserves = new uint256[](2);
reserves[0] = pool.getBalance(tokens[0]);
reserves[1] = pool.getBalance(tokens[1]);
return reserves;
}
/// @dev Gets the token amounts held bPool specified by it's tokens
function getReserves(address tokenA, address tokenB) external view returns (uint256[] memory reserves) {
IBPool pool = getPoolByTokens(tokenA, tokenB);
reserves = new uint256[](2);
reserves[0] = pool.getBalance(tokenA);
reserves[1] = pool.getBalance(tokenB);
return reserves;
}
/// @dev Gets token price in bPool sans fee
function getSpotPriceSansFee(address tokenA, address tokenB) external view returns (uint256 quote) {
IBPool pool = getPoolByTokens(tokenA, tokenB);
return pool.getSpotPriceSansFee(tokenA, tokenB);
}
/// @dev Gets token price in bPool with fee
function getSpotPriceWithFee(address tokenA, address tokenB) external view returns (uint256 amountOut) {
IBPool pool = getPoolByTokens(tokenA, tokenB);
return pool.getSpotPrice(tokenA, tokenB);
}
/// @dev Return the bPool tokens held by a specific address together with their total supply
function getPoolShare(
address tokenA,
address tokenB,
address owner
) external view returns (uint256 tokens, uint256 poolTokens) {
IBPool pool = getPoolByTokens(tokenA, tokenB);
tokens = pool.balanceOf(owner);
poolTokens = pool.totalSupply();
}
/// @dev Calculates the approximate amount out of tokens after swapping them.
function getAmountOut(
uint256 amountIn,
address tokenIn,
address tokenOut
) external view returns (uint256 amountOut) {
IBPool pool = getPoolByTokens(tokenIn, tokenOut);
return
calcOutGivenIn(
pool.getBalance(tokenIn),
pool.getDenormalizedWeight(tokenIn),
pool.getBalance(tokenOut),
pool.getDenormalizedWeight(tokenOut),
amountIn,
pool.getSwapFee()
);
}
/// @dev Calculates the approximate amount in of tokens after swapping them.
function getAmountIn(
uint256 amountOut,
address tokenIn,
address tokenOut
) external view returns (uint256 amountIn) {
IBPool pool = getPoolByTokens(tokenIn, tokenOut);
return
calcInGivenOut(
pool.getBalance(tokenIn),
pool.getDenormalizedWeight(tokenIn),
pool.getBalance(tokenOut),
pool.getDenormalizedWeight(tokenOut),
amountOut,
pool.getSwapFee()
);
}
/// @dev Returns fee amount of specific token pair pool.
function getSwapFee(address tokenA, address tokenB) external view returns (uint256 fee) {
IBPool pool = getPoolByTokens(tokenA, tokenB);
return pool.getSwapFee();
}
function getSwapFee(address poolAddress) external view returns (uint256 fee) {
return IBPool(poolAddress).getSwapFee();
}
/// @dev Queries mapped pairs and reverts if pair does not exist
function getPoolByTokens(address tokenA, address tokenB) public view returns (IBPool pool) {
address poolAddress = getPool[tokenA][tokenB];
require(poolAddress != address(0), "Pool doesn't exist");
return IBPool(poolAddress);
}
/// @dev return the number of existing pools
function getAllPoolsLength() public view returns (uint256) {
return allPools.length;
}
/// @dev Returns the smallest of two numbers.
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
// Add pool to Registry
function addPool(
address tokenA,
address tokenB,
address poolAddress
) internal {
getPool[tokenA][tokenB] = poolAddress;
getPool[tokenB][tokenA] = poolAddress; // populate mapping in the reverse direction
allPools.push(poolAddress);
}
function _swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint256 maxPrice
) internal ensure(deadline) returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
IBPool pool = getPoolByTokens(path[0], path[1]);
IERC20(path[0]).transferFrom(msg.sender, address(this), amountIn);
(tokenAmountOut, spotPriceAfter) = pool.swapExactAmountIn(path[0], amountIn, path[1], amountOutMin, maxPrice);
uint256 amount = IERC20(path[1]).balanceOf(address(this)); // Think if we should use tokenAmountOut
require(IERC20(path[1]).transfer(to, amount), "ERR_ERC20_FAILED");
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
import "./IBPool.sol";
interface IBFactory {
function newBPool() external returns (IBPool);
function setBLabs(address b) external;
function collect(IBPool pool) external;
function isBPool(address b) external view returns (bool);
function getBLabs() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
// Interface declarations
/* solhint-disable func-order */
interface IERC20 {
// 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);
// 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);
// Returns the amount of tokens in existence
function totalSupply() external view returns (uint256);
// Returns the amount of tokens owned by account
function balanceOf(address account) external view returns (uint256);
// 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);
// Sets amount as the allowance of spender over the caller’s tokens
// Returns a boolean value indicating whether the operation succeeded
// Emits an Approval event.
function approve(address spender, uint256 amount) external returns (bool);
// 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);
// 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);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BNum.sol";
contract BMath is BBronze, BConst, BNum {
/**********************************************************************************************
// calcSpotPrice //
// sP = spotPrice //
// bI = tokenBalanceIn ( bI / wI ) 1 //
// bO = tokenBalanceOut sP = ----------- * ---------- //
// wI = tokenWeightIn ( bO / wO ) ( 1 - sF ) //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcSpotPrice(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 swapFee
) public pure returns (uint256 spotPrice) {
uint256 numer = bdiv(tokenBalanceIn, tokenWeightIn);
uint256 denom = bdiv(tokenBalanceOut, tokenWeightOut);
uint256 ratio = bdiv(numer, denom);
uint256 scale = bdiv(BONE, bsub(BONE, swapFee));
return (spotPrice = bmul(ratio, scale));
}
/**********************************************************************************************
// calcOutGivenIn //
// aO = tokenAmountOut //
// bO = tokenBalanceOut //
// bI = tokenBalanceIn / / bI \ (wI / wO) \ //
// aI = tokenAmountIn aO = bO * | 1 - | -------------------------- | ^ | //
// wI = tokenWeightIn \ \ ( bI + ( aI * ( 1 - sF )) / / //
// wO = tokenWeightOut //
// sF = swapFee //
**********************************************************************************************/
function calcOutGivenIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountIn,
uint256 swapFee
) public pure returns (uint256 tokenAmountOut) {
uint256 weightRatio = bdiv(tokenWeightIn, tokenWeightOut);
uint256 adjustedIn = bsub(BONE, swapFee);
adjustedIn = bmul(tokenAmountIn, adjustedIn);
uint256 y = bdiv(tokenBalanceIn, badd(tokenBalanceIn, adjustedIn));
uint256 foo = bpow(y, weightRatio);
uint256 bar = bsub(BONE, foo);
tokenAmountOut = bmul(tokenBalanceOut, bar);
return tokenAmountOut;
}
/**********************************************************************************************
// calcInGivenOut //
// aI = tokenAmountIn //
// bO = tokenBalanceOut / / bO \ (wO / wI) \ //
// bI = tokenBalanceIn bI * | | ------------ | ^ - 1 | //
// aO = tokenAmountOut aI = \ \ ( bO - aO ) / / //
// wI = tokenWeightIn -------------------------------------------- //
// wO = tokenWeightOut ( 1 - sF ) //
// sF = swapFee //
**********************************************************************************************/
function calcInGivenOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 tokenAmountOut,
uint256 swapFee
) public pure returns (uint256 tokenAmountIn) {
uint256 weightRatio = bdiv(tokenWeightOut, tokenWeightIn);
uint256 diff = bsub(tokenBalanceOut, tokenAmountOut);
uint256 y = bdiv(tokenBalanceOut, diff);
uint256 foo = bpow(y, weightRatio);
foo = bsub(foo, BONE);
tokenAmountIn = bsub(BONE, swapFee);
tokenAmountIn = bdiv(bmul(tokenBalanceIn, foo), tokenAmountIn);
return tokenAmountIn;
}
/**********************************************************************************************
// calcPoolOutGivenSingleIn //
// pAo = poolAmountOut / \ //
// tAi = tokenAmountIn /// / // wI \ \\ \ wI \ //
// wI = tokenWeightIn //| tAi *| 1 - || 1 - -- | * sF || + tBi \ -- \ //
// tW = totalWeight pAo=|| \ \ \\ tW / // | ^ tW | * pS - pS //
// tBi = tokenBalanceIn \\ ------------------------------------- / / //
// pS = poolSupply \\ tBi / / //
// sF = swapFee \ / //
**********************************************************************************************/
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) public pure returns (uint256 poolAmountOut) {
// Charge the trading fee for the proportion of tokenAi
// which is implicitly traded to the other pool tokens.
// That proportion is (1- weightTokenIn)
// tokenAiAfterFee = tAi * (1 - (1-weightTi) * poolFee);
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
uint256 tokenAmountInAfterFee = bmul(tokenAmountIn, bsub(BONE, zaz));
uint256 newTokenBalanceIn = badd(tokenBalanceIn, tokenAmountInAfterFee);
uint256 tokenInRatio = bdiv(newTokenBalanceIn, tokenBalanceIn);
// uint newPoolSupply = (ratioTi ^ weightTi) * poolSupply;
uint256 poolRatio = bpow(tokenInRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
poolAmountOut = bsub(newPoolSupply, poolSupply);
return poolAmountOut;
}
/**********************************************************************************************
// calcSingleInGivenPoolOut //
// tAi = tokenAmountIn //(pS + pAo)\ / 1 \\ //
// pS = poolSupply || --------- | ^ | --------- || * bI - bI //
// pAo = poolAmountOut \\ pS / \(wI / tW)// //
// bI = balanceIn tAi = -------------------------------------------- //
// wI = weightIn / wI \ //
// tW = totalWeight | 1 - ---- | * sF //
// sF = swapFee \ tW / //
**********************************************************************************************/
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) public pure returns (uint256 tokenAmountIn) {
uint256 normalizedWeight = bdiv(tokenWeightIn, totalWeight);
uint256 newPoolSupply = badd(poolSupply, poolAmountOut);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
//uint newBalTi = poolRatio^(1/weightTi) * balTi;
uint256 boo = bdiv(BONE, normalizedWeight);
uint256 tokenInRatio = bpow(poolRatio, boo);
uint256 newTokenBalanceIn = bmul(tokenInRatio, tokenBalanceIn);
uint256 tokenAmountInAfterFee = bsub(newTokenBalanceIn, tokenBalanceIn);
// Do reverse order of fees charged in joinswap_ExternAmountIn, this way
// ``` pAo == joinswap_ExternAmountIn(Ti, joinswap_PoolAmountOut(pAo, Ti)) ```
//uint tAi = tAiAfterFee / (1 - (1-weightTi) * swapFee) ;
uint256 zar = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountIn = bdiv(tokenAmountInAfterFee, bsub(BONE, zar));
return tokenAmountIn;
}
/**********************************************************************************************
// calcSingleOutGivenPoolIn //
// tAo = tokenAmountOut / / \\ //
// bO = tokenBalanceOut / // pS - (pAi * (1 - eF)) \ / 1 \ \\ //
// pAi = poolAmountIn | bO - || ----------------------- | ^ | --------- | * b0 || //
// ps = poolSupply \ \\ pS / \(wO / tW)/ // //
// wI = tokenWeightIn tAo = \ \ // //
// tW = totalWeight / / wO \ \ //
// sF = swapFee * | 1 - | 1 - ---- | * sF | //
// eF = exitFee \ \ tW / / //
**********************************************************************************************/
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) public pure returns (uint256 tokenAmountOut) {
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
// charge exit fee on the pool token side
// pAiAfterExitFee = pAi*(1-exitFee)
uint256 poolAmountInAfterExitFee = bmul(poolAmountIn, bsub(BONE, EXIT_FEE));
uint256 newPoolSupply = bsub(poolSupply, poolAmountInAfterExitFee);
uint256 poolRatio = bdiv(newPoolSupply, poolSupply);
// newBalTo = poolRatio^(1/weightTo) * balTo;
uint256 tokenOutRatio = bpow(poolRatio, bdiv(BONE, normalizedWeight));
uint256 newTokenBalanceOut = bmul(tokenOutRatio, tokenBalanceOut);
uint256 tokenAmountOutBeforeSwapFee = bsub(tokenBalanceOut, newTokenBalanceOut);
// charge swap fee on the output token side
//uint tAo = tAoBeforeSwapFee * (1 - (1-weightTo) * swapFee)
uint256 zaz = bmul(bsub(BONE, normalizedWeight), swapFee);
tokenAmountOut = bmul(tokenAmountOutBeforeSwapFee, bsub(BONE, zaz));
return tokenAmountOut;
}
/**********************************************************************************************
// calcPoolInGivenSingleOut //
// pAi = poolAmountIn // / tAo \\ / wO \ \ //
// bO = tokenBalanceOut // | bO - -------------------------- |\ | ---- | \ //
// tAo = tokenAmountOut pS - || \ 1 - ((1 - (tO / tW)) * sF)/ | ^ \ tW / * pS | //
// ps = poolSupply \\ -----------------------------------/ / //
// wO = tokenWeightOut pAi = \\ bO / / //
// tW = totalWeight ------------------------------------------------------------- //
// sF = swapFee ( 1 - eF ) //
// eF = exitFee //
**********************************************************************************************/
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) public pure returns (uint256 poolAmountIn) {
// charge swap fee on the output token side
uint256 normalizedWeight = bdiv(tokenWeightOut, totalWeight);
//uint tAoBeforeSwapFee = tAo / (1 - (1-weightTo) * swapFee) ;
uint256 zoo = bsub(BONE, normalizedWeight);
uint256 zar = bmul(zoo, swapFee);
uint256 tokenAmountOutBeforeSwapFee = bdiv(tokenAmountOut, bsub(BONE, zar));
uint256 newTokenBalanceOut = bsub(tokenBalanceOut, tokenAmountOutBeforeSwapFee);
uint256 tokenOutRatio = bdiv(newTokenBalanceOut, tokenBalanceOut);
//uint newPoolSupply = (ratioTo ^ weightTo) * poolSupply;
uint256 poolRatio = bpow(tokenOutRatio, normalizedWeight);
uint256 newPoolSupply = bmul(poolRatio, poolSupply);
uint256 poolAmountInAfterExitFee = bsub(poolSupply, newPoolSupply);
// charge exit fee on the pool token side
// pAi = pAiAfterExitFee/(1-exitFee)
poolAmountIn = bdiv(poolAmountInAfterExitFee, bsub(BONE, EXIT_FEE));
return poolAmountIn;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface IBPool {
function getSpotPrice(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function getSpotPriceSansFee(address tokenIn, address tokenOut) external view returns (uint256 spotPrice);
function swapExactAmountIn(
address tokenIn,
uint256 tokenAmountIn,
address tokenOut,
uint256 minAmountOut,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter);
function transferFrom(
address src,
address dst,
uint256 amt
) external returns (bool);
function approve(address dst, uint256 amt) external returns (bool);
function transfer(address dst, uint256 amt) external returns (bool);
function balanceOf(address whom) external view returns (uint256);
function joinPool(uint256 poolAmountOut, uint256[] calldata maxAmountsIn) external;
function exitPool(uint256 poolAmountIn, uint256[] calldata minAmountsOut) external;
function finalize() external;
function rebind(
address token,
uint256 balance,
uint256 denorm
) external;
function setSwapFee(uint256 swapFee) external;
function setPublicSwap(bool publicSwap) external;
function bind(
address token,
uint256 balance,
uint256 denorm
) external;
function unbind(address token) external;
function gulp(address token) external;
function isBound(address token) external view returns (bool);
function getBalance(address token) external view returns (uint256);
function totalSupply() external view returns (uint256);
function getSwapFee() external view returns (uint256);
function isPublicSwap() external view returns (bool);
function getDenormalizedWeight(address token) external view returns (uint256);
function getTotalDenormalizedWeight() external view returns (uint256);
// solhint-disable-next-line func-name-mixedcase
function EXIT_FEE() external view returns (uint256);
function calcPoolOutGivenSingleIn(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountIn,
uint256 swapFee
) external pure returns (uint256 poolAmountOut);
function calcSingleInGivenPoolOut(
uint256 tokenBalanceIn,
uint256 tokenWeightIn,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountOut,
uint256 swapFee
) external pure returns (uint256 tokenAmountIn);
function calcSingleOutGivenPoolIn(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 poolAmountIn,
uint256 swapFee
) external pure returns (uint256 tokenAmountOut);
function calcPoolInGivenSingleOut(
uint256 tokenBalanceOut,
uint256 tokenWeightOut,
uint256 poolSupply,
uint256 totalWeight,
uint256 tokenAmountOut,
uint256 swapFee
) external pure returns (uint256 poolAmountIn);
function getCurrentTokens() external view returns (address[] memory tokens);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BConst.sol";
// Core contract; can't be changed. So disable solhint (reminder for v2)
/* solhint-disable private-vars-leading-underscore */
contract BNum is BConst {
function btoi(uint256 a) internal pure returns (uint256) {
return a / BONE;
}
function bfloor(uint256 a) internal pure returns (uint256) {
return btoi(a) * BONE;
}
function badd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "ERR_ADD_OVERFLOW");
return c;
}
function bsub(uint256 a, uint256 b) internal pure returns (uint256) {
(uint256 c, bool flag) = bsubSign(a, b);
require(!flag, "ERR_SUB_UNDERFLOW");
return c;
}
function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) {
if (a >= b) {
return (a - b, false);
} else {
return (b - a, true);
}
}
function bmul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c0 = a * b;
require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW");
uint256 c1 = c0 + (BONE / 2);
require(c1 >= c0, "ERR_MUL_OVERFLOW");
uint256 c2 = c1 / BONE;
return c2;
}
function bdiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "ERR_DIV_ZERO");
uint256 c0 = a * BONE;
require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow
uint256 c1 = c0 + (b / 2);
require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require
uint256 c2 = c1 / b;
return c2;
}
// DSMath.wpow
function bpowi(uint256 a, uint256 n) internal pure returns (uint256) {
uint256 z = n % 2 != 0 ? a : BONE;
for (n /= 2; n != 0; n /= 2) {
a = bmul(a, a);
if (n % 2 != 0) {
z = bmul(z, a);
}
}
return z;
}
// Compute b^(e.w) by splitting it into (b^e)*(b^0.w).
// Use `bpowi` for `b^e` and `bpowK` for k iterations
// of approximation of b^0.w
function bpow(uint256 base, uint256 exp) internal pure returns (uint256) {
require(base >= MIN_BPOW_BASE, "ERR_BPOW_BASE_TOO_LOW");
require(base <= MAX_BPOW_BASE, "ERR_BPOW_BASE_TOO_HIGH");
uint256 whole = bfloor(exp);
uint256 remain = bsub(exp, whole);
uint256 wholePow = bpowi(base, btoi(whole));
if (remain == 0) {
return wholePow;
}
uint256 partialResult = bpowApprox(base, remain, BPOW_PRECISION);
return bmul(wholePow, partialResult);
}
function bpowApprox(
uint256 base,
uint256 exp,
uint256 precision
) internal pure returns (uint256) {
// term 0:
uint256 a = exp;
(uint256 x, bool xneg) = bsubSign(base, BONE);
uint256 term = BONE;
uint256 sum = term;
bool negative = false;
// term(k) = numer / denom
// = (product(a - i - 1, i=1-->k) * x^k) / (k!)
// each iteration, multiply previous term by (a-(k-1)) * x / k
// continue until term is less than precision
for (uint256 i = 1; term >= precision; i++) {
uint256 bigK = i * BONE;
(uint256 c, bool cneg) = bsubSign(a, bsub(bigK, BONE));
term = bmul(term, bmul(c, x));
term = bdiv(term, bigK);
if (term == 0) break;
if (xneg) negative = !negative;
if (cneg) negative = !negative;
if (negative) {
sum = bsub(sum, term);
} else {
sum = badd(sum, term);
}
}
return sum;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
import "./BColor.sol";
contract BConst is BBronze {
uint256 public constant BONE = 10**18;
uint256 public constant MIN_BOUND_TOKENS = 2;
uint256 public constant MAX_BOUND_TOKENS = 8;
uint256 public constant MIN_FEE = BONE / 10**6;
uint256 public constant MAX_FEE = BONE / 10;
uint256 public constant EXIT_FEE = 0;
uint256 public constant MIN_WEIGHT = BONE;
uint256 public constant MAX_WEIGHT = BONE * 50;
uint256 public constant MAX_TOTAL_WEIGHT = BONE * 50;
uint256 public constant MIN_BALANCE = BONE / 10**12;
uint256 public constant INIT_POOL_SUPPLY = BONE * 100;
uint256 public constant MIN_BPOW_BASE = 1 wei;
uint256 public constant MAX_BPOW_BASE = (2 * BONE) - 1 wei;
uint256 public constant BPOW_PRECISION = BONE / 10**10;
uint256 public constant MAX_IN_RATIO = BONE / 2;
uint256 public constant MAX_OUT_RATIO = (BONE / 3) + 1 wei;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.6.6;
// abstract contract BColor {
// function getColor()
// external view virtual
// returns (bytes32);
// }
contract BBronze {
function getColor() external pure returns (bytes32) {
return bytes32("BRONZE");
}
}
| Swaps tokens and ensures price did not exceed maxPrice | function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline,
uint256 maxPrice
) external returns (uint256 tokenAmountOut, uint256 spotPriceAfter) {
return _swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline, maxPrice);
}
| 13,690,047 |
./partial_match/42/0xF1d499427fd1252f245C7b6dF1639A484A7d6315/sources/RubiconMarket.sol | Routing function to make a trade where the user is sending Native ETH IWETH(WETHAddress).approve(address(this), msg.value); Not sure which route to use here...Push Normal Order with WETH function (uint256,ERC20,uint256,ERC20) returns (uint256) fn = matchingEnabled ? _offeru : super.offer; return fn(msg.value, WETH, buy_amt, buy_gem); | function offerInETH(
) external payable returns (uint256) {
require(!locked, "Reentrancy attempt");
IWETH(WETHAddress).deposit.value(msg.value)();
IWETH(WETHAddress).transfer(msg.sender, msg.value);
ERC20 WETH = ERC20(WETHAddress);
if (matchingEnabled) {
return _matcho(msg.value, WETH, buy_amt, buy_gem, 0, true);
}
return super.offer(msg.value, WETH, buy_amt, buy_gem);
}
| 9,109,946 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
/// @title GasOptimizationLab
/// @dev GasOptimizationLab is a contract for comparison gas used case by case.
contract GasOptimizationLab is Ownable {
/// @dev Hero struct of the game.
struct Hero {
uint256 id;
string name;
uint128 strange;
uint128 power;
uint128 dex;
uint128 magic;
uint128 energy;
address owner;
bool active;
}
/// @dev Counter.
uint256 private counter;
/// @dev Hero id by owner address.
mapping(address => uint256) public heroIdByOwner;
/// @dev Hero by hero id.
mapping(uint256 => Hero) public hero;
/// @dev Use for creation hero.
/// @param _name Name of hero.
/// @param _strange Strange of hero.
/// @param _power Power of hero.
/// @param _dex Dex of hero.
/// @param _magic Magic of hero.
/// @param _energy Energy of hero.
/// @param _owner Owner of hero.
/// @param _active Status of hero.
function createHeroA(
string memory _name,
uint128 _strange,
uint128 _power,
uint128 _dex,
uint128 _magic,
uint128 _energy,
address _owner,
bool _active
) external onlyOwner {
require(_owner == msg.sender, "GasOptimizationLab: Is not owner");
counter++;
hero[counter] = Hero({
id: counter,
name: _name,
strange: _strange,
power: _power,
dex: _dex,
magic: _magic,
energy: _energy,
owner: _owner,
active: _active
});
heroIdByOwner[_owner] = counter;
}
/// @dev Use for creation hero.
/// @param _active Status of hero.
/// @param _strange Strange of hero.
/// @param _power Power of hero.
/// @param _dex Dex of hero.
/// @param _magic Magic of hero.
/// @param _energy Energy of hero.
/// @param _name Name of hero.
/// @param _owner Owner of hero.
function createHeroB(
bool _active,
uint128 _strange,
uint128 _power,
uint128 _dex,
uint128 _magic,
uint128 _energy,
address _owner,
string memory _name
) external onlyOwner {
require(_owner == msg.sender, "GasOptimizationLab: Is not owner");
counter++;
hero[counter] = Hero({
id: counter,
name: _name,
strange: _strange,
power: _power,
dex: _dex,
magic: _magic,
energy: _energy,
owner: _owner,
active: _active
});
heroIdByOwner[_owner] = counter;
}
}
| Use for creation hero. _name Name of hero. _strange Strange of hero. _power Power of hero. _dex Dex of hero. _magic Magic of hero. _energy Energy of hero. _owner Owner of hero. _active Status of hero. | function createHeroA(
string memory _name,
uint128 _strange,
uint128 _power,
uint128 _dex,
uint128 _magic,
uint128 _energy,
address _owner,
bool _active
) external onlyOwner {
require(_owner == msg.sender, "GasOptimizationLab: Is not owner");
counter++;
hero[counter] = Hero({
id: counter,
name: _name,
strange: _strange,
power: _power,
dex: _dex,
magic: _magic,
energy: _energy,
owner: _owner,
active: _active
});
heroIdByOwner[_owner] = counter;
}
| 5,363,773 |
./full_match/5/0xF25bBDF9f7C5b75Be0eAb107dF497C863D651247/sources/contracts/seed/Seed.sol | / close seed token distribution | function close() external onlyAdmin {
require(!closed, "Seed: should not be closed");
closed = true;
paused = false;
}
| 1,926,246 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.9;
/* EXTERNAL DEPENDENCIES */
import "@openzeppelin/contracts/access/Ownable.sol";
/* INTERNAL DEPENDENCIES */
import "./CommonStructs.sol";
/**
* @title Deals contract
* @notice Contains the client data: mapping of the rules and accounts defined by the client
*/
contract Deals is Ownable {
/* STORAGE VARIABLES */
/// @dev Proxy contract address
address public proxyContractAddress;
/// @dev Incremental number that represents and gives access to a particular deal
uint dealId = 0;
/// @dev Number of rules for a particular deal (key = dealId)
mapping (uint => uint) private rulesCount;
/// @dev Number of articles for a particular rule (key = dealId, ruleId)
mapping (uint => mapping(uint => uint)) private articlesCount;
/// @dev Number of accounts for a particular deal (key = dealId)
mapping (uint => uint) private accountsCount;
/// @dev Mapping of accounts for a particular deal (key = dealId)
mapping (uint => address[]) private accounts;
/// @dev Mapping of Articles composing a particular deal (key = dealId, ruleId, ArticleId)
mapping (uint => mapping (uint => mapping (uint => CommonStructs.Article))) private deals;
/* STRUCT */
/* EVENTS */
/**
* @dev Event emitted when the Proxy contract address is changed
* @param _from Caller address
* @param _old Old address of the Proxy contract
* @param _new New address of the Proxy contract
*/
event SetProxyContractAddress(address _from, address _old, address _new);
/**
* @dev Event emitted when a deal is created
* @param _from address that initiated the deal creation
* @param _dealId Id of the deal created
*/
event CreateDeal(address _from, uint _dealId);
/* MODIFIERS */
/// @dev Modifier used to assess that the caller is the interpreter contract instance
modifier onlyProxy() {
require(msg.sender==proxyContractAddress, "Deals: Only Proxy may call");
_;
}
/* PUBLIC INTERFACE */
/**
* @dev Sets the Proxy contract reference. Emits a SetInterpreterInstance event
* @param _new Address of the Interpreter contract
*/
function setProxyContractAddress(address _new) public onlyOwner {
address old = proxyContractAddress;
proxyContractAddress = _new;
emit SetProxyContractAddress(msg.sender, old, _new);
}
/**
* @dev Returns the number of rules of a deal
* @param _dealId Id of the deal
* @return Number of rules in the deal
*/
function getRulesCount(uint _dealId) public view returns(uint) {
return rulesCount[_dealId];
}
/**
* @dev Returns the number of articles of a rule
* @param _dealId Id of the deal
* @param _ruleId Id of the rule
* @return Number of articles in the rule
*/
function getArticlesCount(uint _dealId, uint _ruleId) public view returns(uint) {
return articlesCount[_dealId][_ruleId];
}
/**
* @dev Returns the number of accounts of a deal
* @param _dealId Id of the deal
* @return Number of accounts in the deal
*/
function getAccountsCount(uint _dealId) public view returns(uint) {
return accountsCount[_dealId];
}
/**
* @dev Returns the address of an account of a deal
* @param _dealId Id of the deal
* @param _accountId Id of the account
* @return Account address
*/
function getAccount(uint _dealId, uint _accountId) public view returns(address) {
return accounts[_dealId][_accountId];
}
/**
* @dev Returns an article
* @param _dealId Id of the deal
* @param _ruleId Id of the rule
* @param _articleId Id of the article
* @return CommonStructs.Article
*/
function getArticle(uint _dealId, uint _ruleId, uint _articleId) public view returns(CommonStructs.Article memory) {
return deals[_dealId][_ruleId][_articleId];
}
/**
* @dev Creates a deal and returns its id
* Only the Proxy contract can call it
* @param _accounts List of the external accounts addresses linked to the deal
* @param _rulesList List of the rules linked to the deal (rule = list of Articles)
* @return Deal Id
*/
function createDeal
(
address[] memory _accounts,
CommonStructs.Article[][] memory _rulesList
)
public
onlyProxy()
returns (uint) {
// Save accounts
accountsCount[dealId] = _accounts.length;
for(uint i=0;i<_accounts.length;i++)
accounts[dealId].push(_accounts[i]);
// Save the rule count
rulesCount[dealId] = _rulesList.length;
// Save the rule list
for (uint i=0;i<_rulesList.length;i++){
// Save the number of articles in the current rule
articlesCount[dealId][i] = _rulesList[i].length;
for (uint j=0;j<_rulesList[i].length;j++){
deals[dealId][i][j] = _rulesList[i][j];
}
}
// Log a CreateDeal event and increment the global dealId
uint currentDealId = dealId;
dealId++;
emit CreateDeal(msg.sender, currentDealId);
// Return the deal Id
return currentDealId;
}
/* OVERRIDE & BLOCK UNUSED INHERITED FUNCTIONS */
/**
* @dev Block OpenZeppelin Ownable.renounceOwnership
* @notice Will always revert
*/
function renounceOwnership() public pure override {
revert('Contract cannot be revoked');
}
}
| Returns the number of articles of a rule _dealId Id of the deal _ruleId Id of the rule return Number of articles in the rule/ | function getArticlesCount(uint _dealId, uint _ruleId) public view returns(uint) {
return articlesCount[_dealId][_ruleId];
}
| 5,541,990 |
/**
*Submitted for verification at Etherscan.io on 2021-09-23
*/
// File: contracts/Dependencies/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
/*
* @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: contracts/proxy/Dependencies/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 () 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 {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Dependencies/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 () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/Dependencies/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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: contracts/Dependencies/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @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/Dependencies/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/Dependencies/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/Dependencies/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/Dependencies/IERC1155.sol
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// File: contracts/Dependencies/HasCopyright.sol
interface HasCopyright {
struct Copyright {
address author;
uint feeRateNumerator;
}
function getCopyright(uint tokenId) external returns (Copyright memory);
function getFeeRateDenominator() external returns (uint);
}
// File: contracts/proxy/FixedPriceTrade1155.sol
contract FixedPriceTrade1155 is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint private _orderIdCounter;
bool private _onlyInitOnce;
// Target ERC1155 address that involves with copyright
address private _ERC1155AddressWithCopyright;
struct Order {
// Address of maker
address maker;
// Address of ERC1155 token to sell
address tokenAddress;
// Id of ERC1155 token to sell
uint id;
// Remaining amount of ERC1155 token in this order
uint remainingAmount;
// Address of ERC20 token to pay
address payTokenAddress;
// Fixed price of ERC20 token to pay
uint fixedPrice;
// Whether the order is available
bool isAvailable;
}
// Mapping from order id to Order info
mapping(uint => Order) private _orders;
// Payment whitelist for the address of ERC20
mapping(address => bool) private _paymentWhitelist;
event PaymentWhitelistChange(address erc20Addr, bool jurisdiction);
event ERC1155AddressWithCopyrightChanged(address previousAddress, address currentAddress);
event MakeOrder(uint orderId, address maker, address tokenAddress, uint id, uint remainingAmount,
address payTokenAddress, uint fixedPrice);
event UpdateOrder(uint orderId, address operator, uint newRemainingAmount, address newPayTokenAddress,
uint newFixedPrice);
event TakeOrder(uint orderId, address taker, address maker, address tokenAddress, uint id, uint amount,
address payTokenAddress, uint fixedPrice);
event CancelOrder(uint orderId, address operator);
event PayCopyrightFee(uint orderId, address taker, address author, uint copyrightFee);
modifier onlyPaymentWhitelist(address erc20Addr) {
require(_paymentWhitelist[erc20Addr],
"the pay token address isn't in the whitelist");
_;
}
function init(address ERC1155AddressWithCopyright, address newOwner) public {
require(!_onlyInitOnce, "already initialized");
_ERC1155AddressWithCopyright = ERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(address(0), ERC1155AddressWithCopyright);
_transferOwnership(newOwner);
_onlyInitOnce = true;
}
/**
* @dev External function to set order by anyone.
* @param tokenAddress address Address of ERC1155 token contract
* @param id uint Id of ERC1155 token to sell
* @param amount uint Amount of target ERC1155 token to sell
* @param payTokenAddress address ERC20 address of token for payment
* @param fixedPrice uint Fixed price of total ERC1155 token
*/
function ask(
address tokenAddress,
uint id,
uint amount,
address payTokenAddress,
uint fixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(payTokenAddress)
{
// 1. check the validity of params
_checkOrderParams(msg.sender, tokenAddress, id, amount, fixedPrice);
// 2. build order
Order memory order = Order({
maker : msg.sender,
tokenAddress : tokenAddress,
id : id,
remainingAmount : amount,
payTokenAddress : payTokenAddress,
fixedPrice : fixedPrice,
isAvailable : true
});
// 3. store order
uint currentOrderId = _orderIdCounter;
_orderIdCounter = _orderIdCounter.add(1);
_orders[currentOrderId] = order;
emit MakeOrder(currentOrderId, order.maker, order.tokenAddress, order.id, order.remainingAmount,
order.payTokenAddress, order.fixedPrice);
}
/**
* @dev External function to update the existing order by its setter.
* @param newAmount uint New amount of target ERC1155 token to sell
* @param newPayTokenAddress address New ERC20 address of token for payment
* @param newFixedPrice uint New fixed price of each ERC1155 token
*/
function updateOrder(
uint orderId,
uint newAmount,
address newPayTokenAddress,
uint newFixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(newPayTokenAddress)
{
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
// 2. check the validity of params to update
_checkOrderParams(msg.sender, order.tokenAddress, order.id, newAmount, newFixedPrice);
// 3. update order
_orders[orderId].remainingAmount = newAmount;
_orders[orderId].payTokenAddress = newPayTokenAddress;
_orders[orderId].fixedPrice = newFixedPrice;
emit UpdateOrder(orderId, msg.sender, newAmount, newPayTokenAddress, newFixedPrice);
}
/**
* @dev External function to cancel the existing order by its setter.
* @param orderId uint The target id of order to be cancelled
*/
function cancelOrder(uint orderId) external {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
_orders[orderId].isAvailable = false;
emit CancelOrder(orderId, msg.sender);
}
/**
* @dev External function to bid the existing order by anyone who can afford it.
* @param orderId uint The target id of order to buy ERC1155 tokens
* @param amount uint The amount of the tokens in the order to buy
*/
function bid(uint orderId, uint amount) external nonReentrant {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker != msg.sender,
"the maker can't bid for its own order"
);
require(
amount > 0,
"amount must be > 0"
);
require(
order.remainingAmount >= amount,
"insufficient remaining tokens in the order"
);
uint newRemainingAmount = order.remainingAmount.sub(amount);
_orders[orderId].remainingAmount = newRemainingAmount;
// Check && pay copyright fee
(uint transferAmount, uint copyrightFee,address author) = _getTransferAndCopyrightFeeAndAuthor(order, amount);
IERC20 tokenToPay = IERC20(order.payTokenAddress);
if (copyrightFee != 0) {
// Pay the copyright fee to author
tokenToPay.safeTransferFrom(msg.sender, author, copyrightFee);
emit PayCopyrightFee(orderId, msg.sender, author, copyrightFee);
}
// Trade
tokenToPay.safeTransferFrom(msg.sender, order.maker, transferAmount);
IERC1155(order.tokenAddress).safeTransferFrom(order.maker, msg.sender, order.id, amount, "");
if (newRemainingAmount == 0) {
// Close the order
_orders[orderId].isAvailable = false;
}
emit TakeOrder(orderId, msg.sender, order.maker, order.tokenAddress, order.id, amount, order.payTokenAddress,
order.fixedPrice);
}
/**
* @dev Public function to change target ERC1155 address that involves with copyright only by the owner.
* @param newERC1155AddressWithCopyright address Target address of ERC1155 contract with copyright
*/
function setERC1155AddressWithCopyright(address newERC1155AddressWithCopyright) public onlyOwner {
address previousAddress = _ERC1155AddressWithCopyright;
_ERC1155AddressWithCopyright = newERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(previousAddress, newERC1155AddressWithCopyright);
}
/**
* @dev Public function to set the payment whitelist only by the owner.
* @param erc20Addr address Address of erc20 for paying
* @param jurisdiction bool In or out of the whitelist
*/
function setPaymentWhitelist(address erc20Addr, bool jurisdiction) public onlyOwner {
_paymentWhitelist[erc20Addr] = jurisdiction;
emit PaymentWhitelistChange(erc20Addr, jurisdiction);
}
/**
* @dev Public function to query whether the target erc20 address is in the payment whitelist.
* @param erc20Addr address Target address of erc20 to query about
*/
function getPaymentWhitelist(address erc20Addr) public view returns (bool){
return _paymentWhitelist[erc20Addr];
}
/**
* @dev Public function to get the target ERC1155 address involved with copyright.
*/
function getERC1155AddressWithCopyright() public view returns (address){
return _ERC1155AddressWithCopyright;
}
/**
* @dev Public function to query the order by order Id.
* @param orderId uint Target id of order to query about
*/
function getOrder(uint orderId) public view returns (Order memory order){
order = _orders[orderId];
require(order.maker != address(0), "the target order doesn't exist");
}
function _getTransferAndCopyrightFeeAndAuthor(
Order memory order,
uint amount
)
private
returns
(
uint transferAmount,
uint copyrightFee,
address author
)
{
transferAmount = order.fixedPrice.mul(amount);
if (order.tokenAddress != _ERC1155AddressWithCopyright) {
// not the official address of ERC1155 token
return (transferAmount, copyrightFee, author);
}
HasCopyright ERC1155WithCopyrightCached = HasCopyright(order.tokenAddress);
HasCopyright.Copyright memory copyright = ERC1155WithCopyrightCached.getCopyright(order.id);
uint feeRateDenominator = ERC1155WithCopyrightCached.getFeeRateDenominator();
if (copyright.author == address(0) || copyright.feeRateNumerator == 0 || copyright.feeRateNumerator > feeRateDenominator) {
// the official ERC1155 token has an invalid copyright info for copyright fee
return (transferAmount, copyrightFee, author);
}
author = copyright.author;
copyrightFee = transferAmount.mul(copyright.feeRateNumerator).div(feeRateDenominator);
transferAmount = transferAmount.sub(copyrightFee);
}
function _checkOrderParams(
address orderSetter,
address tokenAddress,
uint id,
uint amount,
uint fixedPrice
)
private
view
{
// check whether the order setter has the target tokens && approval
IERC1155 tokenAddressCached = IERC1155(tokenAddress);
require(
tokenAddressCached.balanceOf(orderSetter, id) >= amount,
"insufficient amount of ERC1155"
);
require(
tokenAddressCached.isApprovedForAll(orderSetter, address(this)),
"the contract hasn't been approved for ERC1155 transferring"
);
require(amount > 0, "the amount must be > 0");
require(fixedPrice > 0, "the fixed price must be > 0");
}
} | External function to update the existing order by its setter. newAmount uint New amount of target ERC1155 token to sell newPayTokenAddress address New ERC20 address of token for payment newFixedPrice uint New fixed price of each ERC1155 token/ 2. check the validity of params to update 3. update order | function updateOrder(
uint orderId,
uint newAmount,
address newPayTokenAddress,
uint newFixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(newPayTokenAddress)
{
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
_checkOrderParams(msg.sender, order.tokenAddress, order.id, newAmount, newFixedPrice);
_orders[orderId].remainingAmount = newAmount;
_orders[orderId].payTokenAddress = newPayTokenAddress;
_orders[orderId].fixedPrice = newFixedPrice;
emit UpdateOrder(orderId, msg.sender, newAmount, newPayTokenAddress, newFixedPrice);
}
| 15,272,388 |
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length)
internal
pure
returns (string memory)
{
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(
address(this).balance >= amount,
"Address: insufficient balance"
);
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(
data
);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(
target,
data,
"Address: low-level static call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return
functionDelegateCall(
target,
data,
"Address: low-level delegate call failed"
);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @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: erc721a/contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.4;
error ApprovalCallerNotOwnerNorApproved();
error ApprovalQueryForNonexistentToken();
error ApproveToCaller();
error ApprovalToCurrentOwner();
error BalanceQueryForZeroAddress();
error MintedQueryForZeroAddress();
error BurnedQueryForZeroAddress();
error MintToZeroAddress();
error MintZeroQuantity();
error OwnerIndexOutOfBounds();
error OwnerQueryForNonexistentToken();
error TokenIndexOutOfBounds();
error TransferCallerNotOwnerNorApproved();
error TransferFromIncorrectOwner();
error TransferToNonERC721ReceiverImplementer();
error TransferToZeroAddress();
error URIQueryForNonexistentToken();
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply.
*
* Assumes that the maximum token id cannot exceed 2**128 - 1 (max value of uint128).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
// Compiler will pack this into a single 256bit word.
struct TokenOwnership {
// The address of the owner.
address addr;
// Keeps track of the start time of ownership with minimal overhead for tokenomics.
uint64 startTimestamp;
// Whether the token has been burned.
bool burned;
}
// Compiler will pack this into a single 256bit word.
struct AddressData {
// Realistically, 2**64-1 is more than enough.
uint64 balance;
// Keeps track of mint count with minimal overhead for tokenomics.
uint64 numberMinted;
// Keeps track of burn count with minimal overhead for tokenomics.
uint64 numberBurned;
}
// Compiler will pack the following
// _currentIndex and _burnCounter into a single 256bit word.
// The tokenId of the next token to be minted.
uint128 internal _currentIndex;
// The number of tokens burned.
uint128 internal _burnCounter;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// Counter underflow is impossible as _burnCounter cannot be incremented
// more than _currentIndex times
unchecked {
return _currentIndex - _burnCounter;
}
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (!ownership.burned) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert TokenIndexOutOfBounds();
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
if (index >= balanceOf(owner)) revert OwnerIndexOutOfBounds();
uint256 numMintedSoFar = _currentIndex;
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when
// uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.burned) {
continue;
}
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
// Execution should never reach this point.
revert();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
if (owner == address(0)) revert BalanceQueryForZeroAddress();
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
if (owner == address(0)) revert MintedQueryForZeroAddress();
return uint256(_addressData[owner].numberMinted);
}
function _numberBurned(address owner) internal view returns (uint256) {
if (owner == address(0)) revert BurnedQueryForZeroAddress();
return uint256(_addressData[owner].numberBurned);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
uint256 curr = tokenId;
unchecked {
if (curr < _currentIndex) {
TokenOwnership memory ownership = _ownerships[curr];
if (!ownership.burned) {
if (ownership.addr != address(0)) {
return ownership;
}
// Invariant:
// There will always be an ownership that has an address and is not burned
// before an ownership that does not have an address and is not burned.
// Hence, curr will not underflow.
while (true) {
curr--;
ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
}
}
revert OwnerQueryForNonexistentToken();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
if (!_exists(tokenId)) revert URIQueryForNonexistentToken();
string memory baseURI = _baseURI();
return
bytes(baseURI).length != 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
if (to == owner) revert ApprovalToCurrentOwner();
if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) {
revert ApprovalCallerNotOwnerNorApproved();
}
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken();
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
if (operator == _msgSender()) revert ApproveToCaller();
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
_transfer(from, to, tokenId);
if (!_checkOnERC721Received(from, to, tokenId, _data)) {
revert TransferToNonERC721ReceiverImplementer();
}
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < _currentIndex && !_ownerships[tokenId].burned;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = _currentIndex;
if (to == address(0)) revert MintToZeroAddress();
if (quantity == 0) revert MintZeroQuantity();
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if _currentIndex + quantity > 3.4e38 (2**128) - 1
unchecked {
_addressData[to].balance += uint64(quantity);
_addressData[to].numberMinted += uint64(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (
safe &&
!_checkOnERC721Received(address(0), to, updatedIndex, _data)
) {
revert TransferToNonERC721ReceiverImplementer();
}
updatedIndex++;
}
_currentIndex = uint128(updatedIndex);
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership
.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
_beforeTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**128.
unchecked {
_addressData[prevOwnership.addr].balance -= 1;
_addressData[prevOwnership.addr].numberBurned += 1;
// Keep track of who burned the token, and the timestamp of burning.
_ownerships[tokenId].addr = prevOwnership.addr;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
_ownerships[tokenId].burned = true;
// If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
// This will suffice for checking _exists(nextTokenId),
// as a burned slot cannot contain the zero address.
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership
.startTimestamp;
}
}
}
emit Transfer(prevOwnership.addr, address(0), tokenId);
_afterTokenTransfers(prevOwnership.addr, address(0), tokenId, 1);
// Overflow not possible, as _burnCounter cannot be exceed _currentIndex times.
unchecked {
_burnCounter++;
}
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert TransferToNonERC721ReceiverImplementer();
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
* And also called before burning one token.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, `tokenId` will be burned by `from`.
* - `from` and `to` are never both zero.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
* And also called after one token has been burned.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, `from`'s `tokenId` has been
* transferred to `to`.
* - When `from` is zero, `tokenId` has been minted for `to`.
* - When `to` is zero, `tokenId` has been burned by `from`.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: @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: contract.sol
interface IStaking {
function mint(address _to, uint256 _amount) external;
}
pragma solidity ^0.8.4;
contract ODmfers is Ownable, ERC721A {
using Strings for uint256;
IStaking public StakingContract;
string private _tokenBaseURI = "https://api.odmfer.com/api/token/";
uint256 public ODM_MAX = 5000;
uint256 public ODM_PRICE_500 = 0.015 ether;
uint256 public ODM_PRICE = 0.025 ether;
uint256 public ODM_PER_MINT = 20;
uint256 public tokenMintsCounter;
bool public publicLive;
bool public stakingLive;
uint256 public earningRate = 781250000000000 wei;
mapping(uint256 => uint256) public tokensLastClaimBlock;
mapping(address => uint256[]) public balanceIds;
constructor() ERC721A("ODmfers", "ODM") {}
modifier callerIsUser() {
require(tx.origin == msg.sender, "The caller is another contract");
_;
}
function gift(address[] calldata receivers) external onlyOwner {
require(tokenMintsCounter + receivers.length <= ODM_MAX, "EXCEED_MAX");
for (uint256 i = 0; i < receivers.length; i++) {
tokensLastClaimBlock[tokenMintsCounter] = block.number;
balanceIds[receivers[i]].push(tokenMintsCounter);
tokenMintsCounter++;
_safeMint(receivers[i], 1);
}
}
function founderMint(uint256 tokenQuantity) external onlyOwner {
require(tokenMintsCounter + tokenQuantity <= ODM_MAX, "EXCEED_MAX");
tokensLastClaimBlock[tokenMintsCounter] = block.number;
balanceIds[msg.sender].push(tokenMintsCounter);
tokenMintsCounter++;
_safeMint(msg.sender, tokenQuantity);
}
function mint(uint256 tokenQuantity) external payable callerIsUser {
require(publicLive, "MINT_CLOSED");
require(tokenMintsCounter + tokenQuantity <= ODM_MAX, "EXCEED_MAX");
require(tokenQuantity <= ODM_PER_MINT, "EXCEED_PER_MINT");
require(
(ODM_PRICE * tokenQuantity <= msg.value &&
tokenMintsCounter >= 500) ||
(ODM_PRICE_500 * tokenQuantity <= msg.value &&
tokenMintsCounter < 500),
"INSUFFICIENT_ETH"
);
for (uint256 index = 0; index < tokenQuantity; index++) {
tokensLastClaimBlock[tokenMintsCounter] = block.number;
balanceIds[msg.sender].push(tokenMintsCounter);
tokenMintsCounter++;
}
_safeMint(msg.sender, tokenQuantity);
}
function withdraw() external onlyOwner {
uint256 currentBalance = address(this).balance;
Address.sendValue(
payable(0x11aAaC8bC9E41CfD4f0a674c5051aA74a10b075f),
(currentBalance * 10) / 100
);
Address.sendValue(
payable(0xabE9f7bdE9c5CBf955437F7982581e0d88Eb4579),
(currentBalance * 10) / 100
);
Address.sendValue(
payable(0x29998632e8fA926b738520Bc9f58382561C2C5D4),
(currentBalance * 10) / 100
);
Address.sendValue(
payable(0xDdCfA7150E12016A09b09E82319DeEAB0aBCA6BC),
(currentBalance * 30) / 100
);
Address.sendValue(
payable(0xc56F023b4B20f1716ab511AC6612b9a53e989c73),
(currentBalance * 30) / 100
);
Address.sendValue(
payable(0xE975567A01Ee879E6bA69eC9F03901267E9375f6),
address(this).balance
);
}
function togglePublicMintStatus() external onlyOwner {
publicLive = !publicLive;
}
function toggleStakingStatus() external onlyOwner {
stakingLive = !stakingLive;
}
function setPrice(uint256 newPrice) external onlyOwner {
ODM_PRICE = newPrice;
}
function setPrice_500(uint256 newPrice) external onlyOwner {
ODM_PRICE_500 = newPrice;
}
function setMax(uint256 newCount) external onlyOwner {
ODM_MAX = newCount;
}
function _baseURI() internal view virtual override returns (string memory) {
return _tokenBaseURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_tokenBaseURI = baseURI;
}
function tokenURI(uint256 tokenId) public view override(ERC721A) returns (string memory) {
require(_exists(tokenId), "Cannot query non-existent token");
return string(abi.encodePacked(_tokenBaseURI, tokenId.toString()));
}
function claimStakingRewards() external {
require(stakingLive, "STAKING_CLOSED");
uint256 totalRewards = 0;
for (
uint256 index = 0;
index < balanceIds[msg.sender].length;
index++
) {
require(
tokensLastClaimBlock[balanceIds[msg.sender][index]] > 0,
"WRONG_BLOCK_NUMBER"
);
totalRewards =
totalRewards +
earningRate *
(block.number -
(tokensLastClaimBlock[balanceIds[msg.sender][index]]));
tokensLastClaimBlock[balanceIds[msg.sender][index]] = block.number;
}
StakingContract.mint(msg.sender, totalRewards);
}
function setEarningRate(uint256 rate) external onlyOwner {
earningRate = rate;
}
function setStakingContract(address contractAddress) external onlyOwner {
StakingContract = IStaking(contractAddress);
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
for (uint256 index = 0; index < balanceIds[from].length; index++) {
if (balanceIds[from][index] == tokenId) {
balanceIds[from][index] = balanceIds[from][
balanceIds[from].length - 1
];
balanceIds[from].pop();
}
}
balanceIds[to].push(tokenId);
tokensLastClaimBlock[tokenId] = block.number;
ERC721A.transferFrom(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public override {
for (uint256 index = 0; index < balanceIds[from].length; index++) {
if (balanceIds[from][index] == tokenId) {
balanceIds[from][index] = balanceIds[from][
balanceIds[from].length - 1
];
balanceIds[from].pop();
}
}
balanceIds[to].push(tokenId);
tokensLastClaimBlock[tokenId] = block.number;
ERC721A.safeTransferFrom(from, to, tokenId, data);
}
receive() external payable {}
} | Transfers `tokenId` from `from` to `to`. Requirements: - `to` cannot be the zero address. - `tokenId` token must be owned by `from`. Emits a {Transfer} event./ Clear approvals from the previous owner Underflow of the sender's balance is impossible because we check for ownership above and the recipient's balance can't realistically overflow. Counter overflow is incredibly unrealistic as tokenId would have to be 2128. If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. This will suffice for checking _exists(nextTokenId), as a burned slot cannot contain the zero address. | function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
isApprovedForAll(prevOwnership.addr, _msgSender()) ||
getApproved(tokenId) == _msgSender());
if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved();
if (prevOwnership.addr != from) revert TransferFromIncorrectOwner();
if (to == address(0)) revert TransferToZeroAddress();
_beforeTokenTransfers(from, to, tokenId, 1);
_approve(address(0), tokenId, prevOwnership.addr);
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (nextTokenId < _currentIndex) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership
.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
| 19,242 |
./partial_match/1/0xa9CC6Ba946061870dC06617693D46325C6D8AdF7/sources/EvilRise.sol | Returns the message sender (defaults to `msg.sender`). If you are writing GSN compatible contracts, you need to override this function./ | function _msgSenderERC721A() internal view virtual returns (address) {
return msg.sender;
) internal virtual {}
}
| 3,697,701 |
./full_match/43114/0x70B907f3F7231bE122100dac51C1995e6804E346/sources/trueReflect.sol | Returns the address of the current owner./ | function getOwner() public view returns (address) {
return _owner;
}
| 4,533,196 |
pragma solidity ^0.5.0;
interface SwapInterface {
// Public variables
function brokerFees(address _broker) external view returns (uint256);
function redeemedAt(bytes32 _swapID) external view returns(uint256);
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) external payable;
/// @notice Initiates the atomic swap with broker fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) external payable;
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _receiver The receiver's address.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) external;
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) external;
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) external;
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) external;
/// @notice Audits an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function audit(
bytes32 _swapID
) external view returns (
uint256 timelock,
uint256 value,
address to, uint256 brokerFee,
address broker,
address from,
bytes32 secretLock
);
/// @notice Audits the secret of an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function auditSecret(bytes32 _swapID) external view returns (bytes32 secretKey);
/// @notice Checks whether a swap is refundable or not.
///
/// @param _swapID The unique atomic swap id.
function refundable(bytes32 _swapID) external view returns (bool);
/// @notice Checks whether a swap is initiatable or not.
///
/// @param _swapID The unique atomic swap id.
function initiatable(bytes32 _swapID) external view returns (bool);
/// @notice Checks whether a swap is redeemable or not.
///
/// @param _swapID The unique atomic swap id.
function redeemable(bytes32 _swapID) external view returns (bool);
/// @notice Generates a deterministic swap id using initiate swap details.
///
/// @param _secretLock The hash of the secret.
/// @param _timelock The expiry timestamp.
function swapID(bytes32 _secretLock, uint256 _timelock) external pure returns (bytes32);
}
contract BaseSwap is SwapInterface {
string public VERSION; // Passed in as a constructor parameter.
struct Swap {
uint256 timelock;
uint256 value;
uint256 brokerFee;
bytes32 secretLock;
bytes32 secretKey;
address payable funder;
address payable spender;
address payable broker;
}
enum States {
INVALID,
OPEN,
CLOSED,
EXPIRED
}
// Events
event LogOpen(bytes32 _swapID, address _spender, bytes32 _secretLock);
event LogExpire(bytes32 _swapID);
event LogClose(bytes32 _swapID, bytes32 _secretKey);
// Storage
mapping (bytes32 => Swap) internal swaps;
mapping (bytes32 => States) private _swapStates;
mapping (address => uint256) private _brokerFees;
mapping (bytes32 => uint256) private _redeemedAt;
/// @notice Throws if the swap is not invalid (i.e. has already been opened)
modifier onlyInvalidSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.INVALID, "swap opened previously");
_;
}
/// @notice Throws if the swap is not open.
modifier onlyOpenSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.OPEN, "swap not open");
_;
}
/// @notice Throws if the swap is not closed.
modifier onlyClosedSwaps(bytes32 _swapID) {
require(_swapStates[_swapID] == States.CLOSED, "swap not redeemed");
_;
}
/// @notice Throws if the swap is not expirable.
modifier onlyExpirableSwaps(bytes32 _swapID) {
/* solium-disable-next-line security/no-block-members */
require(now >= swaps[_swapID].timelock, "swap not expirable");
_;
}
/// @notice Throws if the secret key is not valid.
modifier onlyWithSecretKey(bytes32 _swapID, bytes32 _secretKey) {
require(swaps[_swapID].secretLock == sha256(abi.encodePacked(_secretKey)), "invalid secret");
_;
}
/// @notice Throws if the caller is not the authorized spender.
modifier onlySpender(bytes32 _swapID, address _spender) {
require(swaps[_swapID].spender == _spender, "unauthorized spender");
_;
}
/// @notice The contract constructor.
///
/// @param _VERSION A string defining the contract version.
constructor(string memory _VERSION) public {
VERSION = _VERSION;
}
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public onlyInvalidSwaps(_swapID) payable {
// Store the details of the swap.
Swap memory swap = Swap({
timelock: _timelock,
brokerFee: 0,
value: _value,
funder: msg.sender,
spender: _spender,
broker: address(0x0),
secretLock: _secretLock,
secretKey: 0x0
});
swaps[_swapID] = swap;
_swapStates[_swapID] = States.OPEN;
// Logs open event
emit LogOpen(_swapID, _spender, _secretLock);
}
/// @notice Initiates the atomic swap with fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public onlyInvalidSwaps(_swapID) payable {
require(_value >= _brokerFee, "fee must be less than value");
// Store the details of the swap.
Swap memory swap = Swap({
timelock: _timelock,
brokerFee: _brokerFee,
value: _value - _brokerFee,
funder: msg.sender,
spender: _spender,
broker: _broker,
secretLock: _secretLock,
secretKey: 0x0
});
swaps[_swapID] = swap;
_swapStates[_swapID] = States.OPEN;
// Logs open event
emit LogOpen(_swapID, _spender, _secretLock);
}
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _receiver The receiver's address.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) onlySpender(_swapID, msg.sender) {
require(_receiver != address(0x0), "invalid receiver");
// Close the swap.
swaps[_swapID].secretKey = _secretKey;
_swapStates[_swapID] = States.CLOSED;
/* solium-disable-next-line security/no-block-members */
_redeemedAt[_swapID] = now;
// Update the broker fees to the broker.
_brokerFees[swaps[_swapID].broker] += swaps[_swapID].brokerFee;
// Logs close event
emit LogClose(_swapID, _secretKey);
}
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) public onlyOpenSwaps(_swapID) onlyWithSecretKey(_swapID, _secretKey) {
// Close the swap.
swaps[_swapID].secretKey = _secretKey;
_swapStates[_swapID] = States.CLOSED;
/* solium-disable-next-line security/no-block-members */
_redeemedAt[_swapID] = now;
// Update the broker fees to the broker.
_brokerFees[swaps[_swapID].broker] += swaps[_swapID].brokerFee;
// Logs close event
emit LogClose(_swapID, _secretKey);
}
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) public onlyOpenSwaps(_swapID) onlyExpirableSwaps(_swapID) {
// Expire the swap.
_swapStates[_swapID] = States.EXPIRED;
// Logs expire event
emit LogExpire(_swapID);
}
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) public {
require(_amount <= _brokerFees[msg.sender], "insufficient withdrawable fees");
_brokerFees[msg.sender] -= _amount;
}
/// @notice Audits an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function audit(bytes32 _swapID) external view returns (uint256 timelock, uint256 value, address to, uint256 brokerFee, address broker, address from, bytes32 secretLock) {
Swap memory swap = swaps[_swapID];
return (
swap.timelock,
swap.value,
swap.spender,
swap.brokerFee,
swap.broker,
swap.funder,
swap.secretLock
);
}
/// @notice Audits the secret of an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function auditSecret(bytes32 _swapID) external view onlyClosedSwaps(_swapID) returns (bytes32 secretKey) {
return swaps[_swapID].secretKey;
}
/// @notice Checks whether a swap is refundable or not.
///
/// @param _swapID The unique atomic swap id.
function refundable(bytes32 _swapID) external view returns (bool) {
/* solium-disable-next-line security/no-block-members */
return (now >= swaps[_swapID].timelock && _swapStates[_swapID] == States.OPEN);
}
/// @notice Checks whether a swap is initiatable or not.
///
/// @param _swapID The unique atomic swap id.
function initiatable(bytes32 _swapID) external view returns (bool) {
return (_swapStates[_swapID] == States.INVALID);
}
/// @notice Checks whether a swap is redeemable or not.
///
/// @param _swapID The unique atomic swap id.
function redeemable(bytes32 _swapID) external view returns (bool) {
return (_swapStates[_swapID] == States.OPEN);
}
function redeemedAt(bytes32 _swapID) external view returns (uint256) {
return _redeemedAt[_swapID];
}
function brokerFees(address _broker) external view returns (uint256) {
return _brokerFees[_broker];
}
/// @notice Generates a deterministic swap id using initiate swap details.
///
/// @param _secretLock The hash of the secret.
/// @param _timelock The expiry timestamp.
function swapID(bytes32 _secretLock, uint256 _timelock) external pure returns (bytes32) {
return keccak256(abi.encodePacked(_secretLock, _timelock));
}
}
/// @notice EthSwap implements the RenEx atomic swapping interface
/// for Ether values. Does not support ERC20 tokens.
contract EthSwap is SwapInterface, BaseSwap {
constructor(string memory _VERSION) BaseSwap(_VERSION) public {
}
/// @notice Initiates the atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiate(
bytes32 _swapID,
address payable _spender,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public payable {
require(_value == msg.value, "eth amount must match value");
require(_spender != address(0x0), "spender must not be zero");
BaseSwap.initiate(
_swapID,
_spender,
_secretLock,
_timelock,
_value
);
}
/// @notice Initiates the atomic swap with fees.
///
/// @param _swapID The unique atomic swap id.
/// @param _spender The address of the withdrawing trader.
/// @param _broker The address of the broker.
/// @param _brokerFee The fee to be paid to the broker on success.
/// @param _secretLock The hash of the secret (Hash Lock).
/// @param _timelock The unix timestamp when the swap expires.
/// @param _value The value of the atomic swap.
function initiateWithFees(
bytes32 _swapID,
address payable _spender,
address payable _broker,
uint256 _brokerFee,
bytes32 _secretLock,
uint256 _timelock,
uint256 _value
) public payable {
require(_value == msg.value, "eth amount must match value");
require(_spender != address(0x0), "spender must not be zero");
BaseSwap.initiateWithFees(
_swapID,
_spender,
_broker,
_brokerFee,
_secretLock,
_timelock,
_value
);
}
/// @notice Redeems an atomic swap.
///
/// @param _swapID The unique atomic swap id.
/// @param _receiver The receiver's address.
/// @param _secretKey The secret of the atomic swap.
function redeem(bytes32 _swapID, address payable _receiver, bytes32 _secretKey) public {
BaseSwap.redeem(
_swapID,
_receiver,
_secretKey
);
// Transfer the ETH funds from this contract to the receiver.
_receiver.transfer(BaseSwap.swaps[_swapID].value);
}
/// @notice Redeems an atomic swap to the spender. Can be called by anyone.
///
/// @param _swapID The unique atomic swap id.
/// @param _secretKey The secret of the atomic swap.
function redeemToSpender(bytes32 _swapID, bytes32 _secretKey) public {
BaseSwap.redeemToSpender(
_swapID,
_secretKey
);
// Transfer the ETH funds from this contract to the receiver.
swaps[_swapID].spender.transfer(BaseSwap.swaps[_swapID].value);
}
/// @notice Refunds an atomic swap.
///
/// @param _swapID The unique atomic swap id.
function refund(bytes32 _swapID) public {
BaseSwap.refund(_swapID);
// Transfer the ETH value from this contract back to the ETH trader.
BaseSwap.swaps[_swapID].funder.transfer(
BaseSwap.swaps[_swapID].value + BaseSwap.swaps[_swapID].brokerFee
);
}
/// @notice Allows broker fee withdrawals.
///
/// @param _amount The withdrawal amount.
function withdrawBrokerFees(uint256 _amount) public {
BaseSwap.withdrawBrokerFees(_amount);
msg.sender.transfer(_amount);
}
} | Allows broker fee withdrawals. _amount The withdrawal amount. | function withdrawBrokerFees(uint256 _amount) public {
BaseSwap.withdrawBrokerFees(_amount);
msg.sender.transfer(_amount);
}
| 896,599 |
./full_match/43114/0x4cC3F181E4101C02F59978c4D3750C30D739a552/sources/contracts/Masterchef.sol | Update the given pool's EXP allocation point. Can only be called by the owner. | function set(uint256 _pid, uint256 _allocPoint) public onlyOwner {
massUpdatePools();
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
emit Set(_pid, _allocPoint);
}
| 4,629,444 |
pragma solidity 0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
assert(c / _a == _b);
return c;
}
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
return _a / _b;
}
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
assert(c >= _a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract holds owner addresses, and provides basic authorization control
* functions.
*/
contract Ownable {
/**
* @dev Allows to check if the given address has owner rights.
* @param _owner The address to check for owner rights.
* @return True if the address is owner, false if it is not.
*/
mapping(address => bool) public owners;
/**
* @dev The Ownable constructor adds the sender
* account to the owners mapping.
*/
constructor() public {
owners[msg.sender] = true;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwners() {
require(owners[msg.sender], 'Owner message sender required.');
_;
}
/**
* @dev Allows the current owners to grant or revoke
* owner-level access rights to the contract.
* @param _owner The address to grant or revoke owner rights.
* @param _isAllowed Boolean granting or revoking owner rights.
* @return True if the operation has passed or throws if failed.
*/
function setOwner(address _owner, bool _isAllowed) public onlyOwners {
require(_owner != address(0), 'Non-zero owner-address required.');
owners[_owner] = _isAllowed;
}
}
/**
* @title Destroyable
* @dev Base contract that can be destroyed by the owners. All funds in contract will be sent back.
*/
contract Destroyable is Ownable {
constructor() public payable {}
/**
* @dev Transfers The current balance to the message sender and terminates the contract.
*/
function destroy() public onlyOwners {
selfdestruct(msg.sender);
}
/**
* @dev Transfers The current balance to the specified _recipient and terminates the contract.
* @param _recipient The address to send the current balance to.
*/
function destroyAndSend(address _recipient) public onlyOwners {
require(_recipient != address(0), 'Non-zero recipient address required.');
selfdestruct(_recipient);
}
}
/**
* @title BotOperated
* @dev The BotOperated contract holds bot addresses, and provides basic authorization control
* functions.
*/
contract BotOperated is Ownable {
/**
* @dev Allows to check if the given address has bot rights.
* @param _bot The address to check for bot rights.
* @return True if the address is bot, false if it is not.
*/
mapping(address => bool) public bots;
/**
* @dev Throws if called by any account other than bot or owner.
*/
modifier onlyBotsOrOwners() {
require(bots[msg.sender] || owners[msg.sender], 'Bot or owner message sender required.');
_;
}
/**
* @dev Throws if called by any account other than the bot.
*/
modifier onlyBots() {
require(bots[msg.sender], 'Bot message sender required.');
_;
}
/**
* @dev The BotOperated constructor adds the sender
* account to the bots mapping.
*/
constructor() public {
bots[msg.sender] = true;
}
/**
* @dev Allows the current owners to grant or revoke
* bot-level access rights to the contract.
* @param _bot The address to grant or revoke bot rights.
* @param _isAllowed Boolean granting or revoking bot rights.
* @return True if the operation has passed or throws if failed.
*/
function setBot(address _bot, bool _isAllowed) public onlyOwners {
require(_bot != address(0), 'Non-zero bot-address required.');
bots[_bot] = _isAllowed;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is BotOperated {
event Pause();
event Unpause();
bool public paused = true;
/**
* @dev Modifier to allow actions only when the contract IS NOT paused.
*/
modifier whenNotPaused() {
require(!paused, 'Unpaused contract required.');
_;
}
/**
* @dev Called by the owner to pause, triggers stopped state.
* @return True if the operation has passed.
*/
function pause() public onlyBotsOrOwners {
paused = true;
emit Pause();
}
/**
* @dev Called by the owner to unpause, returns to normal state.
* @return True if the operation has passed.
*/
function unpause() public onlyBotsOrOwners {
paused = false;
emit Unpause();
}
}
interface EternalDataStorage {
function balances(address _owner) external view returns (uint256);
function setBalance(address _owner, uint256 _value) external;
function allowed(address _owner, address _spender) external view returns (uint256);
function setAllowance(address _owner, address _spender, uint256 _amount) external;
function totalSupply() external view returns (uint256);
function setTotalSupply(uint256 _value) external;
function frozenAccounts(address _target) external view returns (bool isFrozen);
function setFrozenAccount(address _target, bool _isFrozen) external;
function increaseAllowance(address _owner, address _spender, uint256 _increase) external;
function decreaseAllowance(address _owner, address _spender, uint256 _decrease) external;
}
interface Ledger {
function addTransaction(address _from, address _to, uint _tokens) external;
}
interface WhitelistData {
function kycId(address _customer) external view returns (bytes32);
}
/**
* @title ERC20Standard token
* @dev Implementation of the basic standard token.
* @notice https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
*/
contract ERC20Standard {
using SafeMath for uint256;
EternalDataStorage internal dataStorage;
Ledger internal ledger;
WhitelistData internal whitelist;
/**
* @dev Triggered when tokens are transferred.
* @notice MUST trigger when tokens are transferred, including zero value transfers.
*/
event Transfer(address indexed _from, address indexed _to, uint256 _value);
/**
* @dev Triggered whenever approve(address _spender, uint256 _value) is called.
* @notice MUST trigger on any successful call to approve(address _spender, uint256 _value).
*/
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
modifier isWhitelisted(address _customer) {
require(whitelist.kycId(_customer) != 0x0, 'Whitelisted customer required.');
_;
}
/**
* @dev Constructor function that instantiates the EternalDataStorage, Ledger and Whitelist contracts.
* @param _dataStorage Address of the Data Storage Contract.
* @param _ledger Address of the Ledger Contract.
* @param _whitelist Address of the Whitelist Data Contract.
*/
constructor(address _dataStorage, address _ledger, address _whitelist) public {
require(_dataStorage != address(0), 'Non-zero data storage address required.');
require(_ledger != address(0), 'Non-zero ledger address required.');
require(_whitelist != address(0), 'Non-zero whitelist address required.');
dataStorage = EternalDataStorage(_dataStorage);
ledger = Ledger(_ledger);
whitelist = WhitelistData(_whitelist);
}
/**
* @dev Gets the total supply of tokens.
* @return totalSupplyAmount The total amount of tokens.
*/
function totalSupply() public view returns (uint256 totalSupplyAmount) {
return dataStorage.totalSupply();
}
/**
* @dev Get the balance of the specified `_owner` address.
* @return balance The token balance of the given address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return dataStorage.balances(_owner);
}
/**
* @dev Transfer token to a specified address.
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
* @return success True if the transfer was successful, or throws.
*/
function transfer(address _to, uint256 _value) public returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
/**
* @dev Transfer `_value` tokens to `_to` in behalf of `_from`.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount to send.
* @return success True if the transfer was successful, or throws.
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
uint256 allowed = dataStorage.allowed(_from, msg.sender);
require(allowed >= _value, 'From account has insufficient balance');
allowed = allowed.sub(_value);
dataStorage.setAllowance(_from, msg.sender, allowed);
return _transfer(_from, _to, _value);
}
/**
* @dev Allows `_spender` to withdraw from your account multiple times, up to the `_value` amount.
* approve will revert if allowance of _spender is 0. increaseApproval and decreaseApproval should
* be used instead to avoid exploit identified here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* @notice If this function is called again it overwrites the current allowance with `_value`.
* @param _spender The address authorized to spend.
* @param _value The max amount they can spend.
* @return success True if the operation was successful, or false.
*/
function approve(address _spender, uint256 _value) public returns (bool success) {
require
(
_value == 0 || dataStorage.allowed(msg.sender, _spender) == 0,
'Approve value is required to be zero or account has already been approved.'
);
dataStorage.setAllowance(msg.sender, _spender, _value);
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* This function must be called for increasing approval from a non-zero value
* as using approve will revert. It has been added as a fix to the exploit mentioned
* here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint256 _addedValue) public {
dataStorage.increaseAllowance(msg.sender, _spender, _addedValue);
emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender));
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* This function must be called for decreasing approval from a non-zero value
* as using approve will revert. It has been added as a fix to the exploit mentioned
* here: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md#approve
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint256 _subtractedValue) public {
dataStorage.decreaseAllowance(msg.sender, _spender, _subtractedValue);
emit Approval(msg.sender, _spender, dataStorage.allowed(msg.sender, _spender));
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner The address which owns the funds.
* @param _spender 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 dataStorage.allowed(_owner, _spender);
}
/**
* @dev Internal transfer, can only be called by this contract.
* @param _from The address of the sender.
* @param _to The address of the recipient.
* @param _value The amount to send.
* @return success True if the transfer was successful, or throws.
*/
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {
require(_to != address(0), 'Non-zero to-address required.');
uint256 fromBalance = dataStorage.balances(_from);
require(fromBalance >= _value, 'From-address has insufficient balance.');
fromBalance = fromBalance.sub(_value);
uint256 toBalance = dataStorage.balances(_to);
toBalance = toBalance.add(_value);
dataStorage.setBalance(_from, fromBalance);
dataStorage.setBalance(_to, toBalance);
ledger.addTransaction(_from, _to, _value);
emit Transfer(_from, _to, _value);
return true;
}
}
/**
* @title MintableToken
* @dev ERC20Standard modified with mintable token creation.
*/
contract MintableToken is ERC20Standard, Ownable {
/**
* @dev Hardcap - maximum allowed amount of tokens to be minted
*/
uint104 public constant MINTING_HARDCAP = 1e30;
/**
* @dev Auto-generated function to check whether the minting has finished.
* @return True if the minting has finished, or false.
*/
bool public mintingFinished = false;
event Mint(address indexed _to, uint256 _amount);
event MintFinished();
modifier canMint() {
require(!mintingFinished, 'Uninished minting required.');
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
*/
function mint(address _to, uint256 _amount) public onlyOwners canMint() {
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.add(_amount);
require(totalSupply <= MINTING_HARDCAP, 'Total supply of token in circulation must be below hardcap.');
dataStorage.setTotalSupply(totalSupply);
uint256 toBalance = dataStorage.balances(_to);
toBalance = toBalance.add(_amount);
dataStorage.setBalance(_to, toBalance);
ledger.addTransaction(address(0), _to, _amount);
emit Transfer(address(0), _to, _amount);
emit Mint(_to, _amount);
}
/**
* @dev Function to permanently stop minting new tokens.
*/
function finishMinting() public onlyOwners {
mintingFinished = true;
emit MintFinished();
}
}
/**
* @title BurnableToken
* @dev ERC20Standard token that can be irreversibly burned(destroyed).
*/
contract BurnableToken is ERC20Standard {
event Burn(address indexed _burner, uint256 _value);
/**
* @dev Remove tokens from the system irreversibly.
* @notice Destroy tokens from your account.
* @param _value The amount of tokens to burn.
*/
function burn(uint256 _value) public {
uint256 senderBalance = dataStorage.balances(msg.sender);
require(senderBalance >= _value, 'Burn value less than account balance required.');
senderBalance = senderBalance.sub(_value);
dataStorage.setBalance(msg.sender, senderBalance);
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.sub(_value);
dataStorage.setTotalSupply(totalSupply);
emit Burn(msg.sender, _value);
emit Transfer(msg.sender, address(0), _value);
}
/**
* @dev Remove specified `_value` tokens from the system irreversibly on behalf of `_from`.
* @param _from The address from which to burn tokens.
* @param _value The amount of money to burn.
*/
function burnFrom(address _from, uint256 _value) public {
uint256 fromBalance = dataStorage.balances(_from);
require(fromBalance >= _value, 'Burn value less than from-account balance required.');
uint256 allowed = dataStorage.allowed(_from, msg.sender);
require(allowed >= _value, 'Burn value less than account allowance required.');
fromBalance = fromBalance.sub(_value);
dataStorage.setBalance(_from, fromBalance);
allowed = allowed.sub(_value);
dataStorage.setAllowance(_from, msg.sender, allowed);
uint256 totalSupply = dataStorage.totalSupply();
totalSupply = totalSupply.sub(_value);
dataStorage.setTotalSupply(totalSupply);
emit Burn(_from, _value);
emit Transfer(_from, address(0), _value);
}
}
/**
* @title PausableToken
* @dev ERC20Standard modified with pausable transfers.
**/
contract PausableToken is ERC20Standard, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool success) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool success) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool success) {
return super.approve(_spender, _value);
}
}
/**
* @title FreezableToken
* @dev ERC20Standard modified with freezing accounts ability.
*/
contract FreezableToken is ERC20Standard, Ownable {
event FrozenFunds(address indexed _target, bool _isFrozen);
/**
* @dev Allow or prevent target address from sending & receiving tokens.
* @param _target Address to be frozen or unfrozen.
* @param _isFrozen Boolean indicating freeze or unfreeze operation.
*/
function freezeAccount(address _target, bool _isFrozen) public onlyOwners {
require(_target != address(0), 'Non-zero to-be-frozen-account address required.');
dataStorage.setFrozenAccount(_target, _isFrozen);
emit FrozenFunds(_target, _isFrozen);
}
/**
* @dev Checks whether the target is frozen or not.
* @param _target Address to check.
* @return isFrozen A boolean that indicates whether the account is frozen or not.
*/
function isAccountFrozen(address _target) public view returns (bool isFrozen) {
return dataStorage.frozenAccounts(_target);
}
/**
* @dev Overrided _transfer function that uses freeze functionality
*/
function _transfer(address _from, address _to, uint256 _value) internal returns (bool success) {
assert(!dataStorage.frozenAccounts(_from));
assert(!dataStorage.frozenAccounts(_to));
return super._transfer(_from, _to, _value);
}
}
/**
* @title ERC20Extended
* @dev Standard ERC20 token with extended functionalities.
*/
contract ERC20Extended is FreezableToken, PausableToken, BurnableToken, MintableToken, Destroyable {
/**
* @dev Auto-generated function that returns the name of the token.
* @return The name of the token.
*/
string public constant name = 'ORBISE10';
/**
* @dev Auto-generated function that returns the symbol of the token.
* @return The symbol of the token.
*/
string public constant symbol = 'ORBT';
/**
* @dev Auto-generated function that returns the number of decimals of the token.
* @return The number of decimals of the token.
*/
uint8 public constant decimals = 18;
/**
* @dev Constant for the minimum allowed amount of tokens one can buy
*/
uint72 public constant MINIMUM_BUY_AMOUNT = 200e18;
/**
* @dev Auto-generated function that gets the price at which the token is sold.
* @return The sell price of the token.
*/
uint256 public sellPrice;
/**
* @dev Auto-generated function that gets the price at which the token is bought.
* @return The buy price of the token.
*/
uint256 public buyPrice;
/**
* @dev Auto-generated function that gets the address of the wallet of the contract.
* @return The address of the wallet.
*/
address public wallet;
/**
* @dev Constructor function that calculates the total supply of tokens,
* sets the initial sell and buy prices and
* passes arguments to base constructors.
* @param _dataStorage Address of the Data Storage Contract.
* @param _ledger Address of the Data Storage Contract.
* @param _whitelist Address of the Whitelist Data Contract.
*/
constructor
(
address _dataStorage,
address _ledger,
address _whitelist
)
ERC20Standard(_dataStorage, _ledger, _whitelist)
public
{
}
/**
* @dev Fallback function that allows the contract
* to receive Ether directly.
*/
function() public payable { }
/**
* @dev Function that sets both the sell and the buy price of the token.
* @param _sellPrice The price at which the token will be sold.
* @param _buyPrice The price at which the token will be bought.
*/
function setPrices(uint256 _sellPrice, uint256 _buyPrice) public onlyBotsOrOwners {
sellPrice = _sellPrice;
buyPrice = _buyPrice;
}
/**
* @dev Function that sets the current wallet address.
* @param _walletAddress The address of wallet to be set.
*/
function setWallet(address _walletAddress) public onlyOwners {
require(_walletAddress != address(0), 'Non-zero wallet address required.');
wallet = _walletAddress;
}
/**
* @dev Send Ether to buy tokens at the current token sell price.
* @notice buy function has minimum allowed amount one can buy
*/
function buy() public payable whenNotPaused isWhitelisted(msg.sender) {
uint256 amount = msg.value.mul(1e18);
amount = amount.div(sellPrice);
require(amount >= MINIMUM_BUY_AMOUNT, "Buy amount too small");
_transfer(this, msg.sender, amount);
}
/**
* @dev Sell `_amount` tokens at the current buy price.
* @param _amount The amount to sell.
*/
function sell(uint256 _amount) public whenNotPaused {
uint256 toBeTransferred = _amount.mul(buyPrice);
require(toBeTransferred >= 1e18, "Sell amount too small");
toBeTransferred = toBeTransferred.div(1e18);
require(address(this).balance >= toBeTransferred, 'Contract has insufficient balance.');
_transfer(msg.sender, this, _amount);
msg.sender.transfer(toBeTransferred);
}
/**
* @dev Get the contract balance in WEI.
*/
function getContractBalance() public view returns (uint256) {
return address(this).balance;
}
/**
* @dev Withdraw `_amount` ETH to the wallet address.
* @param _amount The amount to withdraw.
*/
function withdraw(uint256 _amount) public onlyOwners {
require(address(this).balance >= _amount, 'Unable to withdraw specified amount.');
require(wallet != address(0), 'Non-zero wallet address required.');
wallet.transfer(_amount);
}
/**
* @dev Transfer, which is used when Orbise is bought with different currency than ETH.
* @param _to The address of the recipient.
* @param _value The amount of Orbise Tokens to transfer.
* @return success True if operation is executed successfully.
*/
function nonEtherPurchaseTransfer(address _to, uint256 _value) public isWhitelisted(_to) onlyBots whenNotPaused returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
} | Transfers The current balance to the message sender and terminates the contract./ | function destroy() public onlyOwners {
selfdestruct(msg.sender);
}
| 12,954,008 |
pragma solidity ^0.4.20;
import "Userbase.sol";
contract Rental {
/* DECLARING VARIABLES */
address public owner;
int public idCount;
/* MAPPING */
mapping (uint => Apartment) public apartments;
mapping (address => bool) public isRenter;
mapping (address => uint) internal balances;
/* EVENTS */
event apartmentAdded (uint id);
event ForRent (uint id);
event Deposited (uint id);
event Rented (uint id);
event Cancelled (uint id);
event Refunded (address accountToRefund, uint id);
event OffMarket (uint id);
/* MODIFIERS */
modifier forRent (uint _id) { require(apartments[_id].state == "ForRent"); _; };
modifier canDeposit (uint _id) { require(balances[msg.sender] >= msg.value); _; };
modifier depositedEnough (uint _id) { require(apartments[_id].deposit <= msg.value); _; };
modifier deposited (uint _id) { require(apartments[_id].state == "Deposited"); _; };
modifier rented (uint _id) { require(apartments[_id].state == "Rented"); _; };
modifier cancelled (uint _id) { require(apartments[_id].state == "Cancelled"); _; };
modifier canCancel (uint _id) { require(apartments[_id].seller == msg.sender || apartments[_id].renter == msg.sender); _; };
modifier offMarket (uint _id) { require(apartments[_id].state == "OffMarket"); _; };
modifier apartmentExists(uint _id) { require _id > 0 && _id <= idCount }
/* ENUMERATORS */
enum State { OffMarket, OnMarket, ForRent, Deposited, Rented, Ended }
/* STRUCTS */
struct Apartment {
uint id;
string location;
uint state;
uint term;
uint deposit;
uint price;
address seller;
address renter;
}
/* CONSTRUCTOR */
// define contract owner
constructor() public {
owner = msg.sender;
idCount = 0;
}
/* VIEWS */
function getApartment(uint _id)
public
view
returns (
uint _id,
string location,
uint state, // NOTE: is this correct?
uint term,
uint deposit,
uint price,
address seller,
address renter
)
{
apartmentExists(_id);
Apartment storage apartment = apartments[_id];
location = apartment.location;
state = apartment.state;
deposit = apartment.deposit;
price = apartment.price;
seller = apartment.seller;
renter = apartment.renter;
}
function getSellers() public view returns (address[]) {
return sellers;
}
function getSeller(uint _id) public view returns (address) {
return apartments[_id].seller;
}
function getDeposit(uint _id) public view returns (uint) {
return apartments[_id].deposit;
}
function getPrice(uint _id) public view returns (uint) {
return apartments[_id].price;
}
/* FUNCTIONS */
// enable seller to post rental
function addApartment(string _location, string _term, string _deposit, string _price)
public
returns (bool)
{
authorizedUser(msg.sender);
idCount = idCount + 1;
emit ForRent(idCount);
apartments[id] = Apartment({
id: idCount,
location: _location,
state: State.OffMarket,
term: _term,
deposit: _deposit,
price: _price,
seller: msg.sender,
renter: 0
});
return true;
}
// enable seller to delete rental
function removeApartment(uint _id)
public
returns ()
{
// do something
}
// security deposit
function securityDeposit(uint _id)
public
returns (uint)
{
forRent(_id);
canDeposit(msg.sender);
depositedEnough(msg.sender);
_securityDeposit(uint _id);
}
function _securityDeposit(uint _id)
internal
payable
returns (uint)
{
emit Deposited(uint _id);
}
// enable renter to buy apartment
function rentApartment(uint _id)
public
returns (bool)
{
// do something
}
// cancel apartment rental
function cancelRental(uint _id)
public
payable
returns (bool)
{
emit Cancelled(_id);
canCancel(_id);
}
// confirm cancellation
function confirmCancelRental()
public
{
// do something
}
}
| enable seller to post rental | function addApartment(string _location, string _term, string _deposit, string _price)
public
returns (bool)
{
authorizedUser(msg.sender);
idCount = idCount + 1;
emit ForRent(idCount);
apartments[id] = Apartment({
id: idCount,
location: _location,
state: State.OffMarket,
term: _term,
deposit: _deposit,
price: _price,
seller: msg.sender,
renter: 0
});
return true;
}
| 1,035,541 |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256; // Allow SafeMath functions to be called for all uint256 types (similar to "prototype" in Javascript)
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
mapping(bytes32 => Flight) private flights;
address[] multiCalls = new address[](0); // keep track of the number of addresses authorizing a new airline
struct Airlines {
address airline;
bool haveFund;
bool isActive;
uint256 value;
}
mapping(address => Airlines) airlines;
//Airlines[] airlines;
// Track the number of registered airlines
// We should start with one airline
uint countAirlines = 1;
uint256 public constant FUND_FEE = 10 ether; // Fee to be paid when registering an airline
uint256 public constant INSURANCE_FEE = 1 ether; // Fee to be paid when registering oracle
FlightSuretyData flightSuretyData;
/********************************************************************************************/
/* 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 requireIsOperational()
{
// Modify to call data contract's status
require(isOperational(), "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 requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
event FundsReceived(address airline, uint256 amount);
event BoughtInsurance(address airline, address passenger, string flight, uint256 insurance, uint256 payout);
event PassengerPaid(address passenger, uint256 payout);
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor
(
address dataContract
)
public
payable
{
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
// register first airline
airlines[msg.sender] = Airlines({
airline: msg.sender,
haveFund: false,
isActive: true,
value: 0
});
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
function isOperational()
public
view
returns(bool)
{
return operational; // Modify to call data contract's status
}
function getOwner()
public
view
returns(address)
{
return contractOwner; // Modify to call data contract's status
}
function getNumberOfAirlines()
public
view
returns(uint)
{
return countAirlines;
}
function getAirlineInfo
(
address _airline
)
public
view
returns
(
address airline,
bool haveFund,
bool isActive,
uint256 value
)
{
airline = airlines[_airline].airline;
haveFund = airlines[_airline].haveFund;
isActive = airlines[_airline].isActive;
value = airlines[_airline].value;
return
(
airline,
haveFund,
isActive,
value
);
}
function getInsurance
(
address _passenger
)
public
view
returns
(
address _air,
address _pas,
string _fli,
uint256 _amo,
uint256 _payout,
bool _open
)
{
return flightSuretyData.getInsurance(_passenger);
}
function getPayment
(
address p
)
public
view
returns
(
uint256
)
{
return flightSuretyData.getPayout(p);
}
// function getAirlines() public view returns (airlines) {
// return airlines;
// }
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Add an airline to the registration queue
*
*/
function registerAirline
(
address airline
)
public
returns(bool success, uint256 votes)
{
require(airlines[msg.sender].isActive, "Caller is not active yet");
flightSuretyData.registerAirline(airline);
success = true;
return (success, 0);
}
function setAirlineStatus
(
address airline
)
public
{
require(flightSuretyData.isQueued(airline) == true, "Airline not added to the queue yet");
require(airlines[airline].airline == address(0), "Airline already exist");
require(airlines[msg.sender].isActive, "Caller is not active yet");
if(countAirlines < 4) {
airlines[airline] = Airlines({
airline: airline,
haveFund: false,
isActive: true,
value: 0
});
countAirlines += 1;
} else {
bool isDuplicate = false;
for(uint c=0; c<multiCalls.length; c++) {
if (multiCalls[c] == msg.sender) {
isDuplicate = true;
break;
}
}
require(!isDuplicate, "Caller has already called this function.");
multiCalls.push(msg.sender);
flightSuretyData.addVotes(airline,1);
uint M = (countAirlines*10)/2;
uint vote = flightSuretyData.getVotes(airline)*10;
//uint vote = multiCalls.length*10;
if (vote >= M) {
airlines[airline] = Airlines({
airline: airline,
haveFund: false,
isActive: true,
value: 0
});
countAirlines += 1;
multiCalls = new address[](0); // Reset multiCalls array
flightSuretyData.removeVotes(airline);
}
}
}
function addFunds
(
)
public
payable
{
require(msg.sender == airlines[msg.sender].airline, "You need to be a registered airline to add funds to this contract");
require(msg.value == FUND_FEE, "We need 10 ether here");
airlines[msg.sender].haveFund = true;
airlines[msg.sender].value = msg.value;
emit FundsReceived(msg.sender, msg.value);
}
function buyInsurance
(
address airline,
string flight
)
public
payable
{
require(msg.value <= INSURANCE_FEE, "Maximum insurance allowed is 1 ether");
require(airlines[airline].haveFund == true, "Airline not yet available to sell insurance");
address passenger = msg.sender;
uint256 amount = msg.value;
uint256 payout = amount.mul(150).div(100);
flightSuretyData.buy(airline, passenger, flight, amount, payout);
emit BoughtInsurance(airline, passenger, flight, amount, payout);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight
(
)
external
pure
{
}
function payPassenger(address acc) public payable
{
require(msg.sender == tx.origin, "Contracts not allowed");
uint256 amount = flightSuretyData.pay(acc);
require(amount > 0, "Insufficient funds");
acc.transfer(amount);
emit PassengerPaid(acc, amount);
}
/**
* @dev Called after oracle has updated flight status
*
*/
function processFlightStatus
(
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
public
{
if (statusCode==STATUS_CODE_LATE_AIRLINE) {
address[] memory insurances = flightSuretyData.getInsurees(flight);
for(uint c=0; c<insurances.length; c++) {
(address _air, address pas, string memory _fli, uint256 _amo, uint256 payout, bool _open) = getInsurance(insurances[c]);
flightSuretyData.creditInsurees(pas,payout);
}
}
}
// Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
external
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
// Register an oracle with the contract
function registerOracle
(
)
external
payable
{
// Require registration fee
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({
isRegistered: true,
indexes: indexes
});
}
function getMyIndexes
(
)
view
external
returns(uint8[3])
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
processFlightStatus(airline, flight, timestamp, statusCode);
}
}
function getFlightKey
(
address airline,
string flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes
(
address account
)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex
(
address account
)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
contract FlightSuretyData {
function registerAirline(address airline) external;
function getVotes(address airline) external returns(uint8);
function addVotes(address airline, uint8 value) external;
function removeVotes(address airline) external;
function isQueued(address airline) external view returns(bool);
function buy(address airline, address passenger, string flight, uint256 amount, uint256 payout) external;
function getInsurance(address _passenger) external view returns(address airline, address passenger, string flight, uint256 amount, uint256 payout, bool open);
function getInsurees(string flight) public view returns(address[]);
function creditInsurees(address p, uint256 a) external view;
function getPayout(address a) external view returns(uint256);
function pay(address acount) external returns(uint256);
}
| Add an airline to the registration queue/ | function registerAirline
(
address airline
)
public
returns(bool success, uint256 votes)
{
require(airlines[msg.sender].isActive, "Caller is not active yet");
flightSuretyData.registerAirline(airline);
success = true;
return (success, 0);
}
| 5,350,280 |
pragma solidity ^0.4.24;
/*
* Wall Street Market presents......
.______ __ __ __ _______ ______ __ __ __ .______ _______ ___ .___ ___. _______
| _ \ | | | | | | | ____| / || | | | | | | _ \ / _____| / \ | \/ | | ____|
| |_) | | | | | | | | |__ | ,----'| |__| | | | | |_) | | | __ / ^ \ | \ / | | |__
| _ < | | | | | | | __| | | | __ | | | | ___/ | | |_ | / /_\ \ | |\/| | | __|
| |_) | | `----.| `--' | | |____ | `----.| | | | | | | | | |__| | / _____ \ | | | | | |____
|______/ |_______| \______/ |_______| \______||__| |__| |__| | _| \______| /__/ \__\ |__| |__| |_______|
(BCHIP)
website: https://wallstreetmarket.tk
discord: https://discord.gg/8AFP9gS
25% Dividends Fees/Payouts
5% of Buy In Fee Will Go into Buying Tokens from the contract for "THE 82" group until
400,000 tokens have been distributed. 25% Fee will apply for these transactions.
After this the 5% fee will be reserved for use in additional card and lending games using BCHIP tokens.
Referral Program pays out 33% of Buy-in/Sell Fees to user of masternode link
*/
contract AcceptsExchange {
BlueChipGame public tokenContract;
function AcceptsExchange(address _tokenContract) public {
tokenContract = BlueChipGame(_tokenContract);
}
modifier onlyTokenContract {
require(msg.sender == address(tokenContract));
_;
}
/**
* @dev Standard ERC677 function that will handle incoming token transfers.
*
* @param _from Token sender address.
* @param _value Amount of tokens.
* @param _data Transaction metadata.
*/
function tokenFallback(address _from, uint256 _value, bytes _data) external returns (bool);
function tokenFallbackExpanded(address _from, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool);
}
contract BlueChipGame {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
modifier notContract() {
require (msg.sender == tx.origin);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[_customerAddress]);
_;
}
modifier onlyActive(){
require(boolContractActive);
_;
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "BlueChipExchange";
string public symbol = "BCHIP";
uint8 constant public decimals = 18;
uint256 constant internal tokenPriceInitial_ = 0.00000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.000000001 ether;
uint256 constant internal magnitude = 2**64;
uint256 public totalEthFundRecieved; // total ETH Bond recieved from this contract
uint256 public totalEthFundCollected; // total ETH Bond collected in this contract
// proof of stake (defaults at 25 tokens)
uint256 public stakingRequirement = 25e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 2.5 ether;
uint256 constant internal ambassadorQuota_ = 2.5 ether;
uint constant internal total82Tokens = 390148;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
mapping(uint => address) internal theGroupofEightyTwo;
mapping(uint => uint) internal theGroupofEightyTwoAmount;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
uint8 public dividendFee_ = 20; // 20% dividend fee on each buy and sell
uint8 public fundFee_ = 0; // 5% bond fund fee on each buy and sell
uint8 public altFundFee_ = 5; // Fund fee rate on each buy and sell for future game
bool boolPay82 = false;
bool bool82Mode = true;
bool boolContractActive = true;
uint bondFund = 0;
// administrator list (see above on what they can do)
mapping(address => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
// Special Wall Street Market Platform control from scam game contracts on Wall Street Market platform
mapping(address => bool) public canAcceptTokens_; // contracts, which can accept Wall Street tokens
mapping(address => address) public stickyRef;
address public bondFundAddress = 0x1822435de9b923a7a8c4fbd2f6d0aa8f743d3010; //Bond Fund
address public altFundAddress = 0x1822435de9b923a7a8c4fbd2f6d0aa8f743d3010; //Alternate Fund for Future Game
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function BlueChipGame()
public
{
// add administrators here
administrators[msg.sender] = true;
//* Populate the 82 Mappings
theGroupofEightyTwo[1] = 0x41fe3738b503cbafd01c1fd8dd66b7fe6ec11b01;
theGroupofEightyTwo[2] = 0x96762288ebb2560a19f8eadaaa2012504f64278b;
theGroupofEightyTwo[3] = 0xc29a6dd21801e58566df9f003b7011e30724543e;
theGroupofEightyTwo[4] = 0xc63ea85cc823c440319013d4b30e19b66466642d;
theGroupofEightyTwo[5] = 0xc6f827796a2e1937fd7f97c4e0a4906c476794f6;
theGroupofEightyTwo[6] = 0xe74b1ea522b9d558c8e8719c3b1c4a9050b531ca;
theGroupofEightyTwo[7] = 0x6b90d498062140c607d03fd642377eeaa325703e;
theGroupofEightyTwo[8] = 0x5f1088110edcba27fc206cdcc326b413b5867361;
theGroupofEightyTwo[9] = 0xc92fd0e554b12eb10f584819eec2394a9a6f3d1d;
theGroupofEightyTwo[10] = 0xb62a0ac2338c227748e3ce16d137c6282c9870cf;
theGroupofEightyTwo[11] = 0x3f6c42409da6faf117095131168949ab81d5947d;
theGroupofEightyTwo[12] = 0xd54c47b3165508fb5418dbdec59a0d2448eeb3d7;
theGroupofEightyTwo[13] = 0x285d366834afaa8628226e65913e0dd1aa26b1f8;
theGroupofEightyTwo[14] = 0x285d366834afaa8628226e65913e0dd1aa26b1f8;
theGroupofEightyTwo[15] = 0x5f5996f9e1960655d6fc00b945fef90672370d9f;
theGroupofEightyTwo[16] = 0x3825c8ba07166f34ce9a2cd1e08a68b105c82cb9;
theGroupofEightyTwo[17] = 0x7f3e05b4f258e1c15a0ef49894cffa1d89ceb9d3;
theGroupofEightyTwo[18] = 0x3191acf877495e5f4e619ec722f6f38839182660;
theGroupofEightyTwo[19] = 0x14f981ec7b0f59df6e1c56502e272298f221d763;
theGroupofEightyTwo[20] = 0xae817ec70d8b621bb58a047e63c31445f79e20dc;
theGroupofEightyTwo[21] = 0xc43af3becac9c810384b69cf061f2d7ec73105c4;
theGroupofEightyTwo[22] = 0x0743469569ed5cc44a51216a1bf5ad7e7f90f40e;
theGroupofEightyTwo[23] = 0xff6a4d0ed374ba955048664d6ef5448c6cd1d56a;
theGroupofEightyTwo[24] = 0x62358a483311b3de29ae987b990e19de6259fa9c;
theGroupofEightyTwo[25] = 0xa0fea1bcfa32713afdb73b9908f6cb055022e95f;
theGroupofEightyTwo[26] = 0xb2af816608e1a4d0fb12b81028f32bac76256eba;
theGroupofEightyTwo[27] = 0x977193d601b364f38ab1a832dbaef69ca7833992;
theGroupofEightyTwo[28] = 0xed3547f0ed028361685b39cd139aa841df6629ab;
theGroupofEightyTwo[29] = 0xe40ff298079493cba637d92089e3d1db403974cb;
theGroupofEightyTwo[30] = 0xae3dc7fa07f9dd030fa56c027e90998ed9fe9d61;
theGroupofEightyTwo[31] = 0x2dd35e7a6f5fcc28d146c04be641f969f6d1e403;
theGroupofEightyTwo[32] = 0x2afe21ec5114339922d38546a3be7a0b871d3a0d;
theGroupofEightyTwo[33] = 0x6696fee394bb224d0154ea6b58737dca827e1960;
theGroupofEightyTwo[34] = 0xccdf159b1340a35c3567b669c836a88070051314;
theGroupofEightyTwo[35] = 0x1c3416a34c86f9ddcd05c7828bf5693308d19e0b;
theGroupofEightyTwo[36] = 0x846dedb19b105edafac2c9410fa2b5e73b596a14;
theGroupofEightyTwo[37] = 0x3e9294f9b01bc0bcb91413112c75c3225c65d0b3;
theGroupofEightyTwo[38] = 0x3a5ce61c74343dde474bad4210cccf1dac7b1934;
theGroupofEightyTwo[39] = 0x38e123f89a7576b2942010ad1f468cc0ea8f9f4b;
theGroupofEightyTwo[40] = 0xdcd8bad894035b5c554ad450ca84ae6be0b73122;
theGroupofEightyTwo[41] = 0xcfab320d4379a84fe3736eccf56b09916e35097b;
theGroupofEightyTwo[42] = 0x12f53c1d7caea0b41010a0e53d89c801ed579b5a;
theGroupofEightyTwo[43] = 0x5145a296e1bb9d4cf468d6d97d7b6d15700f39ef;
theGroupofEightyTwo[44] = 0xac707a1b4396a309f4ad01e3da4be607bbf14089;
theGroupofEightyTwo[45] = 0x38602d1446fe063444b04c3ca5ecde0cba104240;
theGroupofEightyTwo[46] = 0xc951d3463ebba4e9ec8ddfe1f42bc5895c46ec8f;
theGroupofEightyTwo[47] = 0x69e566a65d00ad5987359db9b3ced7e1cfe9ac69;
theGroupofEightyTwo[48] = 0x533b14f6d04ed3c63a68d5e80b7b1f6204fb4213;
theGroupofEightyTwo[49] = 0x5fa0b03bee5b4e6643a1762df718c0a4a7c1842f;
theGroupofEightyTwo[50] = 0xb74d5f0a81ce99ac1857133e489bc2b4954935ff;
theGroupofEightyTwo[51] = 0xc371117e0adfafe2a3b7b6ba71b7c0352ca7789d;
theGroupofEightyTwo[52] = 0xcade49e583bc226f19894458f8e2051289f1ac85;
theGroupofEightyTwo[53] = 0xe3fc95aba6655619db88b523ab487d5273db484f;
theGroupofEightyTwo[54] = 0x22e4d1433377a2a18452e74fd4ba9eea01824f7d;
theGroupofEightyTwo[55] = 0x32ae5eff81881a9a70fcacada5bb1925cabca508;
theGroupofEightyTwo[56] = 0xb864d177c291368b52a63a95eeff36e3731303c1;
theGroupofEightyTwo[57] = 0x46091f77b224576e224796de5c50e8120ad7d764;
theGroupofEightyTwo[58] = 0xc6407dd687a179aa11781b8a1e416bd0515923c2;
theGroupofEightyTwo[59] = 0x2502ce06dcb61ddf5136171768dfc08d41db0a75;
theGroupofEightyTwo[60] = 0x6b80ca9c66cdcecc39893993df117082cc32bb16;
theGroupofEightyTwo[61] = 0xa511ddba25ffd74f19a400fa581a15b5044855ce;
theGroupofEightyTwo[62] = 0xce81d90ae52d34588a95db59b89948c8fec487ce;
theGroupofEightyTwo[63] = 0x6d60dbf559bbf0969002f19979cad909c2644dad;
theGroupofEightyTwo[64] = 0x45101255a2bcad3175e6fda4020a9b77e6353a9a;
theGroupofEightyTwo[65] = 0xe9078d7539e5eac3b47801a6ecea8a9ec8f59375;
theGroupofEightyTwo[66] = 0x41a21b264f9ebf6cf571d4543a5b3ab1c6bed98c;
theGroupofEightyTwo[67] = 0x471e8d970c30e61403186b6f245364ae790d14c3;
theGroupofEightyTwo[68] = 0x6eb7f74ff7f57f7ba45ca71712bccef0588d8f0d;
theGroupofEightyTwo[69] = 0xe6d6bc079d76dc70fcec5de84721c7b0074d164b;
theGroupofEightyTwo[70] = 0x3ec5972c2177a08fd5e5f606f19ab262d28ceffe;
theGroupofEightyTwo[71] = 0x108b87a18877104e07bd870af70dfc2487447262;
theGroupofEightyTwo[72] = 0x3129354440e4639d2b809ca03d4ccc6277ac8167;
theGroupofEightyTwo[73] = 0x21572b6a855ee8b1392ed1003ecf3474fa83de3e;
theGroupofEightyTwo[74] = 0x75ab98f33a7a60c4953cb907747b498e0ee8edf7;
theGroupofEightyTwo[75] = 0x0fe6967f9a5bb235fc74a63e3f3fc5853c55c083;
theGroupofEightyTwo[76] = 0x49545640b9f3266d13cce842b298d450c0f8d776;
theGroupofEightyTwo[77] = 0x9327128ead2495f60d41d3933825ffd8080d4d42;
theGroupofEightyTwo[78] = 0x82b4e53a7d6bf6c72cc57f8d70dae90a34f0870f;
theGroupofEightyTwo[79] = 0xb74d5f0a81ce99ac1857133e489bc2b4954935ff;
theGroupofEightyTwo[80] = 0x3749d556c167dd73d536a6faaf0bb4ace8f7dab9;
theGroupofEightyTwo[81] = 0x3039f6857071692b540d9e1e759a0add93af3fed;
theGroupofEightyTwo[82] = 0xb74d5f0a81ce99ac1857133e489bc2b4954935ff;
theGroupofEightyTwo[83] = 0x13015632fa722C12E862fF38c8cF2354cbF26c47; //This one is for testing
theGroupofEightyTwoAmount[1] = 100000;
theGroupofEightyTwoAmount[2] = 30000;
theGroupofEightyTwoAmount[3] = 24400;
theGroupofEightyTwoAmount[4] = 21111;
theGroupofEightyTwoAmount[5] = 14200;
theGroupofEightyTwoAmount[6] = 13788;
theGroupofEightyTwoAmount[7] = 12003;
theGroupofEightyTwoAmount[8] = 11000;
theGroupofEightyTwoAmount[9] = 11000;
theGroupofEightyTwoAmount[10] = 8800;
theGroupofEightyTwoAmount[11] = 7000;
theGroupofEightyTwoAmount[12] = 7000;
theGroupofEightyTwoAmount[13] = 6000;
theGroupofEightyTwoAmount[14] = 5400;
theGroupofEightyTwoAmount[15] = 5301;
theGroupofEightyTwoAmount[16] = 5110;
theGroupofEightyTwoAmount[17] = 5018;
theGroupofEightyTwoAmount[18] = 5000;
theGroupofEightyTwoAmount[19] = 5000;
theGroupofEightyTwoAmount[20] = 5000;
theGroupofEightyTwoAmount[21] = 5000;
theGroupofEightyTwoAmount[22] = 4400;
theGroupofEightyTwoAmount[23] = 4146;
theGroupofEightyTwoAmount[24] = 4086;
theGroupofEightyTwoAmount[25] = 4000;
theGroupofEightyTwoAmount[26] = 4000;
theGroupofEightyTwoAmount[27] = 3500;
theGroupofEightyTwoAmount[28] = 3216;
theGroupofEightyTwoAmount[29] = 3200;
theGroupofEightyTwoAmount[30] = 3183;
theGroupofEightyTwoAmount[31] = 3100;
theGroupofEightyTwoAmount[32] = 3001;
theGroupofEightyTwoAmount[33] = 2205;
theGroupofEightyTwoAmount[34] = 2036;
theGroupofEightyTwoAmount[35] = 2000;
theGroupofEightyTwoAmount[36] = 2000;
theGroupofEightyTwoAmount[37] = 1632;
theGroupofEightyTwoAmount[38] = 1600;
theGroupofEightyTwoAmount[39] = 1500;
theGroupofEightyTwoAmount[40] = 1500;
theGroupofEightyTwoAmount[41] = 1478;
theGroupofEightyTwoAmount[42] = 1300;
theGroupofEightyTwoAmount[43] = 1200;
theGroupofEightyTwoAmount[44] = 1127;
theGroupofEightyTwoAmount[45] = 1050;
theGroupofEightyTwoAmount[46] = 1028;
theGroupofEightyTwoAmount[47] = 1011;
theGroupofEightyTwoAmount[48] = 1000;
theGroupofEightyTwoAmount[49] = 1000;
theGroupofEightyTwoAmount[50] = 1000;
theGroupofEightyTwoAmount[51] = 1000;
theGroupofEightyTwoAmount[52] = 1000;
theGroupofEightyTwoAmount[53] = 1000;
theGroupofEightyTwoAmount[54] = 983;
theGroupofEightyTwoAmount[55] = 980;
theGroupofEightyTwoAmount[56] = 960;
theGroupofEightyTwoAmount[57] = 900;
theGroupofEightyTwoAmount[58] = 900;
theGroupofEightyTwoAmount[59] = 839;
theGroupofEightyTwoAmount[60] = 800;
theGroupofEightyTwoAmount[61] = 800;
theGroupofEightyTwoAmount[62] = 800;
theGroupofEightyTwoAmount[63] = 798;
theGroupofEightyTwoAmount[64] = 750;
theGroupofEightyTwoAmount[65] = 590;
theGroupofEightyTwoAmount[66] = 500;
theGroupofEightyTwoAmount[67] = 500;
theGroupofEightyTwoAmount[68] = 500;
theGroupofEightyTwoAmount[69] = 500;
theGroupofEightyTwoAmount[70] = 415;
theGroupofEightyTwoAmount[71] = 388;
theGroupofEightyTwoAmount[72] = 380;
theGroupofEightyTwoAmount[73] = 300;
theGroupofEightyTwoAmount[74] = 300;
theGroupofEightyTwoAmount[75] = 170;
theGroupofEightyTwoAmount[76] = 164;
theGroupofEightyTwoAmount[77] = 142;
theGroupofEightyTwoAmount[78] = 70;
theGroupofEightyTwoAmount[79] = 69;
theGroupofEightyTwoAmount[80] = 16;
theGroupofEightyTwoAmount[81] = 5;
theGroupofEightyTwoAmount[82] = 1;
theGroupofEightyTwoAmount[83] = 1; //This one is for testing
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
onlyActive()
returns(uint256)
{
require(tx.gasprice <= 0.05 szabo);
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
onlyActive()
{
require(tx.gasprice <= 0.05 szabo);
if (boolPay82) { //Add to the Eth Fund if boolPay82 set to true
totalEthFundCollected = SafeMath.add(totalEthFundCollected, msg.value);
} else{
purchaseTokens(msg.value, 0x0);
}
}
function buyTokensfor82()
public
onlyAdministrator()
{
//Periodically Use the Bond Fund to buy tokens and distribute to the Group of 82
if(bool82Mode)
{
uint counter = 83;
uint _ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, _ethToPay);
while (counter > 0) {
uint _distAmountLocal = SafeMath.div(SafeMath.mul(_ethToPay, theGroupofEightyTwoAmount[counter]),total82Tokens);
purchaseTokensfor82(_distAmountLocal, 0x0, counter);
counter = counter - 1;
}
}
}
/**
* Sends Bondf Fund ether to the bond contract
*
*/
function payFund() payable public
onlyAdministrator()
{
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
require(ethToPay > 1);
uint256 _altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,altFundFee_),100);
uint256 _bondEthToPay = SafeMath.div(SafeMath.mul(ethToPay,fundFee_),100);
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);
if(_bondEthToPay > 0){
if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay);
}
}
if(_altEthToPay > 0){
if(!altFundAddress.call.value(_altEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _altEthToPay);
}
}
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_ + altFundFee_), 100);
uint256 _refPayout = _dividends / 3;
_dividends = SafeMath.sub(_dividends, _refPayout);
(_dividends,) = handleRef(stickyRef[msg.sender], _refPayout, _dividends, 0);
// Take out dividends and then _fundPayout
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
// Add ethereum to send to fund
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* REMEMBER THIS IS 0% TRANSFER FEE
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens);
// fire event
Transfer(_customerAddress, _toAddress, _amountOfTokens);
// ERC20
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
*/
function transferAndCall(address _to, uint256 _value, bytes _data) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Wall Street Exchange platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsExchange receiver = AcceptsExchange(_to);
require(receiver.tokenFallback(msg.sender, _value, _data));
}
return true;
}
/**
* Transfer token to a specified address and forward the data to recipient
* ERC-677 standard
* https://github.com/ethereum/EIPs/issues/677
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
* @param _data Transaction metadata.
* We add ability to track the initial sender so we pass that to determine the bond holder
*/
function transferAndCallExpanded(address _to, uint256 _value, bytes _data, address _sender, address _referrer) external returns (bool) {
require(_to != address(0));
require(canAcceptTokens_[_to] == true); // security check that contract approved by Wall Street Exchange platform
require(transfer(_to, _value)); // do a normal token transfer to the contract
if (isContract(_to)) {
AcceptsExchange receiver = AcceptsExchange(_to);
require(receiver.tokenFallbackExpanded(msg.sender, _value, _data, msg.sender, _referrer));
}
return true;
}
/**
* Additional check that the game address we are sending tokens to is a contract
* assemble the given address bytecode. If bytecode exists then the _addr is a contract.
*/
function isContract(address _addr) private constant returns (bool is_contract) {
// retrieve the size of the code on target address, this needs assembly
uint length;
assembly { length := extcodesize(_addr) }
return length > 0;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
//function disableInitialStage()
// onlyAdministrator()
// public
//{
// onlyAmbassadors = false;
//}
function setBondFundAddress(address _newBondFundAddress)
onlyAdministrator()
public
{
bondFundAddress = _newBondFundAddress;
}
function setAltFundAddress(address _newAltFundAddress)
onlyAdministrator()
public
{
altFundAddress = _newAltFundAddress;
}
/**
* Set fees/rates
*/
function setFeeRates(uint8 _newDivRate, uint8 _newFundFee, uint8 _newAltRate)
onlyAdministrator()
public
{
require(_newDivRate <= 25);
require(_newAltRate + _newFundFee <= 5);
dividendFee_ = _newDivRate;
fundFee_ = _newFundFee;
altFundFee_ = _newAltRate;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(address _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* Add or remove game contract, which can accept Wall Street Market tokens
*/
function setCanAcceptTokens(address _address, bool _value)
onlyAdministrator()
public
{
canAcceptTokens_[_address] = _value;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/**
* Set if we will pay the 82 group with funds in
*/
function setBool82(bool _bool)
onlyAdministrator()
public
{
boolPay82 = _bool;
}
/**
*Set if we will use 5% fund to purchase new tokens for 82 group
*/
function set82Mode(bool _bool)
onlyAdministrator()
public
{
bool82Mode = _bool;
}
/**
*Set flag for contract to accept ether
*/
function setContractActive(bool _bool)
onlyAdministrator()
public
{
boolContractActive = _bool;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return this.balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_ + altFundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_ + altFundFee_), 100);
uint256 _taxedEthereum = SafeMath.add(SafeMath.add(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereumToSpend, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereumToSpend, fundFee_ + altFundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereumToSpend, _dividends), _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(SafeMath.mul(_ethereum, dividendFee_), 100);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_ethereum, fundFee_ + altFundFee_), 100);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_ethereum, _dividends), _fundPayout);
return _taxedEthereum;
}
/**
* Function for the frontend to show ether waiting to be send to fund in contract
*/
function etherToSendFund()
public
view
returns(uint256) {
return SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
// Make sure we will send back excess if user sends more then 5 ether before 10 ETH in contract
function purchaseInternal(uint256 _incomingEthereum, address _referredBy)
notContract()// no contracts allowed
internal
returns(uint256) {
uint256 purchaseEthereum = _incomingEthereum;
uint256 excess;
if(purchaseEthereum > 2.5 ether) { // check if the transaction is over 2.5 ether
if (SafeMath.sub(address(this).balance, purchaseEthereum) <= 10 ether) { // if so check the contract is less then 100 ether
purchaseEthereum = 2.5 ether;
excess = SafeMath.sub(_incomingEthereum, purchaseEthereum);
}
}
purchaseTokens(purchaseEthereum, _referredBy);
if (excess > 0) {
msg.sender.transfer(excess);
}
}
function handleRef(address _ref, uint _referralBonus, uint _currentDividends, uint _currentFee) internal returns (uint, uint){
uint _dividends = _currentDividends;
uint _fee = _currentFee;
address _referredBy = stickyRef[msg.sender];
if (_referredBy == address(0x0)){
_referredBy = _ref;
}
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != msg.sender &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
if (stickyRef[msg.sender] == address(0x0)){
stickyRef[msg.sender] = _referredBy;
}
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus/2);
address currentRef = stickyRef[_referredBy];
if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){
referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*3);
currentRef = stickyRef[currentRef];
if (currentRef != address(0x0) && tokenBalanceLedger_[currentRef] >= stakingRequirement){
referralBalance_[currentRef] = SafeMath.add(referralBalance_[currentRef], (_referralBonus/10)*2);
}
else{
_dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2 - (_referralBonus/10)*3);
_fee = _dividends * magnitude;
}
}
else{
_dividends = SafeMath.add(_dividends, _referralBonus - _referralBonus/2);
_fee = _dividends * magnitude;
}
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
return (_dividends, _fee);
}
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_ + altFundFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _fee;
(_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout);
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[msg.sender] = SafeMath.add(tokenBalanceLedger_[msg.sender], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[msg.sender] += _updatedPayouts;
// fire event
onTokenPurchase(msg.sender, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
//*Seperate function to handle internal purchases for the 82 Group
function purchaseTokensfor82(uint256 _incomingEthereum, address _referredBy, uint _playerIndex)
internal
returns(uint256)
{
// data setup
uint256 _undividedDividends = SafeMath.div(SafeMath.mul(_incomingEthereum, dividendFee_), 100);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _fundPayout = SafeMath.div(SafeMath.mul(_incomingEthereum, fundFee_ + altFundFee_), 100);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _fee;
(_dividends, _fee) = handleRef(_referredBy, _referralBonus, _dividends, _fee);
uint256 _taxedEthereum = SafeMath.sub(SafeMath.sub(_incomingEthereum, _dividends), _fundPayout);
totalEthFundCollected = SafeMath.add(totalEthFundCollected, _fundPayout);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[theGroupofEightyTwo[_playerIndex]] = SafeMath.add(tokenBalanceLedger_[theGroupofEightyTwo[_playerIndex]], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[theGroupofEightyTwo[_playerIndex]] += _updatedPayouts;
// fire event
onTokenPurchase(theGroupofEightyTwo[_playerIndex], _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | Sends Bondf Fund ether to the bond contract/ | {
uint256 ethToPay = SafeMath.sub(totalEthFundCollected, totalEthFundRecieved);
require(ethToPay > 1);
uint256 _altEthToPay = SafeMath.div(SafeMath.mul(ethToPay,altFundFee_),100);
uint256 _bondEthToPay = SafeMath.div(SafeMath.mul(ethToPay,fundFee_),100);
totalEthFundRecieved = SafeMath.add(totalEthFundRecieved, ethToPay);
function payFund() payable public
onlyAdministrator()
if(_bondEthToPay > 0){
if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay);
}
}
function payFund() payable public
onlyAdministrator()
if(_bondEthToPay > 0){
if(!bondFundAddress.call.value(_bondEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _bondEthToPay);
}
}
if(_altEthToPay > 0){
if(!altFundAddress.call.value(_altEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _altEthToPay);
}
}
if(_altEthToPay > 0){
if(!altFundAddress.call.value(_altEthToPay).gas(400000)()) {
totalEthFundRecieved = SafeMath.sub(totalEthFundRecieved, _altEthToPay);
}
}
}
| 1,798,617 |
pragma solidity 0.5.17;
import "../../other/1inch.sol";
import "../../other/reetrancy.sol";
import "../../other/Initializable.sol";
interface IOracle{
function getiTokenDetails(uint _poolIndex) external returns(string memory, string memory,string memory);
function getTokenDetails(uint _poolIndex) external returns(address[] memory,uint[] memory,uint ,uint);
}
interface Iitokendeployer{
function createnewitoken(string calldata _name, string calldata _symbol) external returns(address);
}
interface Iitoken{
function mint(address account, uint256 amount) external returns (bool);
function burn(address account, uint256 amount) external returns (bool);
function balanceOf(address account) external view returns (uint256);
function totalSupply() external view returns (uint256);
}
interface IMAsterChef{
function depositFromDaaAndDAO(uint256 _pid, uint256 _amount, uint256 vault, address _sender,bool isPremium) external;
function distributeExitFeeShare(uint256 _amount) external;
}
interface IPoolConfiguration{
function checkDao(address daoAddress) external returns(bool);
function getperformancefees() external view returns(uint256);
function getmaxTokenSupported() external view returns(uint256);
function getslippagerate() external view returns(uint256);
function getoracleaddress() external view returns(address);
function getEarlyExitfees() external view returns(uint256);
function checkStableCoin(address _stable) external view returns(bool);
}
contract PoolV1 is ReentrancyGuard,Initializable {
using SafeMath for uint;
using SafeERC20 for IERC20;
address public constant ETH_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
// Kovan addresses
// address public EXCHANGE_CONTRACT = 0x5e676a2Ed7CBe15119EBe7E96e1BB0f3d157206F;
// address public WETH_ADDRESS = 0x7816fBBEd2C321c24bdB2e2477AF965Efafb7aC0;
// address public baseStableCoin = 0xc6196e00Fd2970BD91777AADd387E08574cDf92a;
// Mainnet Addresses
address public EXCHANGE_CONTRACT = 0x50FDA034C0Ce7a8f7EFDAebDA7Aa7cA21CC1267e;
address public WETH_ADDRESS = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address public baseStableCoin = 0x6B175474E89094C44Da98b954EedeAC495271d0F;
// ASTRA token Address
address public ASTRTokenAddress;
// Manager Account Address
address public managerAddresses;
// Pool configuration contract address. This contract manage the configuration for this contract.
address public _poolConf;
// Chef contract address for staking
address public poolChef;
// Address of itoken deployer. This will contract will be responsible for deploying itokens.
address public itokendeployer;
// Structure for storing the pool details
struct PoolInfo {
// Array for token addresses.
address[] tokens;
// Weight for each token. Share is calculated by dividing the weight with total weight.
uint256[] weights;
// Total weight. Sum of all the weight in array.
uint256 totalWeight;
// Check if pool is active or not
bool active;
// Next rebalance time for pool/index in unix timestamp
uint256 rebaltime;
// Threshold value. Minimum value after that pool will start buying token
uint256 threshold;
// Number of rebalance performed on this pool.
uint256 currentRebalance;
// Unix timeseamp for the last rebalance time
uint256 lastrebalance;
// itoken Created address
address itokenaddr;
// Owner address for owner
address owner;
//description for token
string description;
}
struct PoolUser
{
// Balance of user in pool
uint256 currentBalance;
// Number of rebalance pupto which user account is synced
uint256 currentPool;
// Pending amount for which no tokens are bought
uint256 pendingBalance;
// Total amount deposited in stable coin.
uint256 USDTdeposit;
// ioktne balance for that pool. This will tell the total itoken balance either staked at chef or hold at account.
uint256 Itokens;
// Check id user account is active
bool active;
// Check if user account is whitelisted or not.
bool isenabled;
}
// Mapping for user infor based on the structure created above.
mapping ( uint256 =>mapping(address => PoolUser)) public poolUserInfo;
// Array for storing indices details
PoolInfo[] public poolInfo;
// Private array variable use internally by functions.
uint256[] private buf;
// address[] private _Tokens;
// uint256[] private _Values;
address[] private _TokensStable;
uint256[] private _ValuesStable;
// Mapping to show the token balance for a particular pool.
mapping(uint256 => mapping(address => uint256)) public tokenBalances;
// Store the tota pool balance
mapping(uint256 => uint256) public totalPoolbalance;
// Store the pending balance for which tokens are not bought.
mapping(uint256 => uint256) public poolPendingbalance;
//Track the initial block where user deposit amount.
mapping(address =>mapping (uint256 => uint256)) public initialDeposit;
//Check if user already exist or not.
mapping(address =>mapping (uint256 => bool)) public existingUser;
bool public active = true;
mapping(address => bool) public systemAddresses;
/**
* @dev Modifier to check if the called is Admin or not.
*/
modifier systemOnly {
require(systemAddresses[msg.sender], "EO1");
_;
}
// Event emitted
event Transfer(address indexed src, address indexed dst, uint wad);
event Withdrawn(address indexed from, uint value);
event WithdrawnToken(address indexed from, address indexed token, uint amount);
/**
* Error code:
* EO1: system only
* E02: Invalid Pool Index
* E03: Already whitelisted
* E04: Only manager can whitelist
* E05: Only owner can whitelist
* E06: Invalid config length
* E07: Only whitelisted user
* E08: Only one token allowed
* E09: Deposit some amount
* E10: Only stable coins
* E11: Not enough tokens
* E12: Rebalnce time not reached
* E13: Only owner can update the public pool
* E14: No balance in Pool
* E15: Zero address
* E16: More than allowed token in indices
*/
function initialize(address _ASTRTokenAddress, address poolConfiguration,address _itokendeployer, address _chef) public initializer{
require(_ASTRTokenAddress != address(0), "E15");
require(poolConfiguration != address(0), "E15");
require(_itokendeployer != address(0), "E15");
require(_chef != address(0), "E15");
ReentrancyGuard.__init();
systemAddresses[msg.sender] = true;
ASTRTokenAddress = _ASTRTokenAddress;
managerAddresses = msg.sender;
_poolConf = poolConfiguration;
itokendeployer = _itokendeployer;
poolChef = _chef;
}
/**
* @notice White users address
* @param _address Account that needs to be whitelisted.
* @param _poolIndex Pool Index in which user wants to invest.
* @dev Whitelist users for deposit on pool. Without this user will not be able to deposit.
*/
function whitelistaddress(address _address, uint _poolIndex) external {
// Check if pool configuration is correct or not
require(_address != address(0), "E15");
require(_poolIndex<poolInfo.length, "E02");
require(!poolUserInfo[_poolIndex][_address].active,"E03");
// Only pool manager can whitelist users
if(poolInfo[_poolIndex].owner == address(this)){
require(managerAddresses == msg.sender, "E04");
}else{
require(poolInfo[_poolIndex].owner == msg.sender, "E05");
}
// Create new object for user.
PoolUser memory newPoolUser = PoolUser(0, poolInfo[_poolIndex].currentRebalance,0,0,0,true,true);
poolUserInfo[_poolIndex][_address] = newPoolUser;
}
function calculateTotalWeight(uint[] memory _weights) internal view returns(uint){
uint _totalWeight;
// Calculate total weight for new index.
for(uint i = 0; i < _weights.length; i++) {
_totalWeight = _totalWeight.add(_weights[i]);
}
return _totalWeight;
}
/**
* @notice Add public pool
* @param _tokens tokens to purchase in pool.
* @param _weights Weight of new tokens.
* @param _threshold Threshold amount to purchase token.
* @param _rebalanceTime Next Rebalance time.
* @param _name itoken name.
* @param _symbol itoken symbol.
* @dev Add new public pool by any users.Here any users can add there custom pools
*/
function addPublicPool(address[] memory _tokens, uint[] memory _weights,uint _threshold,uint _rebalanceTime,string memory _name,string memory _symbol,string memory _description) public{
//Currently it will only check if configuration is correct as staking amount is not decided to add the new pool.
address _itokenaddr;
address _poolOwner;
uint _poolIndex = poolInfo.length;
address _OracleAddress = IPoolConfiguration(_poolConf).getoracleaddress();
if(_tokens.length == 0){
require(systemAddresses[msg.sender], "EO1");
(_tokens, _weights,_threshold,_rebalanceTime) = IOracle(_OracleAddress).getTokenDetails(_poolIndex);
// Get the new itoken name and symbol from pool
(_name,_symbol,_description) = IOracle(_OracleAddress).getiTokenDetails(_poolIndex);
_poolOwner = address(this);
}else{
_poolOwner = msg.sender;
}
require (_tokens.length == _weights.length, "E06");
require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16");
// Deploy new itokens
_itokenaddr = Iitokendeployer(itokendeployer).createnewitoken(_name, _symbol);
// Add new index.
poolInfo.push(PoolInfo({
tokens : _tokens,
weights : _weights,
totalWeight : calculateTotalWeight(_weights),
active : true,
rebaltime : _rebalanceTime,
currentRebalance : 0,
threshold: _threshold,
lastrebalance: block.timestamp,
itokenaddr: _itokenaddr,
owner: _poolOwner,
description:_description
}));
}
/**
* @notice Internal function to Buy Astra Tokens.
* @param _Amount Amount of Astra token to buy.
* @dev Buy Astra Tokens if user want to pay fees early exit fees by deposit in Astra
*/
function buyAstraToken(uint _Amount) internal returns(uint256){
uint _amount;
uint[] memory _distribution;
IERC20(baseStableCoin).approve(EXCHANGE_CONTRACT, _Amount);
// Get the expected amount of Astra you will recieve for the stable coin.
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, 2, 0);
uint256 minReturn = calculateMinimumReturn(_amount);
// Swap the stabe coin for Astra
IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(baseStableCoin), IERC20(ASTRTokenAddress), _Amount, minReturn, _distribution, 0);
return _amount;
}
/**
* @notice Stake Astra Tokens.
* @param _amount Amount of Astra token to stake.
* @dev Stake Astra tokens for various functionality like Staking.
*/
function stakeAstra(uint _amount,bool premium)internal{
//Approve the astra amount to stake.
IERC20(ASTRTokenAddress).approve(address(poolChef),_amount);
// Stake the amount on chef contract. It will be staked for 6 months by default 0 pool id will be for the astra pool.
IMAsterChef(poolChef).depositFromDaaAndDAO(0,_amount,6,msg.sender,premium);
}
/**
* @notice Calculate Fees.
* @param _account User account.
* @param _amount Amount user wants to withdraw.
* @param _poolIndex Pool Index
* @dev Calculate Early Exit fees
* feeRate = Early Exit fee rate (Const 2%)
* startBlock = Deposit block
* withdrawBlock = Withdrawal block
* n = number of blocks between n1 and n2
* Averageblockperday = Average block per day (assumed: 6500)
* feeconstant =early exit fee cool down period (const 182)
* Wv = withdrawal value
* EEFv = Wv x EEFr - (EEFr x n/ABPx t)
* If EEFv <=0 then EEFv = 0
*/
function calculatefee(address _account, uint _amount,uint _poolIndex)internal returns(uint256){
// Calculate the early eit fees based on the formula mentioned above.
uint256 feeRate = IPoolConfiguration(_poolConf).getEarlyExitfees();
uint256 startBlock = initialDeposit[_account][_poolIndex];
uint256 withdrawBlock = block.number;
uint256 Averageblockperday = 6500;
uint256 feeconstant = 182;
uint256 blocks = withdrawBlock.sub(startBlock);
uint feesValue = feeRate.mul(blocks).div(100);
feesValue = feesValue.div(Averageblockperday).div(feeconstant);
feesValue = _amount.mul(feeRate).div(100).sub(feesValue);
return feesValue;
}
/**
* @notice Buy Tokens.
* @param _poolIndex Pool Index.
* @dev Buy token initially once threshold is reached this can only be called by poolIn function
*/
function buytokens(uint _poolIndex) internal {
// Check if pool configuration is correct or not.
// This function is called inernally when user deposit in pool or during rebalance to purchase the tokens for given stable coin amount.
require(_poolIndex<poolInfo.length, "E02");
address[] memory returnedTokens;
uint[] memory returnedAmounts;
uint ethValue = poolPendingbalance[_poolIndex];
uint[] memory buf3;
buf = buf3;
// Buy tokens for the pending stable amount
(returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, poolInfo[_poolIndex].tokens, poolInfo[_poolIndex].weights, poolInfo[_poolIndex].totalWeight,buf);
// After tokens are purchased update its details in mapping.
for (uint i = 0; i < returnedTokens.length; i++) {
tokenBalances[_poolIndex][returnedTokens[i]] = tokenBalances[_poolIndex][returnedTokens[i]].add(returnedAmounts[i]);
}
// Update the pool details for the purchased tokens
totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].add(ethValue);
poolPendingbalance[_poolIndex] = 0;
if (poolInfo[_poolIndex].currentRebalance == 0){
poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1);
}
}
/**
* @param _amount Amount of user to Update.
* @param _poolIndex Pool Index.
* @dev Update user Info at the time of deposit in pool
*/
function updateuserinfo(uint _amount,uint _poolIndex) internal {
// Update the user details in mapping. This function is called internally when user deposit in pool or withdraw from pool.
if(poolUserInfo[_poolIndex][msg.sender].active){
// Check if user account is synced with latest rebalance or not. In case not it will update its details.
if(poolUserInfo[_poolIndex][msg.sender].currentPool < poolInfo[_poolIndex].currentRebalance){
poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance);
poolUserInfo[_poolIndex][msg.sender].currentPool = poolInfo[_poolIndex].currentRebalance;
poolUserInfo[_poolIndex][msg.sender].pendingBalance = _amount;
}
else{
poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.add(_amount);
}
}
}
/**
* @dev Get the Token details in Index pool.
*/
function getIndexTokenDetails(uint _poolIndex) external view returns(address[] memory){
return (poolInfo[_poolIndex].tokens);
}
/**
* @dev Get the Token weight details in Index pool.
*/
function getIndexWeightDetails(uint _poolIndex) external view returns(uint[] memory){
return (poolInfo[_poolIndex].weights);
}
/**
@param _amount Amount to chec for slippage.
* @dev Function to calculate the Minimum return for slippage
*/
function calculateMinimumReturn(uint _amount) internal view returns (uint){
// This will get the slippage rate from configuration contract and calculate how much amount user can get after slippage.
uint256 sliprate= IPoolConfiguration(_poolConf).getslippagerate();
uint rate = _amount.mul(sliprate).div(100);
// Return amount after calculating slippage
return _amount.sub(rate);
}
/**
* @dev Get amount of itoken to be received.
* Iv = index value
* Pt = total iTokens outstanding
* Dv = deposit USDT value
* DPv = total USDT value in the pool
* pTR = iTokens received
* If Iv = 0 then pTR = DV
* If pt > 0 then pTR = (Dv/Iv)* Pt
*/
function getItokenValue(uint256 outstandingValue, uint256 indexValue, uint256 depositValue, uint256 totalDepositValue) public view returns(uint256){
// Get the itoken value based on the pool value and total itokens. This method is used in pool In.
// outstandingValue is total itokens.
// Index value is pool current value.
// deposit value is stable coin amount user will deposit
// totalDepositValue is total stable coin value deposited over the pool.
if(indexValue == uint(0)){
return depositValue;
}else if(outstandingValue>0){
return depositValue.mul(outstandingValue).div(indexValue);
}
else{
return depositValue;
}
}
/**
* @dev Deposit in Indices pool either public pool or pool created by Astra.
* @param _tokens Token in which user want to give the amount. Currenly ony Stable stable coin is used.
* @param _values Amount to spend.
* @param _poolIndex Pool Index in which user wants to invest.
*/
function poolIn(address[] calldata _tokens, uint[] calldata _values, uint _poolIndex) external payable nonReentrant {
// Require conditions to check if user is whitelisted or check the token configuration which user is depositing
// Only stable coin and Ether can be used in the initial stages.
require(poolUserInfo[_poolIndex][msg.sender].isenabled, "E07");
require(_poolIndex<poolInfo.length, "E02");
require(_tokens.length <2 && _values.length<2, "E08");
// Check if is the first deposit or user already deposit before this. It will be used to calculate early exit fees
if(!existingUser[msg.sender][_poolIndex]){
existingUser[msg.sender][_poolIndex] = true;
initialDeposit[msg.sender][_poolIndex] = block.number;
}
// Variable that are used internally for logic/calling other functions.
uint ethValue;
uint fees;
uint stableValue;
address[] memory returnedTokens;
uint[] memory returnedAmounts;
//Global variable mainted to push values in it. Now we are removing the any value that are stored prior to this.
_TokensStable = returnedTokens;
_ValuesStable = returnedAmounts;
//Check if give token length is greater than 0 or not.
// If it is zero then user should deposit in ether.
// Other deposit in stable coin
if(_tokens.length == 0) {
// User must deposit some amount in pool
require (msg.value > 0.001 ether, "E09");
// Swap the ether with stable coin.
ethValue = msg.value;
_TokensStable.push(baseStableCoin);
_ValuesStable.push(1);
(returnedTokens, returnedAmounts) = swap(ETH_ADDRESS, ethValue, _TokensStable, _ValuesStable, 1);
stableValue = returnedAmounts[0];
} else {
// //Check if the entered address in the parameter of stable coin or not.
// bool checkaddress = (address(_tokens[0]) == address(baseStableCoin));
// // Check if user send some stable amount and user account has that much stable coin balance
// require(checkaddress,"poolIn: Can only submit Stable coin");
// require(msg.value == 0, "poolIn: Submit one token at a time");
require(IPoolConfiguration(_poolConf).checkStableCoin(_tokens[0]) == true,"E10");
require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "E11");
if(address(_tokens[0]) == address(baseStableCoin)){
stableValue = _values[0];
//Transfer the stable coin from users addresses to contract address.
IERC20(baseStableCoin).safeTransferFrom(msg.sender,address(this),stableValue);
}else{
IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]);
stableValue = sellTokensForStable(_tokens, _values);
}
require(stableValue > 0.001 ether,"E09");
}
// else{
// require(supportedStableCoins[_tokens[0]] == true,"poolIn: Can only submit Stable coin");
// // require(IERC20(_tokens[0]).balanceOf(msg.sender) >= _values[0], "poolIn: Not enough tokens");
// IERC20(_tokens[0]).safeTransferFrom(msg.sender,address(this),_values[0]);
// stableValue = sellTokensForStable(_tokens, _values);
// }
// Get the value of itoken to mint.
uint256 ItokenValue = getItokenValue(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply(), getPoolValue(_poolIndex), stableValue, totalPoolbalance[_poolIndex]);
//Update the balance initially as the pending amount. Once the tokens are purchased it will be updated.
poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].add(stableValue);
//Check if total balance in pool if the threshold is reached.
uint checkbalance = totalPoolbalance[_poolIndex].add(poolPendingbalance[_poolIndex]);
//Update the user details in mapping.
poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.add(ItokenValue);
updateuserinfo(stableValue,_poolIndex);
//Buy the tokens if threshold is reached.
if (poolInfo[_poolIndex].currentRebalance == 0){
if(poolInfo[_poolIndex].threshold <= checkbalance){
buytokens( _poolIndex);
}
}
// poolOutstandingValue[_poolIndex] = poolOutstandingValue[_poolIndex].add();
// Again update details after tokens are bought.
updateuserinfo(0,_poolIndex);
//Mint new itokens and store details in mapping.
Iitoken(poolInfo[_poolIndex].itokenaddr).mint(msg.sender, ItokenValue);
}
/**
* @dev Withdraw from Pool using itoken.
* @param _poolIndex Pool Index to withdraw funds from.
* @param stakeEarlyFees Choose to stake early fees or not.
* @param withdrawAmount Amount to withdraw
*/
function withdraw(uint _poolIndex, bool stakeEarlyFees,bool stakePremium, uint withdrawAmount) external nonReentrant{
require(_poolIndex<poolInfo.length, "E02");
require(Iitoken(poolInfo[_poolIndex].itokenaddr).balanceOf(msg.sender)>=withdrawAmount, "E11");
// Update user info before withdrawal.
updateuserinfo(0,_poolIndex);
// Get the user share on the pool
uint userShare = poolUserInfo[_poolIndex][msg.sender].currentBalance.add(poolUserInfo[_poolIndex][msg.sender].pendingBalance).mul(withdrawAmount).div(poolUserInfo[_poolIndex][msg.sender].Itokens);
uint _balance;
uint _pendingAmount;
// Check if withdrawn amount is greater than pending amount. It will use the pending stable balance after that it will
if(userShare>poolUserInfo[_poolIndex][msg.sender].pendingBalance){
_balance = userShare.sub(poolUserInfo[_poolIndex][msg.sender].pendingBalance);
_pendingAmount = poolUserInfo[_poolIndex][msg.sender].pendingBalance;
}else{
_pendingAmount = userShare;
}
// Call the functions to sell the tokens and recieve stable based on the user share in that pool
uint256 _totalAmount = withdrawTokens(_poolIndex,_balance);
uint fees;
uint256 earlyfees;
uint256 pendingEarlyfees;
// Check if user actually make profit or not.
if(_totalAmount>_balance){
// Charge the performance fees on profit
fees = _totalAmount.sub(_balance).mul(IPoolConfiguration(_poolConf).getperformancefees()).div(100);
}
earlyfees = earlyfees.add(calculatefee(msg.sender,_totalAmount.sub(fees),_poolIndex));
pendingEarlyfees =calculatefee(msg.sender,_pendingAmount,_poolIndex);
poolUserInfo[_poolIndex][msg.sender].Itokens = poolUserInfo[_poolIndex][msg.sender].Itokens.sub(withdrawAmount);
//Update details in mapping for the withdrawn aount.
poolPendingbalance[_poolIndex] = poolPendingbalance[_poolIndex].sub( _pendingAmount);
poolUserInfo[_poolIndex][msg.sender].pendingBalance = poolUserInfo[_poolIndex][msg.sender].pendingBalance.sub(_pendingAmount);
totalPoolbalance[_poolIndex] = totalPoolbalance[_poolIndex].sub(_balance);
poolUserInfo[_poolIndex][msg.sender].currentBalance = poolUserInfo[_poolIndex][msg.sender].currentBalance.sub(_balance);
// Burn the itokens and update details in mapping.
Iitoken(poolInfo[_poolIndex].itokenaddr).burn(msg.sender, withdrawAmount);
withdrawUserAmount(_poolIndex,fees,_totalAmount.sub(fees).sub(earlyfees),_pendingAmount.sub(pendingEarlyfees),earlyfees.add(pendingEarlyfees),stakeEarlyFees,stakePremium);
emit Withdrawn(msg.sender, _balance);
}
// Withdraw amoun and charge fees. Now this single function will be used instead of chargePerformancefees,chargeEarlyFees,withdrawStable,withdrawPendingAmount.
// Some comment code line is for refrence what original code looks like.
function withdrawUserAmount(uint _poolIndex,uint fees,uint totalAmount,uint _pendingAmount, uint earlyfees,bool stakeEarlyFees,bool stakePremium) internal{
// This logic is similar to charge early fees.
// If user choose to stake early exit fees it will buy astra and stake them.
// If user don't want to stake it will be distributes among stakers and index onwer.
// Distribution logic is similar to performance fees so it is integrated with that. Early fees is added with performance fees.
if(stakeEarlyFees == true){
uint returnAmount= buyAstraToken(earlyfees);
stakeAstra(returnAmount,false);
}else{
fees = fees.add(earlyfees);
}
// This logic is similar to withdrawStable stable coins.
// If user choose to stake the amount instead of withdraw it will buy Astra and stake them.
// If user don't want to stake then they will recieve on there account in base stable coins.
if(stakePremium == true){
uint returnAmount= buyAstraToken(totalAmount);
stakeAstra(returnAmount,true);
}
else{
transferTokens(baseStableCoin,msg.sender,totalAmount);
// IERC20(baseStableCoin).safeTransfer(msg.sender, totalAmount);
}
// This logic is similar to withdrawPendingAmount. Early exit fees for pending amount is calculated previously.
// It transfer the pending amount to user account for which token are not bought.
transferTokens(baseStableCoin,msg.sender,_pendingAmount);
// IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount);
// This logic is similar to chargePerformancefees.
// 80 percent of fees will be send to the inde creator. Remaining 20 percent will be distributed among stakers.
if(fees>0){
uint distribution = fees.mul(80).div(100);
if(poolInfo[_poolIndex].owner==address(this)){
transferTokens(baseStableCoin,managerAddresses,distribution);
// IERC20(baseStableCoin).safeTransfer(managerAddresses, distribution);
}else{
transferTokens(baseStableCoin,poolInfo[_poolIndex].owner,distribution);
//IERC20(baseStableCoin).safeTransfer(poolInfo[_poolIndex].owner, distribution);
}
uint returnAmount= buyAstraToken(fees.sub(distribution));
transferTokens(ASTRTokenAddress,address(poolChef),returnAmount);
// IERC20(ASTRTokenAddress).safeTransfer(address(poolChef),returnAmount);
IMAsterChef(poolChef).distributeExitFeeShare(returnAmount);
}
}
function transferTokens(address _token, address _reciever,uint _amount) internal{
IERC20(_token).safeTransfer(_reciever, _amount);
}
/**
* @dev Internal fucntion to Withdraw from Pool using itoken.
* @param _poolIndex Pool Index to withdraw funds from.
* @param _balance Amount to withdraw from Pool.
*/
function withdrawTokens(uint _poolIndex,uint _balance) internal returns(uint256){
uint localWeight;
// Check if total pool balance is more than 0.
if(totalPoolbalance[_poolIndex]>0){
localWeight = _balance.mul(1 ether).div(totalPoolbalance[_poolIndex]);
// localWeight = _balance.mul(1 ether).div(Iitoken(poolInfo[_poolIndex].itokenaddr).totalSupply());
}
uint _totalAmount;
// Run loop over the tokens in the indices pool to sell the user share.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
uint _amount;
uint[] memory _distribution;
// Get the total token balance in that Pool.
uint tokenBalance = tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]];
// Get the user share from the total token amount
uint withdrawBalance = tokenBalance.mul(localWeight).div(1 ether);
if (withdrawBalance == 0) {
continue;
}
// Skip if withdraw amount is 0
if (poolInfo[_poolIndex].tokens[i] == baseStableCoin) {
_totalAmount = _totalAmount.add(withdrawBalance);
continue;
}
// Approve the Exchnage contract before selling thema.
IERC20(poolInfo[_poolIndex].tokens[i]).approve(EXCHANGE_CONTRACT, withdrawBalance);
// Get the expected amount of tokens to sell
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, 2, 0);
if (_amount == 0) {
continue;
}
_totalAmount = _totalAmount.add(_amount);
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = tokenBalance.sub(withdrawBalance);
// Swap the tokens and get stable in return so that users can withdraw.
IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), withdrawBalance, _amount, _distribution, 0);
}
return _totalAmount;
}
/**
* @param _poolIndex Pool Index to withdraw funds from.
* @param _pendingAmount Pending Amounts to withdraw from Pool.
* @dev Withdraw the pending amount that is submitted before next.
*/
function withdrawPendingAmount(uint256 _poolIndex,uint _pendingAmount)internal returns(uint256){
uint _earlyfee;
// Withdraw the pending Stable amount for which no tokens are bought. Here early exit fees wil be charged before transfering to user
if(_pendingAmount>0){
//Calculate how much early exit fees must be applicable
_earlyfee = calculatefee(msg.sender,_pendingAmount,_poolIndex);
IERC20(baseStableCoin).safeTransfer(msg.sender, _pendingAmount.sub(_earlyfee));
}
return _earlyfee;
}
/**
* @dev Update pool function to do the rebalaning.
* @param _tokens New tokens to purchase after rebalance.
* @param _weights Weight of new tokens.
* @param _threshold Threshold amount to purchase token.
* @param _rebalanceTime Next Rebalance time.
* @param _poolIndex Pool Index to do rebalance.
*/
function updatePool(address[] memory _tokens,uint[] memory _weights,uint _threshold,uint _rebalanceTime,uint _poolIndex) public nonReentrant{
require(block.timestamp >= poolInfo[_poolIndex].rebaltime,"E12");
// require(poolUserInfo[_poolIndex][msg.sender].currentBalance>poolInfo[_poolIndex].threshold,"Threshold not reached");
// Check if entered indices pool is public or Astra managed.
// Also check if is public pool then request came from the owner or not.
if(poolInfo[_poolIndex].owner != address(this)){
require(_tokens.length == _weights.length, "E02");
require(poolInfo[_poolIndex].owner == msg.sender, "E13");
}else{
(_tokens, _weights,_threshold,_rebalanceTime) = IOracle(IPoolConfiguration(_poolConf).getoracleaddress()).getTokenDetails(_poolIndex);
}
require (_tokens.length <= IPoolConfiguration(_poolConf).getmaxTokenSupported(), "E16");
address[] memory newTokens;
uint[] memory newWeights;
uint newTotalWeight;
uint _newTotalWeight;
// Loop over the tokens details to update its total weight.
for(uint i = 0; i < _tokens.length; i++) {
require (_tokens[i] != ETH_ADDRESS && _tokens[i] != WETH_ADDRESS);
_newTotalWeight = _newTotalWeight.add(_weights[i]);
}
// Update new tokens details
newTokens = _tokens;
newWeights = _weights;
newTotalWeight = _newTotalWeight;
// Update the pool details for next rebalance
poolInfo[_poolIndex].threshold = _threshold;
poolInfo[_poolIndex].rebaltime = _rebalanceTime;
//Sell old tokens and buy new tokens.
rebalance(newTokens, newWeights,newTotalWeight,_poolIndex);
// Buy the token for Stable which is in pending state.
if(poolPendingbalance[_poolIndex]>0){
buytokens(_poolIndex);
}
}
/**
* @dev Enable or disable Pool can only be called by admin
*/
function setPoolStatus(address _exchange, address _weth, address _stable) external systemOnly {
// poolInfo[_poolIndex].active = _active;
EXCHANGE_CONTRACT = _exchange;
WETH_ADDRESS = _weth;
baseStableCoin = _stable;
}
/**
* @dev Internal function called while updating the pool.
*/
function rebalance(address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint _poolIndex) internal {
require(poolInfo[_poolIndex].currentRebalance >0, "E14");
// Variable used to call the functions internally
uint[] memory buf2;
buf = buf2;
uint ethValue;
address[] memory returnedTokens;
uint[] memory returnedAmounts;
//Updating the balancing of tokens you are selling in storage and make update the balance in main mapping.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
buf.push(tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]]);
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = 0;
}
// Sell the Tokens in pool to recieve tokens
if(totalPoolbalance[_poolIndex]>0){
ethValue = sellTokensForStable(poolInfo[_poolIndex].tokens, buf);
}
// Updating pool configuration/mapping to update the new tokens details
poolInfo[_poolIndex].tokens = newTokens;
poolInfo[_poolIndex].weights = newWeights;
poolInfo[_poolIndex].totalWeight = newTotalWeight;
poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1);
poolInfo[_poolIndex].lastrebalance = block.timestamp;
// Return if you recieve 0 value for selling all the tokens
if (ethValue == 0) {
return;
}
uint[] memory buf3;
buf = buf3;
// Buy new tokens for the pool.
if(totalPoolbalance[_poolIndex]>0){
//Buy new tokens
(returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, newTokens, newWeights,newTotalWeight,buf);
// Update those tokens details in mapping.
for(uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = buf[i];
}
}
}
/**
* @dev Get the current value of pool to check the value of pool
*/
function getPoolValue(uint256 _poolIndex)public view returns(uint256){
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Return the total Amount of Stable you will recieve for selling. This will be total value of pool that it has purchased.
uint _totalAmount;
// Run loops over the tokens in the pool to get the token worth.
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(poolInfo[_poolIndex].tokens[i]), IERC20(baseStableCoin), tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]], 2, 0);
if (_amount == 0) {
continue;
}
_totalAmount = _totalAmount.add(_amount);
}
// Return the total values of pool locked
return _totalAmount;
}
/**
* @dev Function to swap two token. Used by other functions during buying and selling. It used where ether is used like at the time of ether deposit.
*/
function swap(address _token, uint _value, address[] memory _tokens, uint[] memory _weights, uint _totalWeight) internal returns(address[] memory, uint[] memory) {
// Use to get the share of particular token based on there share.
uint _tokenPart;
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Run loops over the tokens in the parametess to buy them.
for(uint i = 0; i < _tokens.length; i++) {
// Calculate the share of token based on the weight and the buy for that.
_tokenPart = _value.mul(_weights[i]).div(_totalWeight);
// Get the amount of tokens pool will recieve based on the token selled.
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(_tokens[i]), _tokenPart, 2, 0);
// calculate slippage
uint256 minReturn = calculateMinimumReturn(_amount);
_weights[i] = _amount;
// Check condition if token you are selling is ETH or another ERC20 and then sell the tokens.
if (_token == ETH_ADDRESS) {
_amount = IOneSplit(EXCHANGE_CONTRACT).swap.value(_tokenPart)(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0);
} else {
IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _tokenPart);
_amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(_tokens[i]), _tokenPart, minReturn, _distribution, 0);
}
}
return (_tokens, _weights);
}
/**
* @dev Function to swap two token. It used in case of ERC20 - ERC20 swap.
*/
function swap2(address _token, uint _value, address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint[] memory _buf) internal returns(address[] memory, uint[] memory) {
// Use to get the share of particular token based on there share.
uint _tokenPart;
// Used to get the Expected amount for the token you are selling.
uint _amount;
buf = _buf;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Approve before selling the tokens
IERC20(_token).approve(EXCHANGE_CONTRACT, _value);
// Run loops over the tokens in the parametess to buy them.
for(uint i = 0; i < newTokens.length; i++) {
_tokenPart = _value.mul(newWeights[i]).div(newTotalWeight);
if(_tokenPart == 0) {
buf.push(0);
continue;
}
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_token), IERC20(newTokens[i]), _tokenPart, 2, 0);
uint256 minReturn = calculateMinimumReturn(_amount);
buf.push(_amount);
newWeights[i] = _amount;
_amount= IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_token), IERC20(newTokens[i]), _tokenPart, minReturn, _distribution, 0);
}
return (newTokens, newWeights);
}
/**
* @dev Sell tokens for Stable is used during the rebalancing to sell previous token and buy new tokens
*/
function sellTokensForStable(address[] memory _tokens, uint[] memory _amounts) internal returns(uint) {
// Used to get the Expected amount for the token you are selling.
uint _amount;
// Used to get the distributing dex details for the token you are selling.
uint[] memory _distribution;
// Return the total Amount of Stable you will recieve for selling
uint _totalAmount;
// Run loops over the tokens in the parametess to sell them.
for(uint i = 0; i < _tokens.length; i++) {
if (_amounts[i] == 0) {
continue;
}
if (_tokens[i] == baseStableCoin) {
_totalAmount = _totalAmount.add(_amounts[i]);
continue;
}
// Approve token access to Exchange contract.
IERC20(_tokens[i]).approve(EXCHANGE_CONTRACT, _amounts[i]);
// Get the amount of Stable tokens you will recieve for selling tokens
(_amount, _distribution) = IOneSplit(EXCHANGE_CONTRACT).getExpectedReturn(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], 2, 0);
// Skip remaining execution if no token is available
if (_amount == 0) {
continue;
}
// Calculate slippage over the the expected amount
uint256 minReturn = calculateMinimumReturn(_amount);
_totalAmount = _totalAmount.add(_amount);
// Actually swap tokens
_amount = IOneSplit(EXCHANGE_CONTRACT).swap(IERC20(_tokens[i]), IERC20(baseStableCoin), _amounts[i], minReturn, _distribution, 0);
}
return _totalAmount;
}
}
pragma solidity ^0.5.0;
// import "./token.sol";
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call.value(weiValue)(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the decimal of tokens in existence.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract IOneSplitConsts {
// flags = FLAG_DISABLE_UNISWAP + FLAG_DISABLE_BANCOR + ...
uint256 internal constant FLAG_DISABLE_UNISWAP = 0x01;
uint256 internal constant DEPRECATED_FLAG_DISABLE_KYBER = 0x02; // Deprecated
uint256 internal constant FLAG_DISABLE_BANCOR = 0x04;
uint256 internal constant FLAG_DISABLE_OASIS = 0x08;
uint256 internal constant FLAG_DISABLE_COMPOUND = 0x10;
uint256 internal constant FLAG_DISABLE_FULCRUM = 0x20;
uint256 internal constant FLAG_DISABLE_CHAI = 0x40;
uint256 internal constant FLAG_DISABLE_AAVE = 0x80;
uint256 internal constant FLAG_DISABLE_SMART_TOKEN = 0x100;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_ETH = 0x200; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_BDAI = 0x400;
uint256 internal constant FLAG_DISABLE_IEARN = 0x800;
uint256 internal constant FLAG_DISABLE_CURVE_COMPOUND = 0x1000;
uint256 internal constant FLAG_DISABLE_CURVE_USDT = 0x2000;
uint256 internal constant FLAG_DISABLE_CURVE_Y = 0x4000;
uint256 internal constant FLAG_DISABLE_CURVE_BINANCE = 0x8000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_DAI = 0x10000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDC = 0x20000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_CURVE_SYNTHETIX = 0x40000;
uint256 internal constant FLAG_DISABLE_WETH = 0x80000;
uint256 internal constant FLAG_DISABLE_UNISWAP_COMPOUND = 0x100000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_CHAI = 0x200000; // Works only when ETH<>DAI or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_UNISWAP_AAVE = 0x400000; // Works only when one of assets is ETH or FLAG_ENABLE_MULTI_PATH_ETH
uint256 internal constant FLAG_DISABLE_IDLE = 0x800000;
uint256 internal constant FLAG_DISABLE_MOONISWAP = 0x1000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2 = 0x2000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ETH = 0x4000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_DAI = 0x8000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_USDC = 0x10000000;
uint256 internal constant FLAG_DISABLE_ALL_SPLIT_SOURCES = 0x20000000;
uint256 internal constant FLAG_DISABLE_ALL_WRAP_SOURCES = 0x40000000;
uint256 internal constant FLAG_DISABLE_CURVE_PAX = 0x80000000;
uint256 internal constant FLAG_DISABLE_CURVE_RENBTC = 0x100000000;
uint256 internal constant FLAG_DISABLE_CURVE_TBTC = 0x200000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_USDT = 0x400000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_WBTC = 0x800000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_TBTC = 0x1000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_RENBTC = 0x2000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_DFORCE_SWAP = 0x4000000000;
uint256 internal constant FLAG_DISABLE_SHELL = 0x8000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN = 0x10000000000;
uint256 internal constant FLAG_DISABLE_MSTABLE_MUSD = 0x20000000000;
uint256 internal constant FLAG_DISABLE_CURVE_SBTC = 0x40000000000;
uint256 internal constant FLAG_DISABLE_DMM = 0x80000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_ALL = 0x100000000000;
uint256 internal constant FLAG_DISABLE_CURVE_ALL = 0x200000000000;
uint256 internal constant FLAG_DISABLE_UNISWAP_V2_ALL = 0x400000000000;
uint256 internal constant FLAG_DISABLE_SPLIT_RECALCULATION = 0x800000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_ALL = 0x1000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_1 = 0x2000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_2 = 0x4000000000000;
uint256 internal constant FLAG_DISABLE_BALANCER_3 = 0x8000000000000;
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_UNISWAP_RESERVE = 0x10000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_OASIS_RESERVE = 0x20000000000000; // Deprecated, Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_KYBER_BANCOR_RESERVE = 0x40000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_ENABLE_REFERRAL_GAS_SPONSORSHIP = 0x80000000000000; // Turned off by default
uint256 internal constant DEPRECATED_FLAG_ENABLE_MULTI_PATH_COMP = 0x100000000000000; // Deprecated, Turned off by default
uint256 internal constant FLAG_DISABLE_KYBER_ALL = 0x200000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_1 = 0x400000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_2 = 0x800000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_3 = 0x1000000000000000;
uint256 internal constant FLAG_DISABLE_KYBER_4 = 0x2000000000000000;
uint256 internal constant FLAG_ENABLE_CHI_BURN_BY_ORIGIN = 0x4000000000000000;
}
contract IOneSplit is IOneSplitConsts {
function getExpectedReturn(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags // See constants in IOneSplit.sol
)
external
view
returns(
uint256 returnAmount,
uint256[] memory distribution
);
function getExpectedReturnWithGas(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 parts,
uint256 flags, // See constants in IOneSplit.sol
uint256 destTokenEthPriceTimesGasPrice
)
external
view
returns(
uint256 returnAmount,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swap(
IERC20 fromToken,
IERC20 destToken,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256 flags
)
external
payable
returns(uint256 returnAmount);
}
contract IOneSplitMulti is IOneSplit {
function getExpectedReturnWithGasMulti(
IERC20[] calldata tokens,
uint256 amount,
uint256[] calldata parts,
uint256[] calldata flags,
uint256[] calldata destTokenEthPriceTimesGasPrices
)
external
view
returns(
uint256[] memory returnAmounts,
uint256 estimateGasAmount,
uint256[] memory distribution
);
function swapMulti(
IERC20[] calldata tokens,
uint256 amount,
uint256 minReturn,
uint256[] calldata distribution,
uint256[] calldata flags
)
external
payable
returns(uint256 returnAmount);
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
function __init() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity 0.5.17;
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool wasInitializing = initializing;
initializing = true;
initialized = true;
_;
initializing = wasInitializing;
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
} | Variable used to call the functions internallyUpdating the balancing of tokens you are selling in storage and make update the balance in main mapping. Sell the Tokens in pool to recieve tokens Return if you recieve 0 value for selling all the tokens Buy new tokens for the pool.Buy new tokens Update those tokens details in mapping. | function rebalance(address[] memory newTokens, uint[] memory newWeights,uint newTotalWeight, uint _poolIndex) internal {
require(poolInfo[_poolIndex].currentRebalance >0, "E14");
uint[] memory buf2;
buf = buf2;
uint ethValue;
address[] memory returnedTokens;
uint[] memory returnedAmounts;
for (uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
buf.push(tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]]);
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = 0;
}
if(totalPoolbalance[_poolIndex]>0){
ethValue = sellTokensForStable(poolInfo[_poolIndex].tokens, buf);
}
poolInfo[_poolIndex].weights = newWeights;
poolInfo[_poolIndex].totalWeight = newTotalWeight;
poolInfo[_poolIndex].currentRebalance = poolInfo[_poolIndex].currentRebalance.add(1);
poolInfo[_poolIndex].lastrebalance = block.timestamp;
if (ethValue == 0) {
return;
}
uint[] memory buf3;
buf = buf3;
if(totalPoolbalance[_poolIndex]>0){
(returnedTokens, returnedAmounts) = swap2(baseStableCoin, ethValue, newTokens, newWeights,newTotalWeight,buf);
for(uint i = 0; i < poolInfo[_poolIndex].tokens.length; i++) {
tokenBalances[_poolIndex][poolInfo[_poolIndex].tokens[i]] = buf[i];
}
}
}
| 10,118,495 |
pragma solidity ^0.4.18;
// File: zeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
// File: zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev 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/crowdsale/SaleTracker.sol
/*
This is a simple contract that is used to track incoming payments.
As soon as a payment is received, an event is triggered to log the transaction.
All funds are immediately forwarded to the owner.
The sender must include a payment code as a payload and the contract can conditionally enforce the
sending address matches the payment code.
The payment code is the first 8 bytes of the keccak/sha3 hash of the address that the user has specified in the sale.
*/
contract SaleTracker is Pausable {
using SafeMath for uint256;
// Event to allow monitoring incoming payments
event PurchaseMade (address indexed _from, bytes8 _paymentCode, uint256 _value);
// Tracking of purchase total in wei made per sending address
mapping(address => uint256) public purchases;
// Tracking of purchaser addresses for lookup offline
address[] public purchaserAddresses;
// Flag to enforce payments source address matching the payment code
bool public enforceAddressMatch;
// Constructor to start the contract in a paused state
function SaleTracker(bool _enforceAddressMatch) public {
enforceAddressMatch = _enforceAddressMatch;
pause();
}
// Setter for the enforce flag - only updatable by the owner
function setEnforceAddressMatch(bool _enforceAddressMatch) onlyOwner public {
enforceAddressMatch = _enforceAddressMatch;
}
// Purchase function allows incoming payments when not paused - requires payment code
function purchase(bytes8 paymentCode) whenNotPaused public payable {
// Verify they have sent ETH in
require(msg.value != 0);
// Verify the payment code was included
require(paymentCode != 0);
// If payment from addresses are being enforced, ensure the code matches the sender address
if (enforceAddressMatch) {
// Get the first 8 bytes of the hash of the address
bytes8 calculatedPaymentCode = bytes8(keccak256(msg.sender));
// Fail if the sender code does not match
require(calculatedPaymentCode == paymentCode);
}
// Save off the existing purchase amount for this user
uint256 existingPurchaseAmount = purchases[msg.sender];
// If they have not purchased before (0 value), then save it off
if (existingPurchaseAmount == 0) {
purchaserAddresses.push(msg.sender);
}
// Add the new purchase value to the existing value already being tracked
purchases[msg.sender] = existingPurchaseAmount.add(msg.value);
// Transfer out to the owner wallet
owner.transfer(msg.value);
// Trigger the event for a new purchase
PurchaseMade(msg.sender, paymentCode, msg.value);
}
// Allows owner to sweep any ETH somehow trapped in the contract.
function sweep() onlyOwner public {
owner.transfer(this.balance);
}
// Get the number of addresses that have contributed to the sale
function getPurchaserAddressCount() public constant returns (uint) {
return purchaserAddresses.length;
}
} | Allows owner to sweep any ETH somehow trapped in the contract. | function sweep() onlyOwner public {
owner.transfer(this.balance);
}
| 208,504 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC20/SafeERC20.sol";
import "./ClaimConfig.sol";
import "./interfaces/ICoverPool.sol";
import "./interfaces/ICoverPoolFactory.sol";
import "./interfaces/IClaimManagement.sol";
/**
* @title Claim Management for claims filed for a COVER supported coverPool
* @author Alan + crypto-pumpkin
*/
contract ClaimManagement is IClaimManagement, ClaimConfig {
using SafeERC20 for IERC20;
// the redeem delay for a cover when there is a pending claim
uint256 public constant PENDING_CLAIM_REDEEM_DELAY = 10 days;
// coverPool => nonce => Claim[]
mapping(address => mapping(uint256 => Claim[])) private coverPoolClaims;
constructor(
address _feeCurrency,
address _treasury,
address _coverPoolFactory,
address _defaultCVC
) {
require(_feeCurrency != address(0), "CM: fee cannot be 0");
require(_treasury != address(0), "CM: treasury cannot be 0");
require(_coverPoolFactory != address(0), "CM: factory cannot be 0");
require(_defaultCVC != address(0), "CM: defaultCVC cannot be 0");
feeCurrency = IERC20(_feeCurrency);
treasury = _treasury;
coverPoolFactory = ICoverPoolFactory(_coverPoolFactory);
defaultCVC = _defaultCVC;
initializeOwner();
}
/// @notice File a claim for a Cover Pool, `_incidentTimestamp` must be within allowed time window
function fileClaim(
string calldata _coverPoolName,
bytes32[] calldata _exploitRisks,
uint48 _incidentTimestamp,
string calldata _description,
bool isForceFile
) external override {
address coverPool = _getCoverPoolAddr(_coverPoolName);
require(coverPool != address(0), "CM: pool not found");
require(block.timestamp - _incidentTimestamp <= coverPoolFactory.defaultRedeemDelay() - TIME_BUFFER, "CM: time passed window");
ICoverPool(coverPool).setNoclaimRedeemDelay(PENDING_CLAIM_REDEEM_DELAY);
uint256 nonce = _getCoverPoolNonce(coverPool);
uint256 claimFee = isForceFile ? forceClaimFee : getCoverPoolClaimFee(coverPool);
feeCurrency.safeTransferFrom(msg.sender, address(this), claimFee);
_updateCoverPoolClaimFee(coverPool);
ClaimState state = isForceFile ? ClaimState.ForceFiled : ClaimState.Filed;
coverPoolClaims[coverPool][nonce].push(Claim({
filedBy: msg.sender,
decidedBy: address(0),
filedTimestamp: uint48(block.timestamp),
incidentTimestamp: _incidentTimestamp,
decidedTimestamp: 0,
description: _description,
state: state,
feePaid: claimFee,
payoutRiskList: _exploitRisks,
payoutRates: new uint256[](_exploitRisks.length)
}));
emit ClaimUpdate(coverPool, state, nonce, coverPoolClaims[coverPool][nonce].length - 1);
}
/**
* @notice Validates whether claim will be passed to CVC to decideClaim
* @param _coverPool address: contract address of the coverPool that COVER supports
* @param _nonce uint256: nonce of the coverPool
* @param _index uint256: index of the claim
* @param _claimIsValid bool: true if claim is valid and passed to CVC, false otherwise
* Emits ClaimUpdate
*/
function validateClaim(
address _coverPool,
uint256 _nonce,
uint256 _index,
bool _claimIsValid
) external override onlyOwner {
Claim storage claim = coverPoolClaims[_coverPool][_nonce][_index];
require(_index < coverPoolClaims[_coverPool][_nonce].length, "CM: bad index");
require(_nonce == _getCoverPoolNonce(_coverPool), "CM: wrong nonce");
require(claim.state == ClaimState.Filed, "CM: claim not filed");
if (_claimIsValid) {
claim.state = ClaimState.Validated;
_resetCoverPoolClaimFee(_coverPool);
} else {
claim.state = ClaimState.Invalidated;
claim.decidedTimestamp = uint48(block.timestamp);
feeCurrency.safeTransfer(treasury, claim.feePaid);
_resetNoclaimRedeemDelay(_coverPool, _nonce);
}
emit ClaimUpdate({
coverPool: _coverPool,
state: claim.state,
nonce: _nonce,
index: _index
});
}
/// @notice Decide whether claim for a coverPool should be accepted(will payout) or denied, ignored _incidentTimestamp == 0
function decideClaim(
address _coverPool,
uint256 _nonce,
uint256 _index,
uint48 _incidentTimestamp,
bool _claimIsAccepted,
bytes32[] calldata _exploitRisks,
uint256[] calldata _payoutRates
) external override {
require(_exploitRisks.length == _payoutRates.length, "CM: arrays len don't match");
require(isCVCMember(_coverPool, msg.sender), "CM: !cvc");
require(_nonce == _getCoverPoolNonce(_coverPool), "CM: wrong nonce");
Claim storage claim = coverPoolClaims[_coverPool][_nonce][_index];
require(claim.state == ClaimState.Validated || claim.state == ClaimState.ForceFiled, "CM: ! validated or forceFiled");
if (_incidentTimestamp != 0) {
require(claim.filedTimestamp - _incidentTimestamp <= coverPoolFactory.defaultRedeemDelay() - TIME_BUFFER, "CM: time passed window");
claim.incidentTimestamp = _incidentTimestamp;
}
uint256 totalRates = _getTotalNum(_payoutRates);
if (_claimIsAccepted && !_isDecisionWindowPassed(claim)) {
require(totalRates > 0 && totalRates <= 1 ether, "CM: payout % not in (0%, 100%]");
feeCurrency.safeTransfer(claim.filedBy, claim.feePaid);
_resetCoverPoolClaimFee(_coverPool);
claim.state = ClaimState.Accepted;
claim.payoutRiskList = _exploitRisks;
claim.payoutRates = _payoutRates;
ICoverPool(_coverPool).enactClaim(claim.payoutRiskList, claim.payoutRates, claim.incidentTimestamp, _nonce);
} else { // Max decision claim window passed, claim is default to Denied
require(totalRates == 0, "CM: claim denied (default if passed window), but payoutNumerator != 0");
feeCurrency.safeTransfer(treasury, claim.feePaid);
claim.state = ClaimState.Denied;
}
_resetNoclaimRedeemDelay(_coverPool, _nonce);
claim.decidedBy = msg.sender;
claim.decidedTimestamp = uint48(block.timestamp);
emit ClaimUpdate(_coverPool, claim.state, _nonce, _index);
}
function getCoverPoolClaims(address _coverPool, uint256 _nonce, uint256 _index) external view override returns (Claim memory) {
return coverPoolClaims[_coverPool][_nonce][_index];
}
/// @notice Get all claims for coverPool `_coverPool` and nonce `_nonce` in state `_state`
function getAllClaimsByState(address _coverPool, uint256 _nonce, ClaimState _state)
external view override returns (Claim[] memory)
{
Claim[] memory allClaims = coverPoolClaims[_coverPool][_nonce];
uint256 count;
Claim[] memory temp = new Claim[](allClaims.length);
for (uint i = 0; i < allClaims.length; i++) {
if (allClaims[i].state == _state) {
temp[count] = allClaims[i];
count++;
}
}
Claim[] memory claimsByState = new Claim[](count);
for (uint i = 0; i < count; i++) {
claimsByState[i] = temp[i];
}
return claimsByState;
}
/// @notice Get all claims for coverPool `_coverPool` and nonce `_nonce`
function getAllClaimsByNonce(address _coverPool, uint256 _nonce) external view override returns (Claim[] memory) {
return coverPoolClaims[_coverPool][_nonce];
}
/// @notice Get whether a pending claim for coverPool `_coverPool` and nonce `_nonce` exists
function hasPendingClaim(address _coverPool, uint256 _nonce) public view override returns (bool) {
Claim[] memory allClaims = coverPoolClaims[_coverPool][_nonce];
for (uint i = 0; i < allClaims.length; i++) {
ClaimState state = allClaims[i].state;
if (state == ClaimState.Filed || state == ClaimState.ForceFiled || state == ClaimState.Validated) {
return true;
}
}
return false;
}
function _resetNoclaimRedeemDelay(address _coverPool, uint256 _nonce) private {
if (hasPendingClaim(_coverPool, _nonce)) return;
uint256 defaultRedeemDelay = coverPoolFactory.defaultRedeemDelay();
ICoverPool(_coverPool).setNoclaimRedeemDelay(defaultRedeemDelay);
}
function _getCoverPoolAddr(string calldata _coverPoolName) private view returns (address) {
return coverPoolFactory.coverPools(_coverPoolName);
}
function _getCoverPoolNonce(address _coverPool) private view returns (uint256) {
return ICoverPool(_coverPool).claimNonce();
}
// The times passed since the claim was filed has to be less than the max claim decision window
function _isDecisionWindowPassed(Claim memory claim) private view returns (bool) {
return block.timestamp - claim.filedTimestamp > maxClaimDecisionWindow;
}
function _getTotalNum(uint256[] calldata _payoutRates) private pure returns (uint256 _totalRates) {
for (uint256 i = 0; i < _payoutRates.length; i++) {
_totalRates = _totalRates + _payoutRates[i];
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./utils/Ownable.sol";
import "./interfaces/IClaimConfig.sol";
import "./interfaces/ICoverPool.sol";
import "./interfaces/ICoverPoolFactory.sol";
/**
* @title Config for ClaimManagement contract
* @author Alan + crypto-pumpkin
*/
contract ClaimConfig is IClaimConfig, Ownable {
IERC20 public override feeCurrency;
address public override treasury;
ICoverPoolFactory public override coverPoolFactory;
address public override defaultCVC; // if not specified, default to this
uint256 internal constant TIME_BUFFER = 1 hours;
// The max time allowed from filing a claim to a decision made, 1 hr buffer for calling
uint256 public override maxClaimDecisionWindow = 7 days - TIME_BUFFER;
uint256 public override baseClaimFee = 50e18;
uint256 public override forceClaimFee = 500e18;
uint256 public override feeMultiplier = 2;
// coverPool => claim fee
mapping(address => uint256) private coverPoolClaimFee;
// coverPool => cvc addresses
mapping(address => address[]) public override cvcMap;
function setTreasury(address _treasury) external override onlyOwner {
require(_treasury != address(0), "CC: treasury cannot be 0");
treasury = _treasury;
}
/// @notice Set max time window allowed to decide a claim after filed
function setMaxClaimDecisionWindow(uint256 _newTimeWindow) external override onlyOwner {
require(_newTimeWindow > 0, "CC: window too short");
maxClaimDecisionWindow = _newTimeWindow;
}
function setDefaultCVC(address _cvc) external override onlyOwner {
require(_cvc != address(0), "CC: default CVC cannot be 0");
defaultCVC = _cvc;
}
/// @notice Add CVC groups for multiple coverPools
function addCVCForPools(address[] calldata _coverPools, address[] calldata _cvcs) external override onlyOwner {
require(_coverPools.length == _cvcs.length, "CC: lengths don't match");
for (uint256 i = 0; i < _coverPools.length; i++) {
_addCVCForPool(_coverPools[i], _cvcs[i]);
}
}
/// @notice Remove CVC groups for multiple coverPools
function removeCVCForPools(address[] calldata _coverPools, address[] calldata _cvcs) external override onlyOwner {
require(_coverPools.length == _cvcs.length, "CC: lengths don't match");
for (uint256 i = 0; i < _coverPools.length; i++) {
_removeCVCForPool(_coverPools[i], _cvcs[i]);
}
}
function setFeeAndCurrency(uint256 _baseClaimFee, uint256 _forceClaimFee, address _currency) external override onlyOwner {
require(_currency != address(0), "CC: feeCurrency cannot be 0");
require(_baseClaimFee > 0, "CC: baseClaimFee <= 0");
require(_forceClaimFee > _baseClaimFee, "CC: force Fee <= base Fee");
baseClaimFee = _baseClaimFee;
forceClaimFee = _forceClaimFee;
feeCurrency = IERC20(_currency);
}
function setFeeMultiplier(uint256 _multiplier) external override onlyOwner {
require(_multiplier >= 1, "CC: multiplier must be >= 1");
feeMultiplier = _multiplier;
}
/// @notice return the whole list so dont need to query by index
function getCVCList(address _coverPool) external view override returns (address[] memory) {
return cvcMap[_coverPool];
}
function isCVCMember(address _coverPool, address _address) public view override returns (bool) {
address[] memory cvcCopy = cvcMap[_coverPool];
if (cvcCopy.length == 0 && _address == defaultCVC) return true;
for (uint256 i = 0; i < cvcCopy.length; i++) {
if (_address == cvcCopy[i]) {
return true;
}
}
return false;
}
function getCoverPoolClaimFee(address _coverPool) public view override returns (uint256) {
return coverPoolClaimFee[_coverPool] < baseClaimFee ? baseClaimFee : coverPoolClaimFee[_coverPool];
}
// Add CVC group for a coverPool if `_cvc` isn't already added
function _addCVCForPool(address _coverPool, address _cvc) private onlyOwner {
address[] memory cvcCopy = cvcMap[_coverPool];
for (uint256 i = 0; i < cvcCopy.length; i++) {
require(cvcCopy[i] != _cvc, "CC: cvc exists");
}
cvcMap[_coverPool].push(_cvc);
}
function _removeCVCForPool(address _coverPool, address _cvc) private {
address[] memory cvcCopy = cvcMap[_coverPool];
uint256 len = cvcCopy.length;
if (len < 1) return; // nothing to remove, no need to revert
for (uint256 i = 0; i < len; i++) {
if (_cvc == cvcCopy[i]) {
cvcMap[_coverPool][i] = cvcCopy[len - 1];
cvcMap[_coverPool].pop();
break;
}
}
}
// Updates fee for coverPool `_coverPool` by multiplying current fee by `feeMultiplier`, capped at `forceClaimFee`
function _updateCoverPoolClaimFee(address _coverPool) internal {
uint256 newFee = getCoverPoolClaimFee(_coverPool) * feeMultiplier;
if (newFee <= forceClaimFee) {
coverPoolClaimFee[_coverPool] = newFee;
}
}
// Resets fee for coverPool `_coverPool` to `baseClaimFee`
function _resetCoverPoolClaimFee(address _coverPool) internal {
coverPoolClaimFee[_coverPool] = baseClaimFee;
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @dev CoverPool contract interface. See {CoverPool}.
* @author crypto-pumpkin
*/
interface ICoverPool {
event CoverCreated(address indexed);
event CoverAdded(address indexed _cover, address _acount, uint256 _amount);
event NoclaimRedeemDelayUpdated(uint256 _oldDelay, uint256 _newDelay);
event ClaimEnacted(uint256 _enactedClaimNonce);
event RiskUpdated(bytes32 _risk, bool _isAddRisk);
event PoolStatusUpdated(Status _old, Status _new);
event ExpiryUpdated(uint48 _expiry, string _expiryStr, Status _status);
event CollateralUpdated(address indexed _collateral, uint256 _mintRatio, Status _status);
enum Status { Null, Active, Disabled }
struct ExpiryInfo {
string name;
Status status;
}
struct CollateralInfo {
uint256 mintRatio;
Status status;
}
struct ClaimDetails {
uint48 incidentTimestamp;
uint48 claimEnactedTimestamp;
uint256 totalPayoutRate;
bytes32[] payoutRiskList;
uint256[] payoutRates;
}
// state vars
function name() external view returns (string memory);
function extendablePool() external view returns (bool);
function poolStatus() external view returns (Status _status);
/// @notice only active (true) coverPool allows adding more covers (aka. minting more CLAIM and NOCLAIM tokens)
function claimNonce() external view returns (uint256);
function noclaimRedeemDelay() external view returns (uint256);
function addingRiskWIP() external view returns (bool);
function addingRiskIndex() external view returns (uint256);
function activeCovers(uint256 _index) external view returns (address);
function allCovers(uint256 _index) external view returns (address);
function expiries(uint256 _index) external view returns (uint48);
function collaterals(uint256 _index) external view returns (address);
function riskList(uint256 _index) external view returns (bytes32);
function deletedRiskList(uint256 _index) external view returns (bytes32);
function riskMap(bytes32 _risk) external view returns (Status);
function collateralStatusMap(address _collateral) external view returns (uint256 _mintRatio, Status _status);
function expiryInfoMap(uint48 _expiry) external view returns (string memory _name, Status _status);
function coverMap(address _collateral, uint48 _expiry) external view returns (address);
// extra view
function getRiskList() external view returns (bytes32[] memory _riskList);
function getClaimDetails(uint256 _claimNonce) external view returns (ClaimDetails memory);
function getCoverPoolDetails()
external view returns (
address[] memory _collaterals,
uint48[] memory _expiries,
bytes32[] memory _riskList,
bytes32[] memory _deletedRiskList,
address[] memory _allCovers
);
// user action
/// @notice cover must be deployed first
function addCover(
address _collateral,
uint48 _expiry,
address _receiver,
uint256 _colAmountIn,
uint256 _amountOut,
bytes calldata _data
) external;
function deployCover(address _collateral, uint48 _expiry) external returns (address _coverAddress);
// access restriction - claimManager
function enactClaim(
bytes32[] calldata _payoutRiskList,
uint256[] calldata _payoutRates,
uint48 _incidentTimestamp,
uint256 _coverPoolNonce
) external;
// CM and dev only
function setNoclaimRedeemDelay(uint256 _noclaimRedeemDelay) external;
// access restriction - dev
function addRisk(string calldata _risk) external returns (bool);
function deleteRisk(string calldata _risk) external;
function setExpiry(uint48 _expiry, string calldata _expiryName, Status _status) external;
function setCollateral(address _collateral, uint256 _mintRatio, Status _status) external;
function setPoolStatus(Status _poolStatus) external;
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @dev CoverPoolFactory contract interface. See {CoverPoolFactory}.
* @author crypto-pumpkin
*/
interface ICoverPoolFactory {
event CoverPoolCreated(address indexed _addr);
event IntUpdated(string _type, uint256 _old, uint256 _new);
event AddressUpdated(string _type, address indexed _old, address indexed _new);
event PausedStatusUpdated(bool _old, bool _new);
// state vars
function MAX_REDEEM_DELAY() external view returns (uint256);
function defaultRedeemDelay() external view returns (uint256);
// yearlyFeeRate is scaled 1e18
function yearlyFeeRate() external view returns (uint256);
function paused() external view returns (bool);
function responder() external view returns (address);
function coverPoolImpl() external view returns (address);
function coverImpl() external view returns (address);
function coverERC20Impl() external view returns (address);
function treasury() external view returns (address);
function claimManager() external view returns (address);
/// @notice min gas left requirement before continue deployments (when creating new Cover or adding risks to CoverPool)
function deployGasMin() external view returns (uint256);
function coverPoolNames(uint256 _index) external view returns (string memory);
function coverPools(string calldata _coverPoolName) external view returns (address);
// extra view
function getCoverPools() external view returns (address[] memory);
/// @notice return contract address, the contract may not be deployed yet
function getCoverPoolAddress(string calldata _name) external view returns (address);
function getCoverAddress(string calldata _coverPoolName, uint48 _timestamp, address _collateral, uint256 _claimNonce) external view returns (address);
/// @notice _prefix example: "C_CURVE", "C_FUT1", or "NC_"
function getCovTokenAddress(string calldata _coverPoolName, uint48 _expiry, address _collateral, uint256 _claimNonce, string memory _prefix) external view returns (address);
// access restriction - owner (dev) & responder
function setPaused(bool _paused) external;
// access restriction - owner (dev)
function setYearlyFeeRate(uint256 _yearlyFeeRate) external;
function setDefaultRedeemDelay(uint256 _defaultRedeemDelay) external;
function setResponder(address _responder) external;
function setDeployGasMin(uint256 _deployGasMin) external;
/// @dev update Impl will only affect contracts deployed after
function setCoverPoolImpl(address _newImpl) external;
function setCoverImpl(address _newImpl) external;
function setCoverERC20Impl(address _newImpl) external;
function setTreasury(address _address) external;
function setClaimManager(address _address) external;
/**
* @notice Create a new Cover Pool
* @param _name name for pool, e.g. Yearn
* @param _extendablePool open pools allow adding new risk
* @param _riskList risk risks that are covered in this pool
* @param _collateral the collateral of the pool
* @param _mintRatio 18 decimals, in (0, + infinity) the deposit ratio for the collateral the pool, 1.5 means = 1 collateral mints 1.5 CLAIM/NOCLAIM tokens
* @param _expiry expiration date supported for the pool
* @param _expiryString MONTH_DATE_YEAR, used to create covToken symbols only
*
* Emits CoverPoolCreated, add a supported coverPool in COVER
*/
function createCoverPool(
string calldata _name,
bool _extendablePool,
string[] calldata _riskList,
address _collateral,
uint256 _mintRatio,
uint48 _expiry,
string calldata _expiryString
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev ClaimManagement contract interface. See {ClaimManagement}.
* @author Alan + crypto-pumpkin
*/
interface IClaimManagement {
event ClaimUpdate(address indexed coverPool, ClaimState state, uint256 nonce, uint256 index);
enum ClaimState { Filed, ForceFiled, Validated, Invalidated, Accepted, Denied }
struct Claim {
address filedBy; // Address of user who filed claim
address decidedBy; // Address of the CVC who decided claim
uint48 filedTimestamp; // Timestamp of submitted claim
uint48 incidentTimestamp; // Timestamp of the incident the claim is filed for
uint48 decidedTimestamp; // Timestamp when claim outcome is decided
string description;
ClaimState state; // Current state of claim
uint256 feePaid; // Fee paid to file the claim
bytes32[] payoutRiskList;
uint256[] payoutRates; // Numerators of percent to payout
}
function getCoverPoolClaims(address _coverPool, uint256 _nonce, uint256 _index) external view returns (Claim memory);
function getAllClaimsByState(address _coverPool, uint256 _nonce, ClaimState _state) external view returns (Claim[] memory);
function getAllClaimsByNonce(address _coverPool, uint256 _nonce) external view returns (Claim[] memory);
function hasPendingClaim(address _coverPool, uint256 _nonce) external view returns (bool);
function fileClaim(
string calldata _coverPoolName,
bytes32[] calldata _exploitRisks,
uint48 _incidentTimestamp,
string calldata _description,
bool _isForceFile
) external;
// @dev Only callable by dev when auditor is voting
function validateClaim(address _coverPool, uint256 _nonce, uint256 _index, bool _claimIsValid) external;
// @dev Only callable by CVC
function decideClaim(
address _coverPool,
uint256 _nonce,
uint256 _index,
uint48 _incidentTimestamp,
bool _claimIsAccepted,
bytes32[] calldata _exploitRisks,
uint256[] calldata _payoutRates
) external;
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
/**
* @title Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: No License
pragma solidity ^0.8.0;
import "../interfaces/IOwnable.sol";
import "./Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
* @author crypto-pumpkin
*
* By initialization, the owner account will be the one that called initializeOwner. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev COVER: Initializes the contract setting the deployer as the initial owner.
*/
function initializeOwner() internal initializer {
_owner = msg.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(_owner == msg.sender, "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC20/IERC20.sol";
import "./ICoverPoolFactory.sol";
/**
* @dev ClaimConfg contract interface. See {ClaimConfig}.
* @author Alan + crypto-pumpkin
*/
interface IClaimConfig {
function treasury() external view returns (address);
function coverPoolFactory() external view returns (ICoverPoolFactory);
function defaultCVC() external view returns (address);
function maxClaimDecisionWindow() external view returns (uint256);
function baseClaimFee() external view returns (uint256);
function forceClaimFee() external view returns (uint256);
function feeMultiplier() external view returns (uint256);
function feeCurrency() external view returns (IERC20);
function cvcMap(address _coverPool, uint256 _idx) external view returns (address);
function getCVCList(address _coverPool) external returns (address[] memory);
function isCVCMember(address _coverPool, address _address) external view returns (bool);
function getCoverPoolClaimFee(address _coverPool) external view returns (uint256);
// @notice only dev
function setMaxClaimDecisionWindow(uint256 _newTimeWindow) external;
function setTreasury(address _treasury) external;
function addCVCForPools(address[] calldata _coverPools, address[] calldata _cvcs) external;
function removeCVCForPools(address[] calldata _coverPools, address[] calldata _cvcs) external;
function setDefaultCVC(address _cvc) external;
function setFeeAndCurrency(uint256 _baseClaimFee, uint256 _forceClaimFee, address _currency) external;
function setFeeMultiplier(uint256 _multiplier) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Interface of Ownable
*/
interface IOwnable {
function owner() external view returns (address);
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {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;
}
}
| File a claim for a Cover Pool, `_incidentTimestamp` must be within allowed time window | function fileClaim(
string calldata _coverPoolName,
bytes32[] calldata _exploitRisks,
uint48 _incidentTimestamp,
string calldata _description,
bool isForceFile
) external override {
address coverPool = _getCoverPoolAddr(_coverPoolName);
require(coverPool != address(0), "CM: pool not found");
require(block.timestamp - _incidentTimestamp <= coverPoolFactory.defaultRedeemDelay() - TIME_BUFFER, "CM: time passed window");
ICoverPool(coverPool).setNoclaimRedeemDelay(PENDING_CLAIM_REDEEM_DELAY);
uint256 nonce = _getCoverPoolNonce(coverPool);
uint256 claimFee = isForceFile ? forceClaimFee : getCoverPoolClaimFee(coverPool);
feeCurrency.safeTransferFrom(msg.sender, address(this), claimFee);
_updateCoverPoolClaimFee(coverPool);
ClaimState state = isForceFile ? ClaimState.ForceFiled : ClaimState.Filed;
coverPoolClaims[coverPool][nonce].push(Claim({
filedBy: msg.sender,
decidedBy: address(0),
filedTimestamp: uint48(block.timestamp),
incidentTimestamp: _incidentTimestamp,
decidedTimestamp: 0,
description: _description,
state: state,
feePaid: claimFee,
payoutRiskList: _exploitRisks,
payoutRates: new uint256[](_exploitRisks.length)
}));
emit ClaimUpdate(coverPool, state, nonce, coverPoolClaims[coverPool][nonce].length - 1);
}
| 11,690,110 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.6.0;
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address payable public owner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address payable _newOwner) public onlyOwner {
owner = _newOwner;
emit OwnershipTransferred(msg.sender, _newOwner);
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
abstract contract ERC20Interface {
function totalSupply() public virtual view returns (uint);
function balanceOf(address tokenOwner) public virtual view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public virtual view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public virtual returns (bool success);
function approve(address spender, uint256 tokens) public virtual returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public virtual returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function ceil(uint a, uint m) internal pure returns (uint r) {
return (a + m - 1) / m * m;
}
}
interface ISYFP{
function transferFrom(address from, address to, uint256 tokens) external returns (bool success);
function transfer(address to, uint256 tokens) external returns (bool success);
function mint(address to, uint256 _mint_amount) external;
}
contract SYFP_STAKE_FARM is Owned{
using SafeMath for uint256;
uint256 public yieldCollectionFee = 0.05 ether;
uint256 public stakingPeriod = 2 weeks;
uint256 public stakeClaimFee = 0.01 ether;
uint256 public totalYield;
uint256 public totalRewards;
address public SYFP = 0xC11396e14990ebE98a09F8639a082C03Eb9dB55a;
struct Tokens{
bool exists;
uint256 rate;
uint256 stakedTokens;
}
mapping(address => Tokens) public tokens;
address[] TokensAddresses;
struct DepositedToken{
uint256 activeDeposit;
uint256 totalDeposits;
uint256 startTime;
uint256 pendingGains;
uint256 lastClaimedDate;
uint256 totalGained;
uint rate;
uint period;
}
mapping(address => mapping(address => DepositedToken)) users;
event TokenAdded(address indexed tokenAddress, uint256 indexed APY);
event TokenRemoved(address indexed tokenAddress, uint256 indexed APY);
event FarmingRateChanged(address indexed tokenAddress, uint256 indexed newAPY);
event YieldCollectionFeeChanged(uint256 indexed yieldCollectionFee);
event FarmingStarted(address indexed _tokenAddress, uint256 indexed _amount);
event YieldCollected(address indexed _tokenAddress, uint256 indexed _yield);
event AddedToExistingFarm(address indexed _tokenAddress, uint256 indexed tokens);
event Staked(address indexed staker, uint256 indexed tokens);
event AddedToExistingStake(address indexed staker, uint256 indexed tokens);
event StakingRateChanged(uint256 indexed newAPY);
event TokensClaimed(address indexed claimer, uint256 indexed stakedTokens);
event RewardClaimed(address indexed claimer, uint256 indexed reward);
constructor() public {
owner = 0xf64df26Fb32Ce9142393C31f01BB1689Ff7b29f5;
// add syfp token to ecosystem
_addToken(0xC11396e14990ebE98a09F8639a082C03Eb9dB55a, 4000000); //SYFP
_addToken(0xdAC17F958D2ee523a2206206994597C13D831ec7, 14200); // USDT
_addToken(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48, 14200); // USDC
_addToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2, 5200000); // WETH
_addToken(0x0bc529c00C6401aEF6D220BE8C6Ea1667F6Ad93e, 297300000); // YFI
_addToken(0x45f24BaEef268BB6d63AEe5129015d69702BCDfa, 230000); // YFV
_addToken(0x96d62cdCD1cc49cb6eE99c867CB8812bea86B9FA, 300000); // yfp
}
//#########################################################################################################################################################//
//####################################################FARMING EXTERNAL FUNCTIONS###########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Add assets to farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function Farm(address _tokenAddress, uint256 _amount) external{
require(_tokenAddress != SYFP, "Use staking instead");
// add to farm
_newDeposit(_tokenAddress, _amount);
// transfer tokens from user to the contract balance
require(ISYFP(_tokenAddress).transferFrom(msg.sender, address(this), _amount));
emit FarmingStarted(_tokenAddress, _amount);
}
// ------------------------------------------------------------------------
// Add more deposits to already running farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function AddToFarm(address _tokenAddress, uint256 _amount) external{
require(_tokenAddress != SYFP, "use staking instead");
_addToExisting(_tokenAddress, _amount);
// move the tokens from the caller to the contract address
require(ISYFP(_tokenAddress).transferFrom(msg.sender,address(this), _amount));
emit AddedToExistingFarm(_tokenAddress, _amount);
}
// ------------------------------------------------------------------------
// Withdraw accumulated yield
// @param _tokenAddress address of the token asset
// @required must pay yield claim fee
// ------------------------------------------------------------------------
function Yield(address _tokenAddress) public payable {
require(msg.value >= yieldCollectionFee, "should pay exact claim fee");
require(PendingYield(_tokenAddress, msg.sender) > 0, "No pending yield");
require(tokens[_tokenAddress].exists, "Token doesn't exist");
require(_tokenAddress != SYFP, "use staking instead");
uint256 _pendingYield = PendingYield(_tokenAddress, msg.sender);
// Global stats update
totalYield = totalYield.add(_pendingYield);
// update the record
users[msg.sender][_tokenAddress].totalGained = users[msg.sender][_tokenAddress].totalGained.add(_pendingYield);
users[msg.sender][_tokenAddress].lastClaimedDate = now;
users[msg.sender][_tokenAddress].pendingGains = 0;
// transfer fee to the owner
owner.transfer(msg.value);
// mint more tokens inside token contract equivalent to _pendingYield
ISYFP(SYFP).mint(msg.sender, _pendingYield);
emit YieldCollected(_tokenAddress, _pendingYield);
}
// ------------------------------------------------------------------------
// Withdraw any amount of tokens, the contract will update the farming
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function WithdrawFarmedTokens(address _tokenAddress, uint256 _amount) public {
require(users[msg.sender][_tokenAddress].activeDeposit >= _amount, "insufficient amount in farming");
require(_tokenAddress != SYFP, "use withdraw of staking instead");
// update farming stats
// check if we have any pending yield, add it to previousYield var
users[msg.sender][_tokenAddress].pendingGains = PendingYield(_tokenAddress, msg.sender);
tokens[_tokenAddress].stakedTokens = tokens[_tokenAddress].stakedTokens.sub(_amount);
// update amount
users[msg.sender][_tokenAddress].activeDeposit = users[msg.sender][_tokenAddress].activeDeposit.sub(_amount);
// update farming start time -- new farming will begin from this time onwards
users[msg.sender][_tokenAddress].startTime = now;
// reset last claimed figure as well -- new farming will begin from this time onwards
users[msg.sender][_tokenAddress].lastClaimedDate = now;
// withdraw the tokens and move from contract to the caller
require(ISYFP(_tokenAddress).transfer(msg.sender, _amount));
emit TokensClaimed(msg.sender, _amount);
}
function yieldWithdraw(address _tokenAddress) external {
Yield(_tokenAddress);
WithdrawFarmedTokens(_tokenAddress, users[msg.sender][_tokenAddress].activeDeposit);
}
//#########################################################################################################################################################//
//####################################################STAKING EXTERNAL FUNCTIONS###########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Start staking
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function Stake(uint256 _amount) external {
// add new stake
_newDeposit(SYFP, _amount);
// transfer tokens from user to the contract balance
require(ISYFP(SYFP).transferFrom(msg.sender, address(this), _amount));
emit Staked(msg.sender, _amount);
}
// ------------------------------------------------------------------------
// Add more deposits to already running farm
// @param _tokenAddress address of the token asset
// @param _amount amount of tokens to deposit
// ------------------------------------------------------------------------
function AddToStake(uint256 _amount) external {
require(now - users[msg.sender][SYFP].startTime < users[msg.sender][SYFP].period, "current staking expired");
_addToExisting(SYFP, _amount);
// move the tokens from the caller to the contract address
require(ISYFP(SYFP).transferFrom(msg.sender,address(this), _amount));
emit AddedToExistingStake(msg.sender, _amount);
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimStakedTokens() public {
require(users[msg.sender][SYFP].activeDeposit > 0, "no running stake");
require(users[msg.sender][SYFP].startTime.add(users[msg.sender][SYFP].period) < now, "not claimable before staking period");
uint256 _currentDeposit = users[msg.sender][SYFP].activeDeposit;
// check if we have any pending reward, add it to pendingGains var
users[msg.sender][SYFP].pendingGains = PendingReward(msg.sender);
tokens[SYFP].stakedTokens = tokens[SYFP].stakedTokens.sub(users[msg.sender][SYFP].activeDeposit);
// update amount
users[msg.sender][SYFP].activeDeposit = 0;
// transfer staked tokens
require(ISYFP(SYFP).transfer(msg.sender, _currentDeposit));
emit TokensClaimed(msg.sender, _currentDeposit);
}
function ClaimUnStake() external {
ClaimReward();
ClaimStakedTokens();
}
// ------------------------------------------------------------------------
// Claim reward and staked tokens
// @required user must be a staker
// @required must be claimable
// ------------------------------------------------------------------------
function ClaimReward() public payable {
require(msg.value >= stakeClaimFee, "should pay exact claim fee");
require(PendingReward(msg.sender) > 0, "nothing pending to claim");
uint256 _pendingReward = PendingReward(msg.sender);
// add claimed reward to global stats
totalRewards = totalRewards.add(_pendingReward);
// add the reward to total claimed rewards
users[msg.sender][SYFP].totalGained = users[msg.sender][SYFP].totalGained.add(_pendingReward);
// update lastClaim amount
users[msg.sender][SYFP].lastClaimedDate = now;
// reset previous rewards
users[msg.sender][SYFP].pendingGains = 0;
// transfer the claim fee to the owner
owner.transfer(msg.value);
// mint more tokens inside token contract
ISYFP(SYFP).mint(msg.sender, _pendingReward);
emit RewardClaimed(msg.sender, _pendingReward);
}
//#########################################################################################################################################################//
//##########################################################FARMING QUERIES################################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Query to get the pending yield
// @param _tokenAddress address of the token asset
// ------------------------------------------------------------------------
function PendingYield(address _tokenAddress, address _caller) public view returns(uint256 _pendingRewardWeis){
uint256 _totalFarmingTime = now.sub(users[_caller][_tokenAddress].lastClaimedDate);
uint256 _reward_token_second = ((tokens[_tokenAddress].rate).mul(10 ** 21)).div(365 days); // added extra 10^21
uint256 yield = ((users[_caller][_tokenAddress].activeDeposit).mul(_totalFarmingTime.mul(_reward_token_second))).div(10 ** 27); // remove extra 10^21 // 10^2 are for 100 (%)
return yield.add(users[_caller][_tokenAddress].pendingGains);
}
// ------------------------------------------------------------------------
// Query to get the active farm of the user
// @param farming asset/ token address
// ------------------------------------------------------------------------
function ActiveFarmDeposit(address _tokenAddress, address _user) external view returns(uint256 _activeDeposit){
return users[_user][_tokenAddress].activeDeposit;
}
// ------------------------------------------------------------------------
// Query to get the total farming of the user
// @param farming asset/ token address
// ------------------------------------------------------------------------
function YourTotalFarmingTillToday(address _tokenAddress, address _user) external view returns(uint256 _totalFarming){
return users[_user][_tokenAddress].totalDeposits;
}
// ------------------------------------------------------------------------
// Query to get the time of last farming of user
// ------------------------------------------------------------------------
function LastFarmedOn(address _tokenAddress, address _user) external view returns(uint256 _unixLastFarmedTime){
return users[_user][_tokenAddress].startTime;
}
// ------------------------------------------------------------------------
// Query to get total earned rewards from particular farming
// @param farming asset/ token address
// ------------------------------------------------------------------------
function TotalFarmingRewards(address _tokenAddress, address _user) external view returns(uint256 _totalEarned){
return users[_user][_tokenAddress].totalGained;
}
//#########################################################################################################################################################//
//####################################################FARMING ONLY OWNER FUNCTIONS#########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Add supported tokens
// @param _tokenAddress address of the token asset
// @param _farmingRate rate applied for farming yield to produce
// @required only owner or governance contract
// ------------------------------------------------------------------------
function AddToken(address _tokenAddress, uint256 _rate) public onlyOwner {
_addToken(_tokenAddress, _rate);
}
// ------------------------------------------------------------------------
// Remove tokens if no longer supported
// @param _tokenAddress address of the token asset
// @required only owner or governance contract
// ------------------------------------------------------------------------
function RemoveToken(address _tokenAddress) public onlyOwner {
require(tokens[_tokenAddress].exists, "token doesn't exist");
tokens[_tokenAddress].exists = false;
emit TokenRemoved(_tokenAddress, tokens[_tokenAddress].rate);
}
// ------------------------------------------------------------------------
// Change farming rate of the supported token
// @param _tokenAddress address of the token asset
// @param _newFarmingRate new rate applied for farming yield to produce
// @required only owner or governance contract
// ------------------------------------------------------------------------
function ChangeFarmingRate(address _tokenAddress, uint256 _newFarmingRate) public onlyOwner{
require(tokens[_tokenAddress].exists, "token doesn't exist");
tokens[_tokenAddress].rate = _newFarmingRate;
emit FarmingRateChanged(_tokenAddress, _newFarmingRate);
}
// ------------------------------------------------------------------------
// Change Yield collection fee
// @param _fee fee to claim the yield
// @required only owner or governance contract
// ------------------------------------------------------------------------
function SetYieldCollectionFee(uint256 _fee) public onlyOwner{
yieldCollectionFee = _fee;
emit YieldCollectionFeeChanged(_fee);
}
//#########################################################################################################################################################//
//####################################################STAKING QUERIES######################################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Query to get the pending reward
// ------------------------------------------------------------------------
function PendingReward(address _caller) public view returns(uint256 _pendingReward){
uint256 _totalStakedTime = 0;
uint256 expiryDate = (users[_caller][SYFP].period).add(users[_caller][SYFP].startTime);
if(now < expiryDate)
_totalStakedTime = now.sub(users[_caller][SYFP].lastClaimedDate);
else{
if(users[_caller][SYFP].lastClaimedDate >= expiryDate) // if claimed after expirydate already
_totalStakedTime = 0;
else
_totalStakedTime = expiryDate.sub(users[_caller][SYFP].lastClaimedDate);
}
uint256 _reward_token_second = ((users[_caller][SYFP].rate).mul(10 ** 21)); // added extra 10^21
uint256 reward = ((users[_caller][SYFP].activeDeposit).mul(_totalStakedTime.mul(_reward_token_second))).div(10 ** 27); // remove extra 10^21 // the two extra 10^2 is for 100 (%) // another two extra 10^4 is for decimals to be allowed
reward = reward.div(365 days);
return (reward.add(users[_caller][SYFP].pendingGains));
}
// ------------------------------------------------------------------------
// Query to get the active stake of the user
// ------------------------------------------------------------------------
function YourActiveStake(address _user) external view returns(uint256 _activeStake){
return users[_user][SYFP].activeDeposit;
}
// ------------------------------------------------------------------------
// Query to get the total stakes of the user
// ------------------------------------------------------------------------
function YourTotalStakesTillToday(address _user) external view returns(uint256 _totalStakes){
return users[_user][SYFP].totalDeposits;
}
// ------------------------------------------------------------------------
// Query to get the time of last stake of user
// ------------------------------------------------------------------------
function LastStakedOn(address _user) public view returns(uint256 _unixLastStakedTime){
return users[_user][SYFP].startTime;
}
// ------------------------------------------------------------------------
// Query to get total earned rewards from stake
// ------------------------------------------------------------------------
function TotalStakeRewardsClaimedTillToday(address _user) external view returns(uint256 _totalEarned){
return users[_user][SYFP].totalGained;
}
// ------------------------------------------------------------------------
// Query to get the staking rate
// ------------------------------------------------------------------------
function LatestStakingRate() external view returns(uint256 APY){
return tokens[SYFP].rate;
}
// ------------------------------------------------------------------------
// Query to get the staking rate you staked at
// ------------------------------------------------------------------------
function YourStakingRate(address _user) external view returns(uint256 _stakingRate){
return users[_user][SYFP].rate;
}
// ------------------------------------------------------------------------
// Query to get the staking period you staked at
// ------------------------------------------------------------------------
function YourStakingPeriod(address _user) external view returns(uint256 _stakingPeriod){
return users[_user][SYFP].period;
}
// ------------------------------------------------------------------------
// Query to get the staking time left
// ------------------------------------------------------------------------
function StakingTimeLeft(address _user) external view returns(uint256 _secsLeft){
uint256 left = 0;
uint256 expiryDate = (users[_user][SYFP].period).add(LastStakedOn(_user));
if(now < expiryDate)
left = expiryDate.sub(now);
return left;
}
//#########################################################################################################################################################//
//####################################################STAKING ONLY OWNER FUNCTION##########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Change staking rate
// @param _newStakingRate new rate applied for staking
// @required only owner or governance contract
// ------------------------------------------------------------------------
function ChangeStakingRate(uint256 _newStakingRate) public onlyOwner{
tokens[SYFP].rate = _newStakingRate;
emit StakingRateChanged(_newStakingRate);
}
// ------------------------------------------------------------------------
// Change the staking period
// @param _seconds number of seconds to stake (n days = n*24*60*60)
// @required only callable by owner or governance contract
// ------------------------------------------------------------------------
function SetStakingPeriod(uint256 _seconds) public onlyOwner{
stakingPeriod = _seconds;
}
// ------------------------------------------------------------------------
// Change the staking claim fee
// @param _fee claim fee in weis
// @required only callable by owner or governance contract
// ------------------------------------------------------------------------
function SetClaimFee(uint256 _fee) public onlyOwner{
stakeClaimFee = _fee;
}
//#########################################################################################################################################################//
//################################################################COMMON UTILITIES#########################################################################//
//#########################################################################################################################################################//
// ------------------------------------------------------------------------
// Internal function to add new deposit
// ------------------------------------------------------------------------
function _newDeposit(address _tokenAddress, uint256 _amount) internal{
require(users[msg.sender][_tokenAddress].activeDeposit == 0, "Already running");
require(tokens[_tokenAddress].exists, "Token doesn't exist");
// add that token into the contract balance
// check if we have any pending reward/yield, add it to pendingGains variable
if(_tokenAddress == SYFP){
users[msg.sender][_tokenAddress].pendingGains = PendingReward(msg.sender);
users[msg.sender][_tokenAddress].period = stakingPeriod;
users[msg.sender][_tokenAddress].rate = tokens[_tokenAddress].rate; // rate for stakers will be fixed at time of staking
}
else
users[msg.sender][_tokenAddress].pendingGains = PendingYield(_tokenAddress, msg.sender);
users[msg.sender][_tokenAddress].activeDeposit = _amount;
users[msg.sender][_tokenAddress].totalDeposits = users[msg.sender][_tokenAddress].totalDeposits.add(_amount);
users[msg.sender][_tokenAddress].startTime = now;
users[msg.sender][_tokenAddress].lastClaimedDate = now;
tokens[_tokenAddress].stakedTokens = tokens[_tokenAddress].stakedTokens.add(_amount);
}
// ------------------------------------------------------------------------
// Internal function to add to existing deposit
// ------------------------------------------------------------------------
function _addToExisting(address _tokenAddress, uint256 _amount) internal{
require(tokens[_tokenAddress].exists, "Token doesn't exist");
// require(users[msg.sender][_tokenAddress].running, "no running farming/stake");
require(users[msg.sender][_tokenAddress].activeDeposit > 0, "no running farming/stake");
// update farming stats
// check if we have any pending reward/yield, add it to pendingGains variable
if(_tokenAddress == SYFP){
users[msg.sender][_tokenAddress].pendingGains = PendingReward(msg.sender);
users[msg.sender][_tokenAddress].period = stakingPeriod;
users[msg.sender][_tokenAddress].rate = tokens[_tokenAddress].rate; // rate of only staking will be updated when more is added to stake
}
else
users[msg.sender][_tokenAddress].pendingGains = PendingYield(_tokenAddress, msg.sender);
// update current deposited amount
users[msg.sender][_tokenAddress].activeDeposit = users[msg.sender][_tokenAddress].activeDeposit.add(_amount);
// update total deposits till today
users[msg.sender][_tokenAddress].totalDeposits = users[msg.sender][_tokenAddress].totalDeposits.add(_amount);
// update new deposit start time -- new stake/farming will begin from this time onwards
users[msg.sender][_tokenAddress].startTime = now;
// reset last claimed figure as well -- new stake/farming will begin from this time onwards
users[msg.sender][_tokenAddress].lastClaimedDate = now;
tokens[_tokenAddress].stakedTokens = tokens[_tokenAddress].stakedTokens.add(_amount);
}
// ------------------------------------------------------------------------
// Internal function to add token
// ------------------------------------------------------------------------
function _addToken(address _tokenAddress, uint256 _rate) internal{
require(!tokens[_tokenAddress].exists, "token already exists");
tokens[_tokenAddress] = Tokens({
exists: true,
rate: _rate,
stakedTokens: 0
});
TokensAddresses.push(_tokenAddress);
emit TokenAdded(_tokenAddress, _rate);
}
} | ------------------------------------------------------------------------ Query to get the pending yield _tokenAddress address of the token asset ------------------------------------------------------------------------ | function PendingYield(address _tokenAddress, address _caller) public view returns(uint256 _pendingRewardWeis){
uint256 _totalFarmingTime = now.sub(users[_caller][_tokenAddress].lastClaimedDate);
return yield.add(users[_caller][_tokenAddress].pendingGains);
}
| 15,358,923 |
./partial_match/1/0x10eC0D497824e342bCB0EDcE00959142aAa766dD/sources/IdleToken.sol | Mint protocol tokens through protocol wrapper _wrapperAddr : address of protocol wrapper _amount : amount of underlying to be lended return tokens : new tokens minted/ | function _mintProtocolTokens(address _wrapperAddr, uint256 _amount)
internal
returns (uint256 tokens) {
if (_amount == 0) {
return tokens;
}
ILendingProtocol _wrapper = ILendingProtocol(_wrapperAddr);
tokens = _wrapper.mint();
}
| 4,112,257 |
./full_match/1/0x6E89Fd91e093691d2e3071e52898dd7Df725a9C3/sources/contracts/TTMarketplace.sol | / Delete the listing if no tokens have been sold yet. Note: Keeping most safety checks in child function so they are only performed if we are deleting | function cancelList(uint256 _sellId) external returns (bool) {
if (sales[_sellId].seller != _msgSender()) {
revert MustBeSeller();
}
if (sales[_sellId].amountofTokenSold == 0) {
return _deleteList(_sellId);
return _cancelList(_sellId);
}
}
| 17,015,157 |
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
pragma solidity ^0.5.0;
/**
* @title Elliptic curve signature operations
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*/
library ECDSA {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param signature bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* and hash the result
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/IndexedMerkleProof.sol
pragma solidity ^0.5.2;
library IndexedMerkleProof {
function verify(bytes memory proof, uint160 root, uint160 leaf, uint index) internal pure returns (bool) {
// Check if the computed hash (root) is equal to the provided root
return root == compute(proof, leaf, index);
}
function compute(bytes memory proof, uint160 leaf, uint index) internal pure returns (uint160) {
uint160 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
uint160 proofElement;
assembly {
proofElement := div(mload(add(proof, 32)), 0x1000000000000000000000000)
}
if (index & (1 << i) == 0) {
// Hash(current computed hash + current element of the proof)
computedHash = uint160(uint256(keccak256(abi.encodePacked(computedHash, proofElement))));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = uint160(uint256(keccak256(abi.encodePacked(proofElement, computedHash))));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash;
}
}
// File: contracts/CertCenter.sol
pragma solidity ^0.5.2;
contract CertCenter is Ownable {
mapping(address => bool) public renters;
event RenterAdded(address indexed renter);
event RenterRemoved(address indexed renter);
function updateRenters(
address[] calldata rentersToRemove,
address[] calldata rentersToAdd
)
external
onlyOwner
{
for (uint i = 0; i < rentersToRemove.length; i++) {
if (renters[rentersToRemove[i]]) {
delete renters[rentersToRemove[i]];
emit RenterRemoved(rentersToRemove[i]);
}
}
for (uint i = 0; i < rentersToAdd.length; i++) {
if (!renters[rentersToAdd[i]]) {
renters[rentersToAdd[i]] = true;
emit RenterAdded(rentersToAdd[i]);
}
}
}
}
// File: contracts/Vehicle.sol
pragma solidity ^0.5.2;
contract Vehicle {
address public vehicle;
modifier onlyVehicle {
require(msg.sender == vehicle);
_;
}
constructor(address vehicleAddress) public {
require(vehicleAddress != address(0));
vehicle = vehicleAddress;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts/IKyberNetwork.sol
pragma solidity ^0.5.2;
contract IKyberNetwork {
function trade(
address src,
uint256 srcAmount,
address dest,
address destAddress,
uint256 maxDestAmount,
uint256 minConversionRate,
address walletId
)
public
payable
returns(uint);
function getExpectedRate(
address source,
address dest,
uint srcQty
)
public
view
returns (
uint expectedPrice,
uint slippagePrice
);
}
// File: contracts/AnyPaymentReceiver.sol
pragma solidity ^0.5.2;
contract AnyPaymentReceiver is Ownable {
using SafeMath for uint256;
address constant public ETHER_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
function _processPayment(
IKyberNetwork kyber,
address desiredToken,
address paymentToken,
uint256 paymentAmount
)
internal
returns(uint256)
{
uint256 previousBalance = _balanceOf(desiredToken);
// Receive payment
if (paymentToken != address(0)) {
require(IERC20(paymentToken).transferFrom(msg.sender, address(this), paymentAmount));
} else {
require(msg.value >= paymentAmount);
}
// Convert payment if needed
if (paymentToken != desiredToken) {
if (paymentToken != address(0)) {
IERC20(paymentToken).approve(address(kyber), paymentAmount);
}
kyber.trade.value(msg.value)(
(paymentToken == address(0)) ? ETHER_ADDRESS : paymentToken,
(paymentToken == address(0)) ? msg.value : paymentAmount,
(desiredToken == address(0)) ? ETHER_ADDRESS : desiredToken,
address(this),
1 << 255,
0,
address(0)
);
}
uint256 currentBalance = _balanceOf(desiredToken);
return currentBalance.sub(previousBalance);
}
function _balanceOf(address token) internal view returns(uint256) {
if (token == address(0)) {
return address(this).balance;
}
return IERC20(token).balanceOf(address(this));
}
function _returnRemainder(address payable renter, IERC20 token, uint256 remainder) internal {
if (token == IERC20(0)) {
renter.transfer(remainder);
} else {
token.transfer(renter, remainder);
}
}
}
// File: contracts/Car.sol
pragma solidity ^0.5.2;
contract Car is Ownable, Vehicle, AnyPaymentReceiver {
using ECDSA for bytes;
using IndexedMerkleProof for bytes;
enum State {
NotAvailable,
AlreadyBooked,
AlreadyRented,
AvailableForRent,
ReturningToHome
}
struct Tariff {
IERC20 desiredToken;
uint256 pricePerMinute;
uint256 minimumCost;
uint256 bookingCost;
uint256 maxTime;
}
State public state;
Tariff public tariff;
mapping(address => uint256) public renterDeposits;
mapping(uint160 => uint) public expiringCodesMerkleRoots;
mapping(address => bool) public trustedCertCenters;
event StateUpdated(State indexed newState, State indexed oldState);
event TariffUpdated();
event ExpiringCodeAdded(uint160 indexed expiringCode);
event ExpiringCodeRemoved(uint160 indexed expiringCode);
event CertCenterAdded(address indexed certCenter);
event CertCenterRemoved(address indexed certCenter);
event LocationUpdated(uint256 latitude, uint256 longitude);
event EncryptedLocationUpdated(bytes32 encKey, uint256 encLatitude, uint256 encLongitude);
event DepositAdded(address indexed renter, uint256 amount);
constructor(address vehicle)
public
Vehicle(vehicle)
{
}
// Owner methods
function updateState(State newState) external onlyOwner {
require(state != newState);
emit StateUpdated(newState, state);
state = newState;
}
function updateTariff(
IERC20 desiredToken,
uint256 pricePerMinute,
uint256 minimumCost,
uint256 bookingCost,
uint256 maxTime
)
external
onlyOwner
{
require(state == State.NotAvailable);
emit TariffUpdated();
tariff = Tariff({
desiredToken: desiredToken,
pricePerMinute: pricePerMinute,
minimumCost: minimumCost,
bookingCost: bookingCost,
maxTime: maxTime
});
}
function updateCertCenters(
address[] calldata notYetTrustedCertCenters,
address[] calldata alreadyTrustedCertCenters
)
external
onlyOwner
{
for (uint i = 0; i < alreadyTrustedCertCenters.length; i++) {
if (trustedCertCenters[alreadyTrustedCertCenters[i]]) {
delete trustedCertCenters[alreadyTrustedCertCenters[i]];
emit CertCenterRemoved(alreadyTrustedCertCenters[i]);
}
}
for (uint i = 0; i < notYetTrustedCertCenters.length; i++) {
if (!trustedCertCenters[notYetTrustedCertCenters[i]]) {
trustedCertCenters[notYetTrustedCertCenters[i]] = true;
emit CertCenterAdded(notYetTrustedCertCenters[i]);
}
}
}
// Vehicle methods
function addExpiringCode(
uint160 notYetExpiredCode,
uint160[] calldata alreadyExpiredCodes
)
external
onlyVehicle
{
require(state == State.AvailableForRent);
for (uint i = 0; i < alreadyExpiredCodes.length; i++) {
if (expiringCodesMerkleRoots[alreadyExpiredCodes[i]] != 0) {
delete expiringCodesMerkleRoots[alreadyExpiredCodes[i]];
emit ExpiringCodeRemoved(alreadyExpiredCodes[i]);
}
}
if (expiringCodesMerkleRoots[notYetExpiredCode] == 0) {
expiringCodesMerkleRoots[notYetExpiredCode] = now;
emit ExpiringCodeAdded(notYetExpiredCode);
}
}
function postLocation(uint256 latitude, uint256 longitude) public onlyVehicle {
require(state != State.AlreadyRented);
emit LocationUpdated(latitude, longitude);
}
function postEncryptedLocation(bytes32 encKey, uint256 encLatitude, uint256 encLongitude) public onlyVehicle {
require(state != State.AlreadyRented);
emit EncryptedLocationUpdated(encKey, encLatitude, encLongitude);
}
// Renter methods
function book(
IKyberNetwork kyber, // 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
CertCenter certCenter,
address paymentToken,
uint256 paymentAmount
)
external
payable
{
require(state == State.AvailableForRent || state == State.ReturningToHome);
require(trustedCertCenters[address(certCenter)], "Not trusted cert center");
require(certCenter.renters(msg.sender), "Renter check fails");
uint256 deposit = _processPayment(kyber, address(tariff.desiredToken), paymentToken, paymentAmount);
renterDeposits[msg.sender] = renterDeposits[msg.sender].add(deposit);
require(renterDeposits[msg.sender] >= tariff.bookingCost);
emit DepositAdded(msg.sender, deposit);
emit StateUpdated(State.AlreadyBooked, state);
state = State.AlreadyBooked;
}
function cancelBooking() external {
require(state == State.AlreadyBooked && renterDeposits[msg.sender] != 0);
_returnRemainder(msg.sender, tariff.desiredToken, renterDeposits[msg.sender]);
renterDeposits[msg.sender] = 0;
emit StateUpdated(State.AvailableForRent, state);
state = State.AvailableForRent;
}
function rent(
IKyberNetwork kyber, // 0x818E6FECD516Ecc3849DAf6845e3EC868087B755;
CertCenter certCenter,
address paymentToken,
uint256 paymentAmount,
bytes calldata signature,
uint256 merkleIndex,
bytes calldata merkleProof
)
external
{
require(state == State.AvailableForRent ||
state == State.ReturningToHome);
require(state == State.AlreadyBooked && renterDeposits[msg.sender] != 0);
require(trustedCertCenters[address(certCenter)], "Not trusted cert center");
require(certCenter.renters(msg.sender), "Renter check fails");
bytes32 messageHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(msg.sender)));
address signer = ECDSA.recover(messageHash, signature);
uint160 merkleRoot = merkleProof.compute(uint160(signer), merkleIndex);
require(expiringCodesMerkleRoots[merkleRoot] != 0);
uint256 time = expiringCodesMerkleRoots[merkleRoot] + merkleIndex * 60 * 5;
require(time < now + 60 * 5);
uint256 deposit = _processPayment(kyber, address(tariff.desiredToken), paymentToken, paymentAmount);
renterDeposits[msg.sender] = renterDeposits[msg.sender].add(deposit);
require(renterDeposits[msg.sender] >= tariff.minimumCost);
emit DepositAdded(msg.sender, deposit);
emit StateUpdated(State.AlreadyRented, state);
state = State.AlreadyRented;
}
}
| Hash(current computed hash + current element of the proof) Hash(current element of the proof + current computed hash) | function compute(bytes memory proof, uint160 leaf, uint index) internal pure returns (uint160) {
uint160 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
uint160 proofElement;
assembly {
proofElement := div(mload(add(proof, 32)), 0x1000000000000000000000000)
}
if (index & (1 << i) == 0) {
computedHash = uint160(uint256(keccak256(abi.encodePacked(computedHash, proofElement))));
computedHash = uint160(uint256(keccak256(abi.encodePacked(proofElement, computedHash))));
}
}
}
| 6,433,709 |
./partial_match/1/0x60bb1e2AA1c9ACAfB4d34F71585D7e959f387769/sources/src/Pages.sol | Mint a number of pages to the community reserve. numPages The number of pages to mint to the reserve. Pages minted to the reserve cannot comprise more than 10% of the sum of the supply of goo minted pages and the supply of pages minted to the community reserve. Optimistically increment numMintedForCommunity, may be reverted below. Overflow in this calculation is possible but numPages would have to be so large that it would cause the loop in _batchMint to run out of gas quickly. Ensure that after this mint pages minted to the community reserve won't comprise more than 10% of the new total page supply. currentId is equivalent to the current total supply of pages. Mint the pages to the community reserve and update lastMintedPageId once minting is complete. | function mintCommunityPages(uint256 numPages) external returns (uint256 lastMintedPageId) {
unchecked {
uint256 newNumMintedForCommunity = numMintedForCommunity += uint128(numPages);
if (newNumMintedForCommunity > ((lastMintedPageId = currentId) + numPages) / 10) revert ReserveImbalance();
lastMintedPageId = _batchMint(community, numPages, lastMintedPageId);
emit CommunityPagesMinted(msg.sender, lastMintedPageId, numPages);
}
}
TOKEN URI LOGIC
| 2,819,461 |
./full_match/4/0x6DD820D8036D0bD734E4DDCFE07b849beC43717F/sources/contracts/artifacts/FundMe.sol | antes de transferir necesitamos comprobar que el sender es el propietario, de eso se encargará el constructor | function withDraw() payable onlyOwner public {
msg.sender.transfer(address(this).balance);
for(uint256 funderIndex = 0; funderIndex < funders.length; funderIndex++)
{
address funder = funders[funderIndex];
addressToAmountFunded[funder] = 0;
}
funders = new address[](0);
}
| 768,631 |
./full_match/5/0x82Adf690957264981e5Ede120fE7C48F2334402c/sources/contracts/Contract.sol | is everything okay? | function createCampaign(address _owner, string memory _title, string memory _description, uint256 _target, uint256 _deadline, string memory _image) public returns (uint256){
Campaign storage campaign = campaigns[numberOfCampaigns];
require(campaign.deadline < block.timestamp, "The deadline should be a date in the future.");
campaign.owner = _owner;
campaign.title = _title;
campaign.description = _description;
campaign.target = _target;
campaign.deadline = _deadline;
campaign.amountCollected = 0;
campaign.image = _image;
numberOfCampaigns++;
return numberOfCampaigns - 1;
}
| 7,040,791 |
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "./BDERC1155Tradable.sol";
import "./IWarrior.sol";
import "./IRegion.sol";
//Import ERC1155 standard for utilizing FAME tokens
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
///@title LootChestCollectible
///@notice The contract for managing BattleDrome Loot Chest Tokens
contract LootChestCollectible is BDERC1155Tradable, ERC1155Holder {
//////////////////////////////////////////////////////////////////////////////////////////
// Config
//////////////////////////////////////////////////////////////////////////////////////////
//Fungible Token Tiers
enum ChestType {
NULL,
BRONZE,
SILVER,
GOLD,
DIAMOND
}
//Chest level multipliers are used in math throughout, this is done by taking the integerized value of ChestType
//ie:
// bronze = 1
// silver = 2
// gold = 3
// diamond = 4
//And then taking 2 ^ ({val}-1)
//So the resulting multipliers would be for example:
// bronze = 1
// silver = 2
// gold = 4
// diamond = 8
//Chest Contents Constants
//Base value is multiplied by the appropriate chest level multiplier
uint constant FIXED_VALUE_BASE = 125;
//Chance Constants - chance/10000 eg: 100.00%
//This applies to the bronze level chests, each subsequent chest has chances multiplied by it's multiplier
uint constant CHANCE_BONUS_10 = 500; //5% - Bronze, 10% - Silver, 20% - Gold, 40% - Diamond
uint constant CHANCE_BONUS_25 = 200; //2% - Bronze, 4% - Silver, 8% - Gold, 16% - Diamond
uint constant CHANCE_BONUS_50 = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_WARRIOR = 100; //1% - Bronze, 2% - Silver, 4% - Gold, 8% - Diamond
uint constant CHANCE_BONUS_REGION = 5; //0.05% - Bronze, 0.1% - Silver, 0.2% - Gold, 0.4% - Diamond
//Costing Constants
uint constant ICO_BASE_FAME_VALUE = 10000000 gwei;
uint constant NEW_FAME_PER_OLD = 1000;
uint constant NEW_FAME_ICO_VALUE = ICO_BASE_FAME_VALUE / NEW_FAME_PER_OLD;
uint constant VOLUME_DISCOUNT_PERCENT = 1; //Cost break when increasing tier when calculating cost of a chest tier
//ie: this percentage is multiplied by the multiplier, and applied as a discount to price
uint constant MIN_DEMAND_RATIO = 5000; //Percent * 10000 similar to chances above
uint constant MAX_DEMAND_RATIO = 20000; //Percent * 10000 similar to chances above
//Other Misc Config Constants
uint8 constant RECENT_SALES_TO_TRACK = 64; //Max of last 32 sales
uint constant RECENT_SALES_TIME_SECONDS = 86400 * 30; //Max of last 30 days
//////////////////////////////////////////////////////////////////////////////////////////
// Structs
//////////////////////////////////////////////////////////////////////////////////////////
struct ChestSale {
uint64 timestamp;
uint8 chest_type;
uint32 quantity;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Local Storage Variables
//////////////////////////////////////////////////////////////////////////////////////////
//Associated Contracts
IERC1155 FAMEContract;
uint256 FAMETokenID;
IWarrior WarriorContract;
IRegion RegionContract;
//Sales History (Demand Tracking)
ChestSale[RECENT_SALES_TO_TRACK] recentSales;
uint currentSaleIndex = 0;
//////////////////////////////////////////////////////////////////////////////////////////
// Constructor
//////////////////////////////////////////////////////////////////////////////////////////
constructor(address _proxyRegistryAddress)
BDERC1155Tradable(
"LootChestCollectible",
"BDLC",
_proxyRegistryAddress,
"https://metadata.battledrome.io/api/erc1155-loot-chest/"
)
{
}
//////////////////////////////////////////////////////////////////////////////////////////
// Errors
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice The contract does not have sufficient FAME to support `requested` chests of type `chestType`, maximum of `maxPossible` can be created with current balance.
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param requested The number of chests requested
*@param maxPossible The maximum number of chests of the requested type that can be created with current balance
*/
error InsufficientContractBalance(uint8 chestType, uint256 requested, uint256 maxPossible);
/**
*@notice Insufficient Ether sent for the requested action. You sent `sent` Wei but `required` Wei was required
*@param sent The amount of Ether (in Wei) that was sent by the caller
*@param required The amount of Ether (in Wei) that was actually required for the requested action
*/
error InsufficientEther(uint256 sent, uint256 required);
/**
*@notice Insufficient Chests of type: `chestType`, you only have `balance` chests of that type!
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param balance The number of chests the user currently has of the specified type
*/
error InsufficientChests(uint8 chestType, uint256 balance);
/**
*@notice Error minting new Warrior NFT!
*@param code Error Code
*/
error ErrorMintingWarrior(uint code);
/**
*@notice Error minting new Region NFT!
*@param code Error Code
*/
error ErrorMintingRegion(uint code);
//////////////////////////////////////////////////////////////////////////////////////////
// Events
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Indicates that a user `opener` opened `quantity` chests of type `chestType` at `timeStamp`
*@param opener The address that opened the chests
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests opened in this event
*@param timeStamp the timestamp that the chests were opened
*@param fame The amount of FAME found in the box(s)
*@param warriors The number of warriors found in the box(s)
*@param regions The number of regions found in the box(s)
*/
event LootBoxOpened(address indexed opener, uint8 indexed chestType, uint32 quantity, uint32 timeStamp, uint32 fame, uint32 warriors, uint32 regions);
//////////////////////////////////////////////////////////////////////////////////////////
// ERC1155 Overrides/Functions
//////////////////////////////////////////////////////////////////////////////////////////
function contractURI() public pure returns (string memory) {
return "https://metadata.battledrome.io/contract/erc1155-loot-chest";
}
function onERC1155Received(
address _operator,
address _from,
uint256 _id,
uint256 _amount,
bytes calldata _data
) public override returns (bytes4) {
require(
(
(msg.sender == address(FAMEContract) && _id == FAMETokenID) || //Allow reciept of FAME tokens
msg.sender == address(RegionContract) || //Allow Region Contract to send us Region NFTs (to forward to users)
msg.sender == address(this) //Allow any internal transaction originated here
),
"INVALID_TOKEN!" //Otherwise kick back INVALID_TOKEN error code, preventing the transfer.
);
bytes4 rv = super.onERC1155Received(_operator, _from, _id, _amount, _data);
return rv;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(BDERC1155Tradable, ERC1155Receiver)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Buy/Sell
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Buy a number of chests of the specified type, paying ETH
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to buy
*/
function buy(ChestType chestType, uint quantity) public payable {
//First, is it possible to buy the proposed chests? If not, then revert to prevent people wasting money
uint maxCreatable = maxSafeCreatable(chestType);
if(maxCreatable >= quantity){
//We have sufficient balance to create at least the requested amount
//So calculate the required price of the requested chests:
uint price = getPrice(chestType) * quantity;
//Did the user send enough?
if(msg.value>=price){
//Good, they paid enough... Let's mint their chests then!
_mint(msg.sender, uint(chestType), quantity, "");
tokenSupply[uint(chestType)] = tokenSupply[uint(chestType)] + quantity; //Because we're bypassing the normal mint function.
ChestSale storage saleRecord = recentSales[(currentSaleIndex++)%RECENT_SALES_TO_TRACK];
saleRecord.timestamp = uint64(block.timestamp);
saleRecord.chest_type = uint8(chestType);
saleRecord.quantity = uint32(quantity);
//Check if they overpaid and refund:
if(msg.value>price){
payable(msg.sender).transfer(msg.value-price);
}
}else{
//Bad monkey! Not enough money!
revert InsufficientEther(msg.value,price);
}
}else{
//Insufficient balance, throw error:
revert InsufficientContractBalance(uint8(chestType), quantity, maxCreatable);
}
}
/**
*@notice Sell a number of FAME back to the contract, in exchange for whatever the current payout is.
*@param quantity The number of FAME to sell
*/
function sell(uint quantity) public {
uint payOutAmount = getBuyBackPrice(quantity);
transferFAME(msg.sender,address(this),quantity);
require(address(this).balance>=payOutAmount,"CONTRACT BALANCE ERROR!");
if(payOutAmount>0) payable(msg.sender).transfer(payOutAmount);
}
//////////////////////////////////////////////////////////////////////////////////////////
// Loot Box Opening
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Open a number of your owned chests of the specified type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@param quantity The number of chests to open
*@return fameReward The amount of FAME found in the chests
*@return warriors The number of bonus Warriors found in the chests
*@return regions The number of bonus Regions found in the chests
*/
function open(ChestType chestType, uint quantity) public ownersOnly(uint(chestType)) returns (uint fameReward, uint warriors, uint regions) {
//First let's confirm if the user actually owns enough chests of the appropriate type that they've requested
uint balance = balanceOf(msg.sender, uint(chestType));
if(balance >= quantity){
fameReward = 0;
warriors = 0;
regions = 0;
uint chestTypeMultiplier = (2**(uint(chestType)-1));
uint baseFAMEReward = FIXED_VALUE_BASE * chestTypeMultiplier;
//Burn the appropriate number of chests:
_burn(msg.sender,uint(chestType),quantity);
//Iterate the chests requested to calculate rewards
for(uint chest=0;chest<quantity;chest++){
//Calculate the FAME Reward amount for this chest:
uint fameRoll = roll(chest*2+0);
if(fameRoll<(CHANCE_BONUS_50 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1500 / 1000;
}else if(fameRoll<(CHANCE_BONUS_25 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1250 / 1000;
}else if(fameRoll<(CHANCE_BONUS_10 * chestTypeMultiplier)){
fameReward += baseFAMEReward * 1100 / 1000;
}else{
fameReward += baseFAMEReward;
}
//Calculate if any prize (NFT) was also received in this chest:
uint prizeRoll = roll(chest*2+1);
if(prizeRoll<(CHANCE_BONUS_REGION * chestTypeMultiplier)){
//Woohoo! Won a Region! BONUS!
regions++;
}else if(fameRoll<(CHANCE_BONUS_WARRIOR * chestTypeMultiplier)){
//Woohoo! Won a Warrior!
warriors++;
}
}
//Ok now that we've figured out their rewards, let's give it all to them!
//First the FAME:
transferFAME(address(this),msg.sender,fameReward);
//Now if there are regions or warriors in the rewards, mint the appropriate NFTs:
for(uint w=0;w<warriors;w++){
//Unfortunately because of how warrior minting works, we need to pre-generate some random traits:
// For the record this was chosen for a good reason, it's more flexible and supports a wider set of use cases
// But it is a bit more work when implementing in an external contract like this...
//First let's grab a random seed:
uint randomSeed = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number))));
//And then generate the remaining traits from it
uint16 colorHue = uint16(uint(keccak256(abi.encodePacked(randomSeed,uint8(1)))));
uint8 armorType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(2)))))%4;
uint8 shieldType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(3)))))%4;
uint8 weaponType = uint8(uint(keccak256(abi.encodePacked(randomSeed,uint8(4)))))%10;
//Now mint the warrior:
WarriorContract.mintCustomWarrior(msg.sender, 0, true, randomSeed, colorHue, armorType, shieldType, weaponType);
}
for(uint r=0;r<regions;r++){
//When minting Regions, the caller (this contract) will end up owning them, so we need to first mint, then change ownership:
//First we try to mint:
try RegionContract.trustedCreateRegion() returns (uint regionID){
//Now we transfer it to the user:
RegionContract.safeTransferFrom(address(this),msg.sender,regionID,1,"");
} catch Error(string memory reason) {
revert(reason);
} catch Panic(uint code) {
revert ErrorMintingRegion(code);
} catch (bytes memory) {
revert ErrorMintingRegion(0);
}
}
emit LootBoxOpened(msg.sender, uint8(chestType), uint32(quantity), uint32(block.timestamp), uint32(fameReward), uint32(warriors), uint32(regions));
}else{
//Bad monkey! You don't have that many chests to open!
revert InsufficientChests(uint8(chestType), balance);
}
}
//////////////////////////////////////////////////////////////////////////////////////////
// Costing Getters
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@notice Get the Base Value (guaranteed FAME contents) of a given chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return value The Value (amount of FAME) included in the chest type
*/
function getBaseValue(ChestType chestType) public pure returns (uint value) {
require(chestType > ChestType.NULL && chestType <= ChestType.DIAMOND, "ILLEGAL CHEST TYPE");
value = FIXED_VALUE_BASE * (2**(uint(chestType)-1));
}
/**
*@notice Get the recent sales volume (total amount of FAME sold in chest Base Values)
*@return volume The total Base Value (guaranteed included FAME) of all recent chest sales
*@dev This is used to figure out demand for costing math
*/
function getRecentSalesVolume() public view returns (uint volume) {
volume = 1; //To avoid div/0
for(uint i = 0; i<RECENT_SALES_TO_TRACK; i++){
if(recentSales[i].timestamp >= block.timestamp - RECENT_SALES_TIME_SECONDS){
volume += getBaseValue(ChestType(recentSales[i].chest_type)) * recentSales[i].quantity;
}
}
}
/**
*@notice Calculate the current FAME price (price per FAME token in ETH)
*@return price The current ETH price (in wei) of a single FAME token
*@dev This is used to calculate the "market floor" price for FAME so that we can use it to caluclate cost of chests.
*/
function getCurrentFAMEPrice() public view returns (uint price) {
//First we look at the current (available/non-liable) fame balance, and the recent sales volume, and calculate a demand ratio:
// Note: recent sales volume is always floored at the value of at least one of the max chest, which allows
// for the situation where there is zero supply, to incentivize seeding the supply to accommodate chest sales.
// Otherwise, what happens is if the contract runs dry, and no sales happen because there is no supply, the
// "recent sales" drop to zero, resulting in artificially deflated demand, even though "demand" might be high, but
// it can't be observed because lack of supply has choked off sales. (not to mention it also helps avoid div/0)
//ie: if we have 10,000 FAME, and we've recently only sold 1000, then we have 10:1 ratio so plenty of supply to meet the demand
// however if we have 1000 FAME, and recently sold 2000, we have a 0.5:1 ratio, so low supply, which should drive up price...
//Price is calculated by first calculating demand ratio, and then clamping it to min/max range (in config constants)
//Then taking the ICO base value of new FAME, and dividing by the demand ratio.
//As a practical example, let's assume the ICO base value was 10,000gwei per fame,
//And assume we have a demand ratio clamp range of 0.5 - 2.0
//Then the following table demonstrates how the demand ratios would equate to FAME price
//0.5:1 - 20,000 gwei/FAME
//0.75:1 - 13,333 gwei/FAME
//1:1 - 10,000 gwei/FAME
//1.25:1 - 8,000 gwei/FAME
//1.5:1 - 6,666 gwei/FAME
//1.75:1 - 5,714 gwei/FAME
//2:1 - 5,000 gwei/FAME
//Keep in mind this mechanism is designed to be a fallback to market liquidity. Ideally if the market is healthy, then on
//exchange sites such as OpenSea, or other token exchanges, FAME will trade for normal market value and this contract will be ignored.
//This contract serves a purpose during ramp-up of BattleDrome, to provide a buy-in mechanism, and a sell-off mechanism to distribute
//some of the FAME from ICO backers, to seed initial market distribution, and jump-start new players.
//It also serves a purpose if market liquidity results in poor conditions, provided people are still interested in the tokens/game
//As it will serve as a floor price mechanism, allowing holders to liquidate if there is some demand, and players to buy in if there is supply
//Get the raw sales volume
uint rawSalesVolume = getRecentSalesVolume();
//Find out the minimum sales volume (cost of a diamond chest)
uint minSalesVolume = getBaseValue(ChestType.DIAMOND);
//Raise the sales volume if needed
uint adjustedSalesVolume = (rawSalesVolume<minSalesVolume) ? minSalesVolume : rawSalesVolume;
//Now we figure out our "available balance"
uint availableBalance = getContractFAMEBalance() - calculateCurrentLiability();
//Calculate raw demand ratio
uint rawDemandRatio = (availableBalance * 10000) / adjustedSalesVolume;
//Then clamp the demand ratio within min/max bounds set in constants above
uint demandRatio = (rawDemandRatio<MIN_DEMAND_RATIO)?MIN_DEMAND_RATIO:(rawDemandRatio>MAX_DEMAND_RATIO)?MAX_DEMAND_RATIO:rawDemandRatio;
//And finally calculate the price based on resulting demand ratio
price = (NEW_FAME_ICO_VALUE * 10000) / demandRatio;
}
/**
*@notice Calculate the current price in Ether (wei) for the specified chest type
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return price The current ETH price (in wei) of a chest of that type
*/
function getPrice(ChestType chestType) public view returns (uint price) {
uint8 discountedPriceMultiplier = uint8(100 - (VOLUME_DISCOUNT_PERCENT * (2**(uint(chestType)-1))));
price = getCurrentFAMEPrice() * getBaseValue(chestType) * discountedPriceMultiplier / 100;
}
/**
*@notice Calculate the Ether Price we will pay to buy back FAME from a user (in Wei)
*@param amount The amount of FAME tokens on offer (the total price returned will be for this full amount)
*@return price The current ETH price (in wei) that will be paid for the full amount specified
*/
function getBuyBackPrice(uint amount) public view returns (uint price) {
//Determine current FAME price, and then we multiply down because our buyback percentage is 90% of current market price
//We also multiply by the amount to find the (perfect world) amount we will pay
price = (getCurrentFAMEPrice() * 9 / 10) * amount;
//Now we determine the max we will pay in a single transaction (capped at 25% of our current holdings in ETH, to prevent abuse)
//This means that if one user tries to dump a large amount to take advantage of a favorable price, they will only be paid a limited amount
//Forcing them to reduce their transaction (or risk being under-paid), and do a second transaction.
uint maxPayout = address(this).balance / 4;
//Next we cap the payout based on the maxPayout:
price = price > maxPayout ? maxPayout : price;
}
//////////////////////////////////////////////////////////////////////////////////////////
// Utility Functions
//////////////////////////////////////////////////////////////////////////////////////////
/**
*@dev Internal Helper Function to determine random roll when opening chests. Crude RNG, should be good enough, but is manipulable by miner theoretically
*@param seedOffset Integer seed offset used for additional randomization
*@return result Random roll from 0-10000 (random percentage to 2 decimal places)
*/
function roll(uint seedOffset) internal view returns (uint16 result) {
uint randomUint = uint(keccak256(abi.encodePacked(block.timestamp,blockhash(block.number),seedOffset)));
result = uint16(randomUint % 10000);
}
/**
*@notice ADMIN FUNCTION: Update the FAME Token ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setFAMEContractAddress(address newContract) public onlyOwner {
FAMEContract = IERC1155(newContract);
}
/**
*@notice ADMIN FUNCTION: Set the internal Token ID for FAME Tokens within the ERC1155 Contract
*@param id The new Token ID
*/
function setFAMETokenID(uint256 id) public onlyOwner {
FAMETokenID = id;
}
/**
*@notice ADMIN FUNCTION: Update the Warrior NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setWarriorContractAddress(address newContract) public onlyOwner {
WarriorContract = IWarrior(newContract);
}
/**
*@notice ADMIN FUNCTION: Update the Region NFT ERC1155 Contract Address
*@param newContract The address of the new contract
*/
function setRegionContractAddress(address newContract) public onlyOwner {
RegionContract = IRegion(newContract);
}
/**
*@dev Utility/Helper function for internal use whenever we need to transfer fame between 2 addresses
*@param sender The Sender Address (address from which the FAME will be deducted)
*@param recipient The Recipient Address (address to which the FAME will be credited)
*@param amount The amount of FAME tokens to transfer
*/
function transferFAME(
address sender,
address recipient,
uint256 amount
) internal {
FAMEContract.safeTransferFrom(
sender,
recipient,
FAMETokenID,
amount,
""
);
}
/**
*@notice Fetch the current FAME balance held within the Loot Chest Smart Contract
*@return balance The current FAME Token Balance
*/
function getContractFAMEBalance() public view returns (uint balance) {
return FAMEContract.balanceOf(address(this),FAMETokenID);
}
/**
*@dev Utility/Helper function for internal use, helps determine the worst case liability of a given chest type (amount of FAME that needs paying out)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return fame_liability The liability (amount of FAME this countract could potentially be expected to pay out in the worst case, or maximum reward scenario)
*/
function calculateChestLiability(ChestType chestType) internal pure returns (uint fame_liability) {
return getBaseValue(chestType) * 1500 / 1000;
}
/**
*@notice The current total liability of this contract (total FAME that would be required to be paid out if all current chests in circulation contain the max reward)
*@return fame_liability The current total liability (total FAME payout required in worse case from all chests in circulation)
*/
function calculateCurrentLiability() public view returns (uint fame_liability) {
for(uint8 ct=uint8(ChestType.BRONZE);ct<=uint8(ChestType.DIAMOND);ct++)
{
//Get current chest count of chest type
uint chestCount = totalSupply(ct);
//Then multiply by the liability of that chest type
fame_liability += chestCount * calculateChestLiability(ChestType(ct));
}
}
/**
*@notice Checks based on current FAME balance, and current total liability, the max number of specified chestType that can be created safely (factoring in new liability for requested chests)
*@param chestType The type of chest (1=Bronze,2=Silver,3=Gold,4=Diamond)
*@return maxQuantity Maximum quantity of chests of specified type, that can be created safely based on current conditions.
*/
function maxSafeCreatable(ChestType chestType) public view returns (uint maxQuantity) {
maxQuantity = 0;
uint currentLiability = calculateCurrentLiability();
uint currentBalance = getContractFAMEBalance();
if(currentLiability < currentBalance){
uint freeBalance = currentBalance - currentLiability;
maxQuantity = freeBalance / calculateChestLiability(chestType);
}
}
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
interface IWarrior {
function mintCustomWarrior(address owner, uint32 generation, bool special, uint randomSeed, uint16 colorHue, uint8 armorType, uint8 shieldType, uint8 weaponType) external returns(uint theNewWarrior);
function newWarrior() external returns(uint theNewWarrior);
function getWarriorIDByName(string calldata name) external view returns(uint);
function nameExists(string calldata _name) external view returns(bool);
function setName(uint warriorID, string calldata name) external;
function ownerOf(uint _id) external view returns(address);
function getWarriorCost() external pure returns(uint);
function getWarriorName(uint warriorID) external view returns(string memory);
function payWarrior(uint warriorID, uint amount, bool tax) external;
function transferFAMEFromWarriorToWarrior(uint senderID, uint recipientID, uint amount, bool tax) external;
function transferFAMEFromWarriorToAddress(uint warriorID, address recipient, uint amount) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
interface IRegion is IERC1155 {
function trustedCreateRegion() external returns (uint256 theNewRegion);
function newRegion() external returns (uint256 theNewRegion);
function getCurrentRegionCount() external view returns (uint256);
function getCurrentRegionPricingCounter() external view returns (uint256);
function ownerOf(uint256 _id) external view returns (address);
function getRegionCost(int256 offset) external view returns (uint256);
function getRegionName(uint256 regionID) external;
function payRegion(uint256 regionID, uint256 amount, bool tax) external;
}
// SPDX-License-Identifier: LGPL-3.0
pragma solidity ^0.8.9;
//import "openzeppelin-solidity/contracts/ownership/Ownable.sol";
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155Metadata.sol';
//import 'multi-token-standard/contracts/tokens/ERC1155/ERC1155MintBurn.sol';
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title BDERC1155Tradable
* BDERC1155Tradable - BattleDrome ERC1155 contract that whitelists an operator address, has create and mint functionality, and supports useful standards from OpenZeppelin,
like _exists(), name(), symbol(), and totalSupply()
*/
contract BDERC1155Tradable is ERC1155PresetMinterPauser, Ownable {
using Strings for string;
address proxyRegistryAddress;
uint256 private _currentTokenID = 0;
mapping(uint256 => address) public creators;
mapping(uint256 => uint256) public tokenSupply;
// Contract name
string public name;
// Contract symbol
string public symbol;
//Metadata URI (for backwards compat with old code, overrides URI functionality from openzeppelin)
string public baseMetadataURI;
/**
* @dev Require msg.sender to be the creator of the token id
*/
modifier creatorOnly(uint256 _id) {
require(
creators[_id] == msg.sender,
"ERC1155Tradable#creatorOnly: ONLY_CREATOR_ALLOWED"
);
_;
}
/**
* @dev Require msg.sender to own more than 0 of the token id
*/
modifier ownersOnly(uint256 _id) {
require(
balanceOf(msg.sender, _id) > 0,
"ERC1155Tradable#ownersOnly: ONLY_OWNERS_ALLOWED"
);
_;
}
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress,
string memory _metadataURI
) ERC1155PresetMinterPauser(_metadataURI) {
name = _name;
symbol = _symbol;
proxyRegistryAddress = _proxyRegistryAddress;
_setBaseMetadataURI(_metadataURI);
}
function uri(uint256 _id) public view override returns (string memory) {
require(_exists(_id), "ERC721Tradable#uri: NONEXISTENT_TOKEN");
return string(abi.encodePacked(baseMetadataURI, Strings.toString(_id)));
}
/**
* @dev Returns the total quantity for a token ID
* @param _id uint256 ID of the token to query
* @return amount of token in existence
*/
function totalSupply(uint256 _id) public view returns (uint256) {
return tokenSupply[_id];
}
function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal {
baseMetadataURI = _newBaseMetadataURI;
}
/**
* @dev Will update the base URL of token's URI
* @param _newBaseMetadataURI New base URL of token's URI
*/
function setBaseMetadataURI(string memory _newBaseMetadataURI)
public
onlyOwner
{
_setBaseMetadataURI(_newBaseMetadataURI);
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @param _data Data to pass if receiver is contract
* @return The newly created token ID
*/
function create(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri,
bytes calldata _data
) external onlyOwner returns (uint256) {
uint256 _id = _getNextTokenID();
_incrementTokenTypeId();
creators[_id] = msg.sender;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
_mint(_initialOwner, _id, _initialSupply, _data);
tokenSupply[_id] = _initialSupply;
return _id;
}
/**
* @dev Mints some amount of tokens to an address
* @param _to Address of the future owner of the token
* @param _id Token ID to mint
* @param _quantity Amount of tokens to mint
* @param _data Data to pass if receiver is contract
*/
function mint(
address _to,
uint256 _id,
uint256 _quantity,
bytes memory _data
) public override creatorOnly(_id) {
_mint(_to, _id, _quantity, _data);
tokenSupply[_id] = tokenSupply[_id] + _quantity;
}
/**
* @dev Mint tokens for each id in _ids
* @param _to The address to mint tokens to
* @param _ids Array of ids to mint
* @param _quantities Array of amounts of tokens to mint per id
* @param _data Data to pass if receiver is contract
*/
function batchMint(
address _to,
uint256[] memory _ids,
uint256[] memory _quantities,
bytes memory _data
) public {
for (uint256 i = 0; i < _ids.length; i++) {
uint256 _id = _ids[i];
require(
creators[_id] == msg.sender,
"ERC1155Tradable#batchMint: ONLY_CREATOR_ALLOWED"
);
uint256 quantity = _quantities[i];
tokenSupply[_id] = tokenSupply[_id] + quantity;
}
_mintBatch(_to, _ids, _quantities, _data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal override {
tokenSupply[id] = tokenSupply[id] - amount;
super._burn(from,id,amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal override {
for (uint256 i = 0; i < ids.length; i++) {
tokenSupply[ids[i]] = tokenSupply[ids[i]] - amounts[i];
}
super._burnBatch(from,ids,amounts);
}
/**
* @dev Change the creator address for given tokens
* @param _to Address of the new creator
* @param _ids Array of Token IDs to change creator
*/
function setCreator(address _to, uint256[] memory _ids) public {
require(
_to != address(0),
"ERC1155Tradable#setCreator: INVALID_ADDRESS."
);
require(
_ids.length>0,
"ERC1155Tradeable#setCreator: EMPTY_ARRAY"
);
for (uint256 i = 0; i < _ids.length; i++) {
uint256 id = _ids[i];
_setCreator(_to, id);
}
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-free listings.
*/
function isApprovedForAll(address _owner, address _operator)
public
view
override
returns (bool isOperator)
{
//TODO: FAILING HERE ON REGION SALE
//Failing from inside the transferFAME function (inside safeTransferFrom in the FAME contract itself)
//When being called by the Region contract as the operator
//With the user being the owner.
//WHY!?!?!?
//Ideas:
// Look into the proxy contract, this code is throwing a revert and the debugger seems non-specific
// Pour over this again with debugger a couple times
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(_owner)) == _operator) {
return true;
}
return ERC1155.isApprovedForAll(_owner, _operator);
}
/**
* @dev Change the creator address for given token
* @param _to Address of the new creator
* @param _id Token IDs to change creator of
*/
function _setCreator(address _to, uint256 _id) internal creatorOnly(_id) {
creators[_id] = _to;
}
/**
* @dev Returns whether the specified token exists by checking to see if it has a creator
* @param _id uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 _id) internal view returns (bool) {
return creators[_id] != address(0);
}
/**
* @dev calculates the next token ID based on value of _currentTokenID
* @return uint256 for the next token ID
*/
function _getNextTokenID() internal view returns (uint256) {
return _currentTokenID + 1;
}
/**
* @dev increments the value of _currentTokenID
*/
function _incrementTokenTypeId() internal {
_currentTokenID++;
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// 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 "./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 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;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../extensions/ERC1155Burnable.sol";
import "../extensions/ERC1155Pausable.sol";
import "../../../access/AccessControlEnumerable.sol";
import "../../../utils/Context.sol";
/**
* @dev {ERC1155} token, including:
*
* - ability for holders to burn (destroy) their tokens
* - a minter role that allows for token minting (creation)
* - a pauser role that allows to stop all token transfers
*
* This contract uses {AccessControl} to lock permissioned functions using the
* different roles - head to its documentation for details.
*
* The account that deploys the contract will be granted the minter and pauser
* roles, as well as the default admin role, which will let it grant both minter
* and pauser roles to other accounts.
*/
contract ERC1155PresetMinterPauser is Context, AccessControlEnumerable, ERC1155Burnable, ERC1155Pausable {
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `MINTER_ROLE`, and `PAUSER_ROLE` to the account that
* deploys the contract.
*/
constructor(string memory uri) ERC1155(uri) {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(MINTER_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, _msgSender());
}
/**
* @dev Creates `amount` new tokens for `to`, of token type `id`.
*
* See {ERC1155-_mint}.
*
* Requirements:
*
* - the caller must have the `MINTER_ROLE`.
*/
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mint(to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] variant of {mint}.
*/
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual {
require(hasRole(MINTER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have minter role to mint");
_mintBatch(to, ids, amounts, data);
}
/**
* @dev Pauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC1155Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public virtual {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC1155PresetMinterPauser: must have pauser role to unpause");
_unpause();
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(AccessControlEnumerable, ERC1155)
returns (bool)
{
return super.supportsInterface(interfaceId);
}
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override(ERC1155, ERC1155Pausable) {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
import "../../../security/Pausable.sol";
/**
* @dev ERC1155 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*
* _Available since v3.1._
*/
abstract contract ERC1155Pausable is ERC1155, Pausable {
/**
* @dev See {ERC1155-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
require(!paused(), "ERC1155Pausable: token transfer while paused");
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC1155.sol";
/**
* @dev Extension of {ERC1155} that allows token holders to destroy both their
* own tokens and those that they have been approved to use.
*
* _Available since v3.1._
*/
abstract contract ERC1155Burnable is ERC1155 {
function burn(
address account,
uint256 id,
uint256 value
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burn(account, id, value);
}
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_burnBatch(account, ids, values);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC1155.sol";
import "./IERC1155Receiver.sol";
import "./extensions/IERC1155MetadataURI.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using Address for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
constructor(string memory uri_) {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC1155).interfaceId ||
interfaceId == type(IERC1155MetadataURI).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address account,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] += amount;
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address account,
uint256 id,
uint256 amount
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address account,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 accountBalance = _balances[id][account];
require(accountBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][account] = accountBalance - amount;
}
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155Receiver.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
/**
* @dev External interface of AccessControlEnumerable declared to support ERC165 detection.
*/
interface IAccessControlEnumerable is IAccessControl {
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControlEnumerable.sol";
import "./AccessControl.sol";
import "../utils/structs/EnumerableSet.sol";
/**
* @dev Extension of {AccessControl} that allows enumerating the members of each role.
*/
abstract contract AccessControlEnumerable is IAccessControlEnumerable, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
mapping(bytes32 => EnumerableSet.AddressSet) private _roleMembers;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlEnumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view override returns (address) {
return _roleMembers[role].at(index);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view override returns (uint256) {
return _roleMembers[role].length();
}
/**
* @dev Overload {grantRole} to track enumerable memberships
*/
function grantRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.grantRole(role, account);
_roleMembers[role].add(account);
}
/**
* @dev Overload {revokeRole} to track enumerable memberships
*/
function revokeRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.revokeRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {renounceRole} to track enumerable memberships
*/
function renounceRole(bytes32 role, address account) public virtual override(AccessControl, IAccessControl) {
super.renounceRole(role, account);
_roleMembers[role].remove(account);
}
/**
* @dev Overload {_setupRole} to track enumerable memberships
*/
function _setupRole(bytes32 role, address account) internal virtual override {
super._setupRole(role, account);
_roleMembers[role].add(account);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
function _grantRole(bytes32 role, address account) private {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
} | Utility/Helper function for internal use whenever we need to transfer fame between 2 addresses sender The Sender Address (address from which the FAME will be deducted) recipient The Recipient Address (address to which the FAME will be credited) amount The amount of FAME tokens to transfer/ | function transferFAME(
address sender,
address recipient,
uint256 amount
) internal {
FAMEContract.safeTransferFrom(
sender,
recipient,
FAMETokenID,
amount,
""
);
}
| 13,683,530 |
./full_match/432204/0x010224949cCa211Fb5dDfEDD28Dc8Bf9D2990368/sources/contracts/PortfolioSub.sol | This function is used to withdraw only native ALOT from the portfolio into the subnet wallet. Also referred as AddGas This function decreases ALOT balance of the user and calls the PortfolioMinter to mint the native ALOT _to Address of the withdrawer _quantity Amount of the native ALOT to withdraw/ | function withdrawNative(address payable _to, uint256 _quantity) external override whenNotPaused nonReentrant {
require(_to == msg.sender, "P-OOWN-01");
withdrawNativePrivate(_to, _quantity);
}
| 16,380,941 |
pragma solidity >=0.6.0;
pragma experimental ABIEncoderV2;
import './PriceAPI.sol';
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/math/SafeMath.sol";
import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/master/contracts/utils/ReentrancyGuard.sol";
/// @title Interface for Market Contract
/// @author Kuldeep K Srivastava
interface IMarket {
enum Action {lt, gt, eq}
enum State {active, inactive}
struct MarketDetails {
State state;
string token1;
string token2;
uint amount;
Action action;
uint startTime;
uint interval;
uint endTime;
uint totalVotes;
uint yesVotes;
uint noVotes;
uint yesPrice;
uint noPrice;
bool result;
}
struct Prediction {
uint share;
bool verdict;
}
event predicted(address indexed user, bool verdict, uint share);
event resultDeclared(address indexed market, address user);
event withdrawAmount(address indexed user, uint amount);
// @notice Get all the current details of the market
// @return Market struct with all the details
function getMarket() external returns (MarketDetails memory);
// @notice Allows an end-user to make prediction for the market
// @param _verdict Yes/No selected by end-user
// @param _share Amount of share that user is purchasing for his prediction
// @return Returns true if successful
function predict(bool, uint) external payable returns (bool);
// @notice Resolves the market after the market's prediction function is closed
// @return Returns true if successful
function result() external returns (bool);
// @notice Allows user to withdraw their winning amount after market is resolved
// @return Returns true if successful
function withdraw() external returns (bool);
}
/// @title Cryptocurrency Price Prediction Market
/// @dev Inherits IMarket Interface, APIConsumer Contract
/// @author Kuldeep K. Srivastava
contract Market is IMarket,ReentrancyGuard,APIConsumer {
using SafeMath for uint;
// @notice Address of the user who created this market
// @return Returns market owner's address
address public marketOwner;
MarketDetails private M;
mapping(address => Prediction) private predictions;
mapping(address => bool) private predictors;
constructor (
address owner,
string memory token1,
string memory token2,
Action action,
uint amount,
uint interval
) public {
marketOwner = owner;
M.state = State.active;
M.token1 = token1;
M.token2 = token2;
M.amount = amount;
M.action = action;
M.startTime = block.timestamp;
M.interval = interval;
M.endTime = M.startTime + interval;
M.totalVotes = 0;
M.yesVotes = 0;
M.noVotes = 0;
M.yesPrice = 50 wei;
M.noPrice= 50 wei;
}
bool private stopped = false;
modifier stopInEmergency { require(!stopped); _; }
modifier onlyInEmergency { require(stopped); _; }
modifier marketActive() {
require(M.endTime >= block.timestamp,"Market is not accepting prediction anymore");
_;
}
modifier marketInProgress() {
require(M.endTime < block.timestamp,"Market is still active");
require(M.state == State.active,"Market is already resolved");
require(marketResolved == false);
_;
}
modifier marketInactive() {
require(M.endTime < block.timestamp,"Market is still active");
require(M.state == State.inactive,"Market is not resolved yet");
require(marketResolved == true);
_;
}
// @notice Get all the current details of the market
// @return Market struct with all the details
function getMarket() public override returns (MarketDetails memory) {
return M;
}
// @notice Allows an end-user to make prediction for the market
// @dev It uses circuit breaker pattern.
// @param _verdict Yes/No selected by end-user
// @param _share Amount of share that user is purchasing for his prediction
// @return Returns true if successful
function predict(bool _verdict, uint _share) public override payable marketActive stopInEmergency returns (bool) {
// market not close
// not already predicted
// amount is correct
// create a new predict
// add to predictions list
// modify yes or no votes and profits
// return true
// use circuit breaker pattern
require(predictors[msg.sender] == false, "You have already participated in this market");
if(_verdict) {
require((M.yesPrice.mul(_share)) <= msg.value, "Not enough amount");
} else {
require((M.noPrice.mul(_share)) <= msg.value, "Not enough amount");
}
M.totalVotes = M.totalVotes.add(1);
if(_verdict) {
M.yesVotes = M.yesVotes.add(1);
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
} else {
M.noVotes = M.noVotes.add(1);
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
}
Prediction memory p = Prediction({
share:_share,
verdict: _verdict
});
predictions[msg.sender] = p;
predictors[msg.sender] = true;
emit predicted(msg.sender, _verdict, _share);
return true;
}
// @notice Resolves the market after the market's prediction function is closed
// @dev It uses chainlink oracle for doing the same.
// @return Returns true if successful
function result() public override marketInProgress returns(bool) {
// require only owner or one of the depositor
// call API
// get API response
// change result value
// change State to inactive
require(msg.sender == marketOwner || predictors[msg.sender], "Not authorised");
// resultAmount = 400;
// marketResolved = true;
requestVolumeData(M.token1, M.token2);
M.state = State.inactive;
stopped = true;
emit resultDeclared(address(this), msg.sender);
return true;
}
// @notice Allows user to withdraw their winning amount after market is resolved
// @dev It uses withdrawl pattern
// @return Returns true if successful
function withdraw() public override marketInactive onlyInEmergency nonReentrant returns(bool) {
// withdrawl pattern
// check user has deposited
// calculate amount to pay
// check if enough balance
// change share to 0
// tranfer eth to the user
require(predictors[msg.sender], "Not authorised");
require(predictions[msg.sender].share != 0, "Already withdrawn");
bool finalResult = false;
if(M.action == Action.lt) {
finalResult = M.amount.mul(10**18) < resultAmount;
} else if(M.action == Action.gt) {
finalResult = M.amount.mul(10**18) > resultAmount;
} else {
finalResult = M.amount.mul(10**18) == resultAmount;
}
Prediction memory p = predictions[msg.sender];
require(finalResult == p.verdict, "Sorry you lost");
uint winningAmount;
if(finalResult){
winningAmount = (address(this).balance).div(M.yesVotes);
} else {
winningAmount = (address(this).balance).div(M.noVotes);
}
require(address(this).balance >= (winningAmount.mul(p.share)), "Not enough balance");
msg.sender.transfer(winningAmount.mul(p.share));
emit withdrawAmount(msg.sender, winningAmount.mul(p.share));
predictions[msg.sender].share = 0;
return true;
}
// no price becomes 0 after first votes
// noprice + yesPrice sometimes < 100 eg. 66 + 33
// upgradablility
// share is not regarded in calculating final winning prize
// calculate winning prize only once when result comes from API
} | Allows an end-user to make prediction for the market It uses circuit breaker pattern. _verdict Yes/No selected by end-user _share Amount of share that user is purchasing for his prediction return Returns true if successful market not close not already predicted amount is correct create a new predict add to predictions list modify yes or no votes and profits return true use circuit breaker pattern | function predict(bool _verdict, uint _share) public override payable marketActive stopInEmergency returns (bool) {
require(predictors[msg.sender] == false, "You have already participated in this market");
if(_verdict) {
require((M.yesPrice.mul(_share)) <= msg.value, "Not enough amount");
require((M.noPrice.mul(_share)) <= msg.value, "Not enough amount");
}
M.totalVotes = M.totalVotes.add(1);
if(_verdict) {
M.yesVotes = M.yesVotes.add(1);
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
M.noVotes = M.noVotes.add(1);
M.noPrice = ((M.noVotes.mul(10**2)).div(M.totalVotes));
M.yesPrice = ((M.yesVotes.mul(10**2)).div(M.totalVotes));
}
Prediction memory p = Prediction({
share:_share,
verdict: _verdict
});
predictions[msg.sender] = p;
predictors[msg.sender] = true;
emit predicted(msg.sender, _verdict, _share);
return true;
}
| 2,473,745 |
/**
* @title ERC20SnapshotMock
* @author Team 3301 <[email protected]>
* @dev Mock contract for snapshot functionality when overloading ERC20 functions.
* This contract is excluded from the audit.
*/
pragma solidity 0.5.12;
import "../../../helpers/ERC20/ERC20Snapshot.sol";
contract ERC20SnapshotMock is ERC20Snapshot {
/**
* @dev Access internal mint function.
* @param account Account to mint funds to.
* @param value amount to mint.
*/
function mint(address account, uint256 value) public {
super._mint(account, value);
}
/**
* @dev Access internal burn function.
* @param amount to burn.
*/
function burn(uint256 amount) public {
super._burn(msg.sender, amount);
}
/**
* @dev Access internal burnFor function.
* @param account Account to burn funds from.
* @param amount to burn.
*/
function burnFor(address account, uint256 amount) public {
super._burnFor(account, amount);
}
/**
* @dev Access internal burnFrom function.
* @param account Account to burn funds from.
* @param amount to burn.
*/
function burnFrom(address account, uint256 amount) public {
super._burnFrom(account, amount);
}
/**
* @dev Access internal confiscate function.
* @param confiscatee Account to confiscate funds from.
* @param confiscatee Account to transfer funds to.
* @param amount to confiscate.
*/
function confiscate(
address confiscatee,
address receiver,
uint256 amount
) public {
super._confiscate(confiscatee, receiver, amount);
}
}
| Access internal confiscate function. confiscatee Account to confiscate funds from. confiscatee Account to transfer funds to. amount to confiscate./ | function confiscate(
address confiscatee,
address receiver,
uint256 amount
) public {
super._confiscate(confiscatee, receiver, amount);
}
| 12,915,913 |
./partial_match/4/0x9E0816EaB9602c5306C5cAAd24c700E020d4b3Fd/sources/ETHFarm.sol | Safe testa transfer function, just in case if rounding error causes pool to not have enough Testa. | function safeTestaTransfer(address _to, uint256 _amount) internal {
uint256 testaBal = IERC20(testa).balanceOf(address(this));
if (_amount > testaBal) {
testa.call(abi.encodeWithSignature("transfer(address,uint256)", _to, testaBal));
testa.call(abi.encodeWithSignature("transfer(address,uint256)", _to, _amount));
}
}
| 8,647,677 |
./partial_match/1/0x9972244880a81C19943393e752B3056d6D26b4dc/sources/TsukaGatekeeper.sol | exclude from paying fees or having max transaction amount | constructor() ERC20("Tsuka Gatekeeper", " $Tsukagate") {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
excludeFromMaxTransaction(address(_uniswapV2Router), true);
uniswapV2Router = _uniswapV2Router;
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), USDC);
excludeFromMaxTransaction(address(uniswapV2Pair), true);
uint256 _buyDevFee = 8;
uint256 _buyLiquidityFee = 0;
uint256 _sellDevFee = 8;
uint256 _sellLiquidityFee = 0;
uint256 totalSupply = 100_000_000_000 * 1e18;
buyDevFee = _buyDevFee;
buyLiquidityFee = _buyLiquidityFee;
buyTotalFees = buyDevFee + buyLiquidityFee;
sellDevFee = _sellDevFee;
sellLiquidityFee = _sellLiquidityFee;
sellTotalFees = sellDevFee + sellLiquidityFee;
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);
| 3,680,991 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import {BaseTest, console} from "./base/BaseTest.sol";
import {PayloadAaveStarknetPhaseI, ICollector, IOwnable, LibPropConstants} from "../PayloadAaveStarknetPhaseI.sol";
interface IAaveGov {
struct ProposalWithoutVotes {
uint256 id;
address creator;
address executor;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
uint256 startBlock;
uint256 endBlock;
uint256 executionTime;
uint256 forVotes;
uint256 againstVotes;
bool executed;
bool canceled;
address strategy;
bytes32 ipfsHash;
}
enum ProposalState {
Pending,
Canceled,
Active,
Failed,
Succeeded,
Queued,
Expired,
Executed
}
struct SPropCreateParams {
address executor;
address[] targets;
uint256[] values;
string[] signatures;
bytes[] calldatas;
bool[] withDelegatecalls;
bytes32 ipfsHash;
}
function create(
address executor,
address[] memory targets,
uint256[] memory values,
string[] memory signatures,
bytes[] memory calldatas,
bool[] memory withDelegatecalls,
bytes32 ipfsHash
) external returns (uint256);
function queue(uint256 proposalId) external;
function execute(uint256 proposalId) external payable;
function submitVote(uint256 proposalId, bool support) external;
function getProposalById(uint256 proposalId)
external
view
returns (ProposalWithoutVotes memory);
function getProposalState(uint256 proposalId)
external
view
returns (ProposalState);
}
contract ValidateAIPStarknetPhaseI is BaseTest {
address internal constant AAVE_TREASURY =
0x25F2226B597E8F9514B3F68F00f494cF4f286491;
IAaveGov internal constant GOV =
IAaveGov(0xEC568fffba86c094cf06b22134B23074DFE2252c);
address SHORT_EXECUTOR = 0xEE56e2B3D491590B5b31738cC34d5232F378a8D5;
function setUp() public {}
/// @dev First deploys a fresh payload, then tests everything using it
function testProposalPrePayload() public {
// Block of proposal creation on Ethereum mainnet
if (block.number < 14255778) {
IAaveGov.SPropCreateParams memory proposalParams = _buildProposal(
address(new PayloadAaveStarknetPhaseI())
);
uint256 proposalId = _createProposal(proposalParams);
uint256 recipientUsdcBefore = LibPropConstants.USDC.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
uint256 recipientWethBefore = LibPropConstants.WETH.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
_passVoteAndQueue(proposalId, AAVE_TREASURY);
_executeProposal(proposalId, AAVE_TREASURY);
_validatePhaseIFunds(recipientUsdcBefore, recipientWethBefore);
address newControllerOfCollector = _validateNewCollector();
_validateNewControllerOfCollector(
ICollector(newControllerOfCollector)
);
}
}
/// @dev Uses an already deployed payload on the target network
function testProposalPostPayload() public {
if (block.number < 14255778) {
// Block of proposal creation on Ethereum mainnet
IAaveGov.SPropCreateParams memory proposalParams = _buildProposal(
0x4E76e1d71806aaE6Ccaac0FC67C3aa74cb245277
);
uint256 proposalId = _createProposal(proposalParams);
uint256 recipientUsdcBefore = LibPropConstants.USDC.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
uint256 recipientWethBefore = LibPropConstants.WETH.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
_passVoteAndQueue(proposalId, AAVE_TREASURY);
_executeProposal(proposalId, AAVE_TREASURY);
_validatePhaseIFunds(recipientUsdcBefore, recipientWethBefore);
address newControllerOfCollector = _validateNewCollector();
_validateNewControllerOfCollector(
ICollector(newControllerOfCollector)
);
}
}
function testProposalVoting() public {
// Voting range on Ethereum mainnet
if (block.number > 14255778 && block.number < 14275325) {
uint256 proposalId = 61;
uint256 recipientUsdcBefore = LibPropConstants.USDC.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
uint256 recipientWethBefore = LibPropConstants.WETH.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
_passVoteAndQueue(proposalId, AAVE_TREASURY);
_executeProposal(proposalId, AAVE_TREASURY);
_validatePhaseIFunds(recipientUsdcBefore, recipientWethBefore);
address newControllerOfCollector = _validateNewCollector();
_validateNewControllerOfCollector(
ICollector(newControllerOfCollector)
);
}
}
function testProposalQueued() public {
if (block.number > 14275325) { // TODO add execution block once available
// Block when the proposal has been queued on Ethereum mainnet
uint256 proposalId = 61;
uint256 recipientUsdcBefore = LibPropConstants.USDC.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
uint256 recipientWethBefore = LibPropConstants.WETH.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
_executeProposal(proposalId, AAVE_TREASURY);
_validatePhaseIFunds(recipientUsdcBefore, recipientWethBefore);
address newControllerOfCollector = _validateNewCollector();
_validateNewControllerOfCollector(
ICollector(newControllerOfCollector)
);
}
}
function _buildProposal(address payload)
internal
view
returns (IAaveGov.SPropCreateParams memory)
{
address[] memory targets = new address[](1);
targets[0] = payload;
uint256[] memory values = new uint256[](1);
values[0] = 0;
string[] memory signatures = new string[](1);
signatures[0] = "execute()";
bytes[] memory calldatas = new bytes[](1);
calldatas[0] = "";
bool[] memory withDelegatecalls = new bool[](1);
withDelegatecalls[0] = true;
return
IAaveGov.SPropCreateParams({
executor: SHORT_EXECUTOR,
targets: targets,
values: values,
signatures: signatures,
calldatas: calldatas,
withDelegatecalls: withDelegatecalls,
ipfsHash: bytes32(0)
});
}
function _createProposal(IAaveGov.SPropCreateParams memory params)
internal
returns (uint256)
{
vm.deal(AAVE_TREASURY, 1 ether);
vm.startPrank(AAVE_TREASURY);
uint256 proposalId = GOV.create(
params.executor,
params.targets,
params.values,
params.signatures,
params.calldatas,
params.withDelegatecalls,
params.ipfsHash
);
vm.stopPrank();
return proposalId;
}
function _passVoteAndQueue(uint256 proposalId, address whaleVoter)
internal
{
vm.deal(whaleVoter, 1 ether);
vm.startPrank(whaleVoter);
vm.roll(block.number + 1);
GOV.submitVote(proposalId, true);
uint256 endBlock = GOV.getProposalById(proposalId).endBlock;
vm.roll(endBlock + 1);
GOV.queue(proposalId);
vm.stopPrank();
}
function _executeProposal(uint256 proposalId, address executorOfProposal)
internal
{
vm.deal(executorOfProposal, 1 ether);
vm.startPrank(executorOfProposal);
uint256 executionTime = GOV.getProposalById(proposalId).executionTime;
vm.warp(executionTime + 1);
GOV.execute(proposalId);
vm.stopPrank();
}
function _validatePhaseIFunds(
uint256 recipientUsdcBefore,
uint256 recipientWethBefore
) internal view {
require(
LibPropConstants.USDC.balanceOf(LibPropConstants.FUNDS_RECIPIENT) ==
LibPropConstants.USDC_AMOUNT + recipientUsdcBefore,
"INVALID_RECIPIENT_USDC_BALANCE"
);
require(
LibPropConstants.WETH.balanceOf(LibPropConstants.FUNDS_RECIPIENT) ==
LibPropConstants.ETH_AMOUNT + recipientWethBefore,
"INVALID_RECIPIENT_WETH_BALANCE"
);
}
function _validateNewControllerOfCollector(ICollector controllerOfCollector)
internal
{
require(
IOwnable(address(controllerOfCollector)).owner() == SHORT_EXECUTOR,
"NEW_CONTROLLER_TESTS: INVALID_OWNER"
);
// Negative tests of ownership
vm.startPrank(AAVE_TREASURY);
vm.expectRevert(bytes("Ownable: caller is not the owner"));
controllerOfCollector.transfer(LibPropConstants.AUSDC, address(0), 666);
vm.expectRevert(bytes("Ownable: caller is not the owner"));
controllerOfCollector.approve(LibPropConstants.AWETH, address(0), 999);
vm.stopPrank();
// Positive ownership tests
vm.startPrank(SHORT_EXECUTOR);
uint256 balanceMockRecipientBefore = LibPropConstants.AUSDC.balanceOf(
address(1)
);
controllerOfCollector.transfer(LibPropConstants.AUSDC, address(1), 666);
require(
_almostEqual(
LibPropConstants.AUSDC.balanceOf(address(1)),
balanceMockRecipientBefore + 666
),
"NEW_CONTROLLER_TESTS : INVALID_POST_TRANSFER_BALANCE"
);
controllerOfCollector.approve(LibPropConstants.AWETH, address(1), 777);
require(
(LibPropConstants.AWETH.allowance(
address(LibPropConstants.COLLECTOR_V2_PROXY),
address(1)
) == 777),
"NEW_CONTROLLER_TESTS : INVALID_POST_TRANSFER_ALLOWANCE"
);
vm.stopPrank();
}
function _validateNewCollector() internal returns (address) {
vm.startPrank(SHORT_EXECUTOR);
// Only the admin can call the admin() view function, so acts as assert of correctness
LibPropConstants.COLLECTOR_V2_PROXY.admin();
require(
LibPropConstants.COLLECTOR_V2_PROXY.implementation() ==
address(LibPropConstants.NEW_COLLECTOR_IMPL),
"NEW_COLLECTOR_TESTS : INVALID_NEW_COLLECTOR_IMPL"
);
vm.stopPrank();
require(
LibPropConstants.NEW_COLLECTOR_IMPL.REVISION() == 2,
"NEW_COLLECTOR_TESTS : INVALID_COLLECTOR_IMPL_REVISION"
);
address controllerOfCollector = ICollector(
address(LibPropConstants.COLLECTOR_V2_PROXY)
).getFundsAdmin();
ICollector collectorProxy = ICollector(
address(LibPropConstants.COLLECTOR_V2_PROXY)
);
// Negative tests of ownership
vm.startPrank(AAVE_TREASURY);
vm.expectRevert(bytes("ONLY_BY_FUNDS_ADMIN"));
collectorProxy.transfer(LibPropConstants.AUSDC, address(0), 666);
vm.expectRevert(bytes("ONLY_BY_FUNDS_ADMIN"));
collectorProxy.approve(LibPropConstants.AWETH, address(0), 999);
vm.stopPrank();
// Positive ownership tests
vm.startPrank(controllerOfCollector);
uint256 balanceMockRecipientBefore = LibPropConstants.AUSDC.balanceOf(
address(1)
);
collectorProxy.transfer(LibPropConstants.AUSDC, address(1), 666);
require(
_almostEqual(
LibPropConstants.AUSDC.balanceOf(address(1)),
balanceMockRecipientBefore + 666
),
"NEW_COLLECTOR_TESTS : INVALID_POST_TRANSFER_BALANCE"
);
uint256 allowanceMockRecipientBefore = LibPropConstants.AWETH.allowance(
address(collectorProxy),
address(1)
);
collectorProxy.approve(LibPropConstants.AWETH, address(1), 666);
require(
LibPropConstants.AWETH.allowance(
address(collectorProxy),
address(1)
) == allowanceMockRecipientBefore + 666,
"NEW_COLLECTOR_TESTS : INVALID_POST_TRANSFER_ALLOWANCE"
);
vm.stopPrank();
// No further initialisation can be done
vm.startPrank(AAVE_TREASURY);
vm.expectRevert(
bytes("Contract instance has already been initialized")
);
collectorProxy.initialize(address(1));
vm.stopPrank();
return controllerOfCollector;
}
/// @dev To contemplate +1/-1 precision issues when rounding, mainly on aTokens
function _almostEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (b == 0) {
return (a == b) || (a == (b + 1));
} else {
return (a == b) || (a == (b + 1)) || (a == (b - 1));
}
}
}
| Voting range on Ethereum mainnet | function testProposalVoting() public {
if (block.number > 14255778 && block.number < 14275325) {
uint256 proposalId = 61;
uint256 recipientUsdcBefore = LibPropConstants.USDC.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
uint256 recipientWethBefore = LibPropConstants.WETH.balanceOf(
LibPropConstants.FUNDS_RECIPIENT
);
_passVoteAndQueue(proposalId, AAVE_TREASURY);
_executeProposal(proposalId, AAVE_TREASURY);
_validatePhaseIFunds(recipientUsdcBefore, recipientWethBefore);
address newControllerOfCollector = _validateNewCollector();
_validateNewControllerOfCollector(
ICollector(newControllerOfCollector)
);
}
}
| 6,395,692 |
/*
* @source: https://consensys.github.io/smart-contract-best-practices/known_attacks/
* @author: consensys
* @vulnerable_at_lines: 17
*/
pragma solidity ^0.4.0;
contract Reentrancy_insecure {
// INSECURE
mapping (address => uint) private userBalances;
function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
// <yes> <report> REENTRANCY
(bool success, ) = msg.sender.call.value(amountToWithdraw)(""); // At this point, the caller's code is executed, and can call withdrawBalance again
require(success);
userBalances[msg.sender] = 0;
}
}
| <yes> <report> REENTRANCY | function withdrawBalance() public {
uint amountToWithdraw = userBalances[msg.sender];
require(success);
userBalances[msg.sender] = 0;
}
| 1,803,333 |
// 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;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.7;
import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
contract Object is ERC721Enumerable, ReentrancyGuard, Ownable {
string[] private power = [
"10",
"20",
"30",
"40",
"50",
"60",
"70",
"80",
"90",
"100"
];
string[] private luck = [
"10",
"20",
"30",
"40",
"50",
"60",
"70",
"80",
"90",
"100"
];
// Cooldown (weeks)
string[] private cooldown = [
"0",
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10",
"11",
"12"
];
string[] private affinity = [
"Red",
"Yellow",
"Green",
"Blue",
"Violet"
];
string[] private sigil = [
"Wolf",
"Lion",
"Eagle",
"Stag",
"Bear"
];
string[] private levels = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
];
// Activation Time (days)
string[] private activation = [
"1",
"2",
"3",
"4",
"5"
];
// Volume
string[] private volume = [
"10",
"20",
"30",
"40",
"50",
"60",
"70",
"80",
"90",
"100"
];
function random(string memory input) internal pure returns (uint256) {
return uint256(keccak256(abi.encodePacked(input)));
}
function getPower(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "POWER", power);
}
function getLuck(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "LUCK", luck);
}
function getCooldown(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "COOLDOWN", cooldown);
}
function getAffinity(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "AFFINITY", affinity);
}
function getSigil(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "SIGIL", sigil);
}
function getLevels(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "LEVELS", levels);
}
function getActivation(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "ACTIVATION", activation);
}
function getVolume(uint256 tokenId) public view returns (string memory) {
return pluck(tokenId, "VOLUME", volume);
}
function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal view returns (string memory) {
uint256 rand = random(string(abi.encodePacked(keyPrefix, toString(tokenId), msg.sender, tx.gasprice)));
string memory output = sourceArray[rand % sourceArray.length];
return output;
}
function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[17] memory parts;
parts[0] = '<svg xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="xMinYMin meet" viewBox="0 0 350 350"><style>.base { fill: white; font-family: "Helvetica"; font-size: 16px; }</style><defs><radialGradient id="RadialGradient2" cx="-0.1" cy="-0.1" r="0.85"><stop offset="50%" stop-color="purple"/><stop offset="100%" stop-color="black"/></radialGradient></defs>><rect width="100%" height="100%" fill="url(#RadialGradient2)"/><text x="20" y="30" class="base">Power - ';
parts[1] = getPower(tokenId);
parts[2] = '</text><text x="20" y="50" class="base">Luck - ';
parts[3] = getLuck(tokenId);
parts[4] = '</text><text x="20" y="70" class="base">Cooldown - ';
parts[5] = getCooldown(tokenId);
parts[6] = ' week(s)</text><text x="20" y="90" class="base">Affinity - ';
parts[7] = getAffinity(tokenId);
parts[8] = '</text><text x="20" y="110" class="base">Sigil - ';
parts[9] = getSigil(tokenId);
parts[10] = '</text><text x="20" y="130" class="base">Levels - ';
parts[11] = getLevels(tokenId);
parts[12] = '</text><text x="20" y="150" class="base">Activation - ';
parts[13] = getActivation(tokenId);
parts[14] = ' day(s)</text><text x="20" y="170" class="base">Volume - ';
parts[15] = getVolume(tokenId);
parts[16] = '</text><text x="132" y="275" class="base" style="font-size: 10px; letter-spacing: 1.5; fill: purple">The Alchemist\'s</text><text x="117" y="300" class="base" style="font-size: 20px; letter-spacing: 5;">GLIMMER</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]));
output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16]));
// attributes: [{"trait_type": "Power", "value": "', getWeapon(tokenId), '"}, {"trait_type": "Luck", "value": "', getChest(tokenId), '"}, {"trait_type": "Cooldown", "value": "', getHead(tokenId), '"}, {"trait_type": "Affinity", "value": "', getWaist(tokenId), '"}, {"trait_type": "Sign", "value": "', getFoot(tokenId), '"}, {"trait_type": "Levels", "value": "', getHand(tokenId), '"}, {"trait_type": "Activation", "value": "', getNeck(tokenId), '"}, {"trait_type": "Charge", "value": "', getRing(tokenId), '"}]
string memory json = Base64.encode(bytes(string(abi.encodePacked('{"name": "Object #', toString(tokenId), '", "description": "Why hello there, Moon Boy. It seems that you have found my Glimmer.", "external_url": "https://www.ritualmill.com/", "image": "data:image/svg+xml;base64,', Base64.encode(bytes(output)), '"}'))));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
function claim(uint256 tokenId) public nonReentrant {
require(tokenId > 0 && tokenId < 5778, "Token ID invalid");
_safeMint(_msgSender(), tokenId);
}
function ownerClaim(uint256 tokenId) public nonReentrant onlyOwner {
require(tokenId > 5777 && tokenId < 6001, "Token ID invalid");
_safeMint(owner(), tokenId);
}
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT license
// 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);
}
constructor() ERC721("Digital Object", "OBJECT") Ownable() {}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
| attributes: [{"trait_type": "Power", "value": "', getWeapon(tokenId), '"}, {"trait_type": "Luck", "value": "', getChest(tokenId), '"}, {"trait_type": "Cooldown", "value": "', getHead(tokenId), '"}, {"trait_type": "Affinity", "value": "', getWaist(tokenId), '"}, {"trait_type": "Sign", "value": "', getFoot(tokenId), '"}, {"trait_type": "Levels", "value": "', getHand(tokenId), '"}, {"trait_type": "Activation", "value": "', getNeck(tokenId), '"}, {"trait_type": "Charge", "value": "', getRing(tokenId), '"}] | function tokenURI(uint256 tokenId) override public view returns (string memory) {
string[17] memory parts;
parts[1] = getPower(tokenId);
parts[2] = '</text><text x="20" y="50" class="base">Luck - ';
parts[3] = getLuck(tokenId);
parts[4] = '</text><text x="20" y="70" class="base">Cooldown - ';
parts[5] = getCooldown(tokenId);
parts[6] = ' week(s)</text><text x="20" y="90" class="base">Affinity - ';
parts[7] = getAffinity(tokenId);
parts[8] = '</text><text x="20" y="110" class="base">Sigil - ';
parts[9] = getSigil(tokenId);
parts[10] = '</text><text x="20" y="130" class="base">Levels - ';
parts[11] = getLevels(tokenId);
parts[12] = '</text><text x="20" y="150" class="base">Activation - ';
parts[13] = getActivation(tokenId);
parts[14] = ' day(s)</text><text x="20" y="170" class="base">Volume - ';
parts[15] = getVolume(tokenId);
parts[16] = '</text><text x="132" y="275" class="base" style="font-size: 10px; letter-spacing: 1.5; fill: purple">The Alchemist\'s</text><text x="117" y="300" class="base" style="font-size: 20px; letter-spacing: 5;">GLIMMER</text></svg>';
string memory output = string(abi.encodePacked(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6], parts[7], parts[8]));
output = string(abi.encodePacked(output, parts[9], parts[10], parts[11], parts[12], parts[13], parts[14], parts[15], parts[16]));
output = string(abi.encodePacked('data:application/json;base64,', json));
return output;
}
| 9,837,597 |
./partial_match/1/0x000000000000f968845afB0B8Cf134Ec196D38D4/sources/contracts/controller/ArrngController.sol | requestWithMethod: public method to allow calls specifying the arrng method, allowing functionality to be extensible without requiring a new controller contract. requestWithMethod is overloaded. In this instance you must specify the refund address for unused native token. numberOfNumbers_: the amount of numbers to request minValue_: the min of the range maxValue_: the max of the range refundAddress_: the address for refund of native token method_: the arrng method to call return uniqueID_ : unique ID for this request/ | function requestWithMethod(
uint256 numberOfNumbers_,
uint256 minValue_,
uint256 maxValue_,
address refundAddress_,
uint32 method_
) public payable returns (uint256 uniqueID_) {
return
_requestRandomness(
msg.sender,
msg.value,
method_,
numberOfNumbers_,
minValue_,
maxValue_,
refundAddress_
);
}
| 15,927,267 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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);
}
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional 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);
}
/**
* @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);
}
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);
}
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () internal {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
/**
* @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;
}
}
/**
* @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);
}
}
}
}
/**
* @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));
}
}
/**
* @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 EnumerableMap {
// 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 Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @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) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` 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);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
/*
* @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 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 payable private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address payable msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address payable) {
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 payable newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract EmergenceGallery is
Ownable,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
using Counters for Counters.Counter;
struct Collection {
uint256 id;
uint256 invocations;
uint256 maxInvocations;
string script;
uint256 price;
uint256 partnerPercentage;
uint256 saleStart;
address payable partner;
}
event Mint(
address indexed to,
uint256 collectionId,
uint256 tokenId,
uint256 amount,
bytes32 hash
);
// token and colelction id counter
Counters.Counter private _collectionIdTracker;
// Contract owner
// address payable _owner;
// Mapping from id to colletions
mapping(uint256 => Collection) private _collections;
// Mapping from id to tokens
mapping(uint256 => bytes32) private _tokenIdToHash;
mapping(uint256 => uint256) private _tokenIdToCollectionId;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// 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;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory name_,
string memory symbol_,
string memory uri_
) public {
_name = name_;
_symbol = symbol_;
// _owner = owner_;
_baseURI = uri_;
_collectionIdTracker.increment();
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
modifier onlyArtist(uint256 _collectionId) {
require(
_collections[_collectionId].partner == _msgSender(),
"EmergenceGallery: only partner can call this function"
);
_;
}
function withdrawOwner(uint256 value) public onlyOwner {
owner().transfer(value);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"EmergenceGallery: balance query for the zero address"
);
return _holderTokens[owner].length();
}
function createCollection(
uint256 _price,
address payable _partner,
uint256 _partnerPercentage,
uint256 _maxInvocations,
uint256 _saleStart,
string memory _script
) public onlyOwner {
require(
_saleStart >= block.timestamp,
"EmergenceGallyer: saleStart must be grater than now"
);
require(
_saleStart <= block.timestamp.add(3600 * 24 * 7),
"EmergenceGallyer: saleStart must be maximum 7 days in the future"
);
uint256 collectionId = _collectionIdTracker.current();
_collections[collectionId] = Collection({
id: collectionId,
invocations: 0,
maxInvocations: _maxInvocations,
script: _script,
saleStart: _saleStart,
price: _price,
partnerPercentage: _partnerPercentage,
partner: _partner
});
_collectionIdTracker.increment();
}
function purchaseTo(address _to, uint256 _collectionId) public payable {
require(
_collections[_collectionId].id != 0,
"EmergenceGallery: collection id not found"
);
require(
_collections[_collectionId].invocations <
_collections[_collectionId].maxInvocations,
"EmergenceGallery: max invocations already reached"
);
require(
_collections[_collectionId].saleStart <= block.timestamp ||
_msgSender() == owner(),
"EmergenceGallery: sale not started yet"
);
require(
_collections[_collectionId].price == msg.value,
"EmergenceGallery: wrong amount sent"
);
uint256 _tokenId = _collectionId *
1000 +
_collections[_collectionId].invocations.add(1);
_collections[_collectionId].invocations = _collections[_collectionId]
.invocations
.add(1);
bytes32 hash = keccak256(
abi.encodePacked(
_collections[_collectionId].invocations,
block.number,
msg.sender
)
);
_tokenIdToHash[_tokenId] = hash;
_tokenIdToCollectionId[_tokenId] = _collectionId;
uint256 artistReward = msg
.value
.mul(_collections[_collectionId].partnerPercentage)
.div(100);
_collections[_collectionId].partner.transfer(artistReward);
_safeMint(_to, _tokenId);
emit Mint(_to, _collectionId, _tokenId, 1, hash);
}
function purchase(uint256 _collectionId) public payable {
purchaseTo(msg.sender, _collectionId);
}
function burn(uint256 tokenId) public {
_burn(tokenId);
}
function updatePartnerAddress(uint256 _collectionId, address payable _partner)
public
onlyArtist(_collectionId)
{
_collections[_collectionId].partner = _partner;
}
function updateMaxInvocations(
uint256 _collectionId,
uint256 _maxInvocations
) public onlyOwner {
_collections[_collectionId].maxInvocations = _maxInvocations;
}
function getCollectionInfo(uint256 _collectionId)
public
view
returns (
uint256 id,
uint256 invocations,
uint256 maxInvocations,
string memory script,
uint256 price,
address payable partner,
uint256 partnerPercentage
)
{
require(
_collections[_collectionId].id != 0,
"EmergenceGallery: collection id not found"
);
return (
_collections[_collectionId].id,
_collections[_collectionId].invocations,
_collections[_collectionId].maxInvocations,
_collections[_collectionId].script,
_collections[_collectionId].price,
_collections[_collectionId].partner,
_collections[_collectionId].partnerPercentage
);
}
function getTokenInfo(uint256 _tokenId)
public
view
returns (
uint256,
uint256,
address,
bytes32
)
{
_exists(_tokenId);
bytes32 hash = _tokenIdToHash[_tokenId];
uint256 _collectionId = _tokenIdToCollectionId[_tokenId];
address owner = EmergenceGallery.ownerOf(_tokenId);
return (_tokenId, _collectionId, owner, hash);
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return
_tokenOwners.get(
tokenId,
"EmergenceGallery: owner query for nonexistent token"
);
}
/**
* @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 _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));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = EmergenceGallery.ownerOf(tokenId);
require(to != owner, "EmergenceGallery: approval to current owner");
require(
_msgSender() == owner ||
EmergenceGallery.isApprovedForAll(owner, _msgSender()),
"EmergenceGallery: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"EmergenceGallery: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(
operator != _msgSender(),
"EmergenceGallery: approve to caller"
);
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"EmergenceGallery: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"EmergenceGallery: 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),
"EmergenceGallery: 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 _tokenOwners.contains(tokenId);
}
/**
* @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),
"EmergenceGallery: operator query for nonexistent token"
);
address owner = EmergenceGallery.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
EmergenceGallery.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `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),
"EmergenceGallery: 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), "EmergenceGallery: mint to the zero address");
require(!_exists(tokenId), "EmergenceGallery: token already minted");
_holderTokens[to].add(tokenId);
_tokenOwners.set(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 = EmergenceGallery.ownerOf(tokenId); // internal owner
require(
_msgSender() == owner,
"EmergenceGallery: only token owner can burn"
);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(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(
EmergenceGallery.ownerOf(tokenId) == from,
"EmergenceGallery: transfer of token that is not own"
); // internal owner
require(
to != address(0),
"EmergenceGallery: transfer to the zero address"
);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function setTokenURI(uint256 tokenId, string memory _tokenURI)
public
onlyOwner
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function setBaseURI(string memory baseURI_) public onlyOwner {
_baseURI = baseURI_;
}
/**
* @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()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"EmergenceGallery: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(EmergenceGallery.ownerOf(tokenId), to, tokenId); // internal owner
}
} | Sets `_tokenURI` as the tokenURI of `tokenId`. Requirements: - `tokenId` must exist./ | function setTokenURI(uint256 tokenId, string memory _tokenURI)
public
onlyOwner
{
require(
_exists(tokenId),
"ERC721Metadata: URI set of nonexistent token"
);
_tokenURIs[tokenId] = _tokenURI;
}
| 337,752 |
/// SPDX-License-Identifier: MIT
/*
▄▄█ ▄ ██ █▄▄▄▄ ▄█
██ █ █ █ █ ▄▀ ██
██ ██ █ █▄▄█ █▀▀▌ ██
▐█ █ █ █ █ █ █ █ ▐█
▐ █ █ █ █ █ ▐
█ ██ █ ▀
▀ */
/// Special thanks to Keno, Boring and Gonpachi for review and continued inspiration.
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
/// @notice A library for performing overflow-/underflow-safe math,
/// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math).
library BoringMath {
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a + b) >= b, "BoringMath: Add Overflow");
}
function sub(uint256 a, uint256 b) internal pure returns (uint256 c) {
require((c = a - b) <= a, "BoringMath: Underflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow");
}
function to128(uint256 a) internal pure returns (uint128 c) {
require(a <= uint128(-1), "BoringMath: uint128 Overflow");
c = uint128(a);
}
function to64(uint256 a) internal pure returns (uint64 c) {
require(a <= uint64(-1), "BoringMath: uint64 Overflow");
c = uint64(a);
}
function to32(uint256 a) internal pure returns (uint32 c) {
require(a <= uint32(-1), "BoringMath: uint32 Overflow");
c = uint32(a);
}
}
/// @notice Interface for depositing into and withdrawing from Aave lending pool.
interface IAaveBridge {
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address token,
uint256 amount,
address destination
) external;
}
/// @notice Interface for depositing into and withdrawing from BentoBox vault.
interface IBentoBridge {
function balanceOf(IERC20, address) external view returns (uint256);
function registerProtocol() external;
function deposit(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external payable returns (uint256 amountOut, uint256 shareOut);
function withdraw(
IERC20 token_,
address from,
address to,
uint256 amount,
uint256 share
) external returns (uint256 amountOut, uint256 shareOut);
}
/// @notice Interface for depositing into and withdrawing from Compound finance protocol.
interface ICompoundBridge {
function underlying() external view returns (address);
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
}
/// @notice Interface for Dai Stablecoin (DAI) `permit()` primitive.
interface IDaiPermit {
function permit(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
/// @notice Interface for depositing into and withdrawing from SushiBar.
interface ISushiBarBridge {
function enter(uint256 amount) external;
function leave(uint256 share) external;
}
/// @notice Interface for SushiSwap.
interface ISushiSwap {
function deposit() external payable;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
// File @boringcrypto/boring-solidity/contracts/interfaces/[email protected]
/// License-Identifier: MIT
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, 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);
/// @notice EIP 2612
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File @boringcrypto/boring-solidity/contracts/libraries/[email protected]
/// License-Identifier: MIT
library BoringERC20 {
bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol()
bytes4 private constant SIG_NAME = 0x06fdde03; // name()
bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals()
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
/// @notice Provides a safe ERC20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransfer(
IERC20 token,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: Transfer failed");
}
/// @notice Provides a safe ERC20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 amount
) internal {
(bool success, bytes memory data) = address(token).call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), "BoringERC20: TransferFrom failed");
}
}
// File @boringcrypto/boring-solidity/contracts/[email protected]
/// License-Identifier: MIT
contract BaseBoringBatchable {
/// @dev Helper function to extract a useful revert message from a failed call.
/// If the returned data is malformed or not correctly abi encoded then this call can fail itself.
function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/// @notice Allows batched call to self (this contract).
/// @param calls An array of inputs for each call.
/// @param revertOnFail If True then reverts after a failed call and stops doing further calls.
/// @return successes An array indicating the success of a call, mapped one-to-one to `calls`.
/// @return results An array with the returned data of each function call, mapped one-to-one to `calls`.
// F1: External is ok here because this is the batch function, adding it to a batch makes no sense
// F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value
// C3: The length of the loop is fully under user control, so can't be exploited
// C7: Delegatecall is only used on the same contract, so it's safe
function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results) {
successes = new bool[](calls.length);
results = new bytes[](calls.length);
for (uint256 i = 0; i < calls.length; i++) {
(bool success, bytes memory result) = address(this).delegatecall(calls[i]);
require(success || !revertOnFail, _getRevertMsg(result));
successes[i] = success;
results[i] = result;
}
}
}
/// @notice Extends `BoringBatchable` with DAI `permit()`.
contract BoringBatchableWithDai is BaseBoringBatchable {
address constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; // DAI token contract
/// @notice Call wrapper that performs `ERC20.permit` on `dai` using EIP 2612 primitive.
/// Lookup `IDaiPermit.permit`.
function permitDai(
address holder,
address spender,
uint256 nonce,
uint256 expiry,
bool allowed,
uint8 v,
bytes32 r,
bytes32 s
) public {
IDaiPermit(dai).permit(holder, spender, nonce, expiry, allowed, v, r, s);
}
/// @notice Call wrapper that performs `ERC20.permit` on `token`.
/// Lookup `IERC20.permit`.
// F6: Parameters can be used front-run the permit and the user's permit will fail (due to nonce or other revert)
// if part of a batch this could be used to grief once as the second call would not need the permit
function permitToken(
IERC20 token,
address from,
address to,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public {
token.permit(from, to, amount, deadline, v, r, s);
}
}
/// @notice Contract that batches SUSHI staking and DeFi strategies - V1.
contract Inari is BoringBatchableWithDai {
using BoringMath for uint256;
using BoringERC20 for IERC20;
IERC20 constant sushiToken = IERC20(0x6B3595068778DD592e39A122f4f5a5cF09C90fE2); // SUSHI token contract
address constant sushiBar = 0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272; // xSUSHI staking contract for SUSHI
IAaveBridge constant aave = IAaveBridge(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9); // AAVE lending pool contract for xSUSHI staking into aXSUSHI
IERC20 constant aaveSushiToken = IERC20(0xF256CC7847E919FAc9B808cC216cAc87CCF2f47a); // aXSUSHI staking contract for xSUSHI
IBentoBridge constant bento = IBentoBridge(0xF5BCE5077908a1b7370B9ae04AdC565EBd643966); // BENTO vault contract
address constant crSushiToken = 0x338286C0BC081891A4Bda39C7667ae150bf5D206; // crSUSHI staking contract for SUSHI
address constant crXSushiToken = 0x228619CCa194Fbe3Ebeb2f835eC1eA5080DaFbb2; // crXSUSHI staking contract for xSUSHI
address constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; // ETH wrapper contract (v9)
address constant sushiSwapFactory = 0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac; // SushiSwap factory contract
ISushiSwap constant sushiSwapSushiETHPair = ISushiSwap(0x795065dCc9f64b5614C407a6EFDC400DA6221FB0); // SUSHI/ETH pair on SushiSwap
bytes32 constant pairCodeHash = 0xe18a34eb0e04b04f7a0ac29a6e80748dca96319b42c54d679cb821dca90c6303; // SushiSwap pair code hash
/// @notice Initialize this Inari contract and core SUSHI strategies.
constructor() public {
bento.registerProtocol(); // register this contract with BENTO
sushiToken.approve(address(sushiBar), type(uint256).max); // max approve `sushiBar` spender to stake SUSHI into xSUSHI from this contract
sushiToken.approve(crSushiToken, type(uint256).max); // max approve `crSushiToken` spender to stake SUSHI into crSUSHI from this contract
IERC20(sushiBar).approve(address(aave), type(uint256).max); // max approve `aave` spender to stake xSUSHI into aXSUSHI from this contract
IERC20(sushiBar).approve(address(bento), type(uint256).max); // max approve `bento` spender to stake xSUSHI into BENTO from this contract
IERC20(sushiBar).approve(crXSushiToken, type(uint256).max); // max approve `crXSushiToken` spender to stake xSUSHI into crXSUSHI from this contract
IERC20(dai).approve(address(bento), type(uint256).max); // max approve `bento` spender to pull DAI into BENTO from this contract
}
/// @notice Helper function to approve this contract to spend and bridge more tokens among DeFi contracts.
function bridgeABC(IERC20[] calldata underlying, address[] calldata cToken) external {
for (uint256 i = 0; i < underlying.length; i++) {
underlying[i].approve(address(aave), type(uint256).max); // max approve `aave` spender to pull `underlying` from this contract
underlying[i].approve(address(bento), type(uint256).max); // max approve `bento` spender to pull `underlying` from this contract
underlying[i].approve(cToken[i], type(uint256).max); // max approve `cToken` spender to pull `underlying` from this contract (also serves as generalized approval bridge)
}
}
/************
SUSHI HELPERS
************/
/// @notice Stake SUSHI `amount` into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushi(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice Stake SUSHI local balance into xSushi for benefit of `to` by call to `sushiBar`.
function stakeSushiBalance(address to) external {
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake local SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/**********
TKN HELPERS
**********/
/// @notice Token deposit function for `batch()` into strategies.
function depositToken(IERC20 token, uint256 amount) external {
IERC20(token).safeTransferFrom(msg.sender, address(this), amount);
}
/// @notice Token withdraw function for `batch()` into strategies.
function withdrawToken(IERC20 token, address to, uint256 amount) external {
IERC20(token).safeTransfer(to, amount);
}
/// @notice Token local balance withdraw function for `batch()` into strategies.
function withdrawTokenBalance(IERC20 token, address to) external {
IERC20(token).safeTransfer(to, token.balanceOf(address(this)));
}
/*
██ ██ ▄ ▄███▄
█ █ █ █ █ █▀ ▀
█▄▄█ █▄▄█ █ █ ██▄▄
█ █ █ █ █ █ █▄ ▄▀
█ █ █ █ ▀███▀
█ █ █▐
▀ ▀ ▐ */
/***********
AAVE HELPERS
***********/
function toAave(address underlying, address to, uint256 amount) external {
aave.deposit(underlying, amount, to, 0);
}
function balanceToAave(address underlying, address to) external {
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0);
}
function fromAave(address underlying, address to, uint256 amount) external {
aave.withdraw(underlying, amount, to);
}
function balanceFromAave(address aToken, address to) external {
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, IERC20(aToken).balanceOf(address(this)), to);
}
/**************************
AAVE -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into BENTO for benefit of `to` by batching calls to `aave` and `bento`.
function aaveToBento(address aToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
bento.deposit(IERC20(underlying), address(this), to, amount, 0); // stake `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> AAVE
**************************/
/// @notice Migrate `underlying` `amount` from BENTO into AAVE for benefit of `to` by batching calls to `bento` and `aave`.
function bentoToAave(IERC20 underlying, address to, uint256 amount) external {
bento.withdraw(underlying, msg.sender, address(this), amount, 0); // withdraw `amount` of `underlying` from BENTO into this contract
aave.deposit(address(underlying), amount, to, 0); // stake `underlying` into `aave` for `to`
}
/*************************
AAVE -> UNDERLYING -> COMP
*************************/
/// @notice Migrate AAVE `aToken` underlying `amount` into COMP/CREAM `cToken` for benefit of `to` by batching calls to `aave` and `cToken`.
function aaveToCompound(address aToken, address cToken, address to, uint256 amount) external {
IERC20(aToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `aToken` `amount` into this contract
address underlying = IAaveBridge(aToken).UNDERLYING_ASSET_ADDRESS(); // sanity check for `underlying` token
aave.withdraw(underlying, amount, address(this)); // burn deposited `aToken` from `aave` into `underlying`
ICompoundBridge(cToken).mint(amount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/*************************
COMP -> UNDERLYING -> AAVE
*************************/
/// @notice Migrate COMP/CREAM `cToken` underlying `amount` into AAVE for benefit of `to` by batching calls to `cToken` and `aave`.
function compoundToAave(address cToken, address to, uint256 amount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` `cToken` `amount` into this contract
ICompoundBridge(cToken).redeem(amount); // burn deposited `cToken` into `underlying`
address underlying = ICompoundBridge(cToken).underlying(); // sanity check for `underlying` token
aave.deposit(underlying, IERC20(underlying).balanceOf(address(this)), to, 0); // stake resulting `underlying` into `aave` for `to`
}
/**********************
SUSHI -> XSUSHI -> AAVE
**********************/
/// @notice Stake SUSHI `amount` into aXSUSHI for benefit of `to` by batching calls to `sushiBar` and `aave`.
function stakeSushiToAave(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
aave.deposit(sushiBar, IERC20(sushiBar).balanceOf(address(this)), to, 0); // stake resulting xSUSHI into `aave` aXSUSHI for `to`
}
/**********************
AAVE -> XSUSHI -> SUSHI
**********************/
/// @notice Unstake aXSUSHI `amount` into SUSHI for benefit of `to` by batching calls to `aave` and `sushiBar`.
function unstakeSushiFromAave(address to, uint256 amount) external {
aaveSushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` aXSUSHI `amount` into this contract
aave.withdraw(sushiBar, amount, address(this)); // burn deposited aXSUSHI from `aave` into xSUSHI
ISushiBarBridge(sushiBar).leave(amount); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
███ ▄███▄ ▄ ▄▄▄▄▀ ████▄
█ █ █▀ ▀ █ ▀▀▀ █ █ █
█ ▀ ▄ ██▄▄ ██ █ █ █ █
█ ▄▀ █▄ ▄▀ █ █ █ █ ▀████
███ ▀███▀ █ █ █ ▀
█ ██ */
/// @notice Helper function to `permit()` this contract to deposit `dai` into `bento` for benefit of `to`.
function daiToBentoWithPermit(
address to, uint256 amount, uint256 nonce, uint256 expiry,
uint8 v, bytes32 r, bytes32 s
) external {
IDaiPermit(dai).permit(msg.sender, address(this), nonce, expiry, true, v, r, s); // `permit()` this contract to spend `msg.sender` `dai`
IERC20(dai).safeTransferFrom(msg.sender, address(this), amount); // pull `dai` `amount` into this contract
bento.deposit(IERC20(dai), address(this), to, amount, 0); // stake `dai` into BENTO for `to`
}
/************
BENTO HELPERS
************/
function toBento(IERC20 token, address to, uint256 amount) external {
bento.deposit(token, address(this), to, amount, 0);
}
function balanceToBento(IERC20 token, address to) external {
bento.deposit(token, address(this), to, token.balanceOf(address(this)), 0);
}
function fromBento(IERC20 token, address to, uint256 amount) external {
bento.withdraw(token, msg.sender, to, amount, 0);
}
function balanceFromBento(IERC20 token, address to) external {
bento.withdraw(token, msg.sender, to, bento.balanceOf(token, msg.sender), 0);
}
/***********************
SUSHI -> XSUSHI -> BENTO
***********************/
/// @notice Stake SUSHI `amount` into BENTO xSUSHI for benefit of `to` by batching calls to `sushiBar` and `bento`.
function stakeSushiToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI into `sushiBar` xSUSHI
bento.deposit(IERC20(sushiBar), address(this), to, IERC20(sushiBar).balanceOf(address(this)), 0); // stake resulting xSUSHI into BENTO for `to`
}
/***********************
BENTO -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake xSUSHI `amount` from BENTO into SUSHI for benefit of `to` by batching calls to `bento` and `sushiBar`.
function unstakeSushiFromBento(address to, uint256 amount) external {
bento.withdraw(IERC20(sushiBar), msg.sender, address(this), amount, 0); // withdraw `amount` of xSUSHI from BENTO into this contract
ISushiBarBridge(sushiBar).leave(amount); // burn withdrawn xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█
█▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █
█ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █
█▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █
▀███▀ █ ▀███▀ █ █
▀ █ ▀
▀ */
// - COMPOUND - //
/***********
COMP HELPERS
***********/
function toCompound(ICompoundBridge cToken, uint256 underlyingAmount) external {
cToken.mint(underlyingAmount);
}
function balanceToCompound(ICompoundBridge cToken) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
cToken.mint(underlying.balanceOf(address(this)));
}
function fromCompound(ICompoundBridge cToken, uint256 cTokenAmount) external {
ICompoundBridge(cToken).redeem(cTokenAmount);
}
function balanceFromCompound(address cToken) external {
ICompoundBridge(cToken).redeem(IERC20(cToken).balanceOf(address(this)));
}
/**************************
COMP -> UNDERLYING -> BENTO
**************************/
/// @notice Migrate COMP/CREAM `cToken` `cTokenAmount` into underlying and BENTO for benefit of `to` by batching calls to `cToken` and `bento`.
function compoundToBento(address cToken, address to, uint256 cTokenAmount) external {
IERC20(cToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `cToken` `cTokenAmount` into this contract
ICompoundBridge(cToken).redeem(cTokenAmount); // burn deposited `cToken` into `underlying`
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.deposit(underlying, address(this), to, underlying.balanceOf(address(this)), 0); // stake resulting `underlying` into BENTO for `to`
}
/**************************
BENTO -> UNDERLYING -> COMP
**************************/
/// @notice Migrate `cToken` `underlyingAmount` from BENTO into COMP/CREAM for benefit of `to` by batching calls to `bento` and `cToken`.
function bentoToCompound(address cToken, address to, uint256 underlyingAmount) external {
IERC20 underlying = IERC20(ICompoundBridge(cToken).underlying()); // sanity check for `underlying` token
bento.withdraw(underlying, msg.sender, address(this), underlyingAmount, 0); // withdraw `underlyingAmount` of `underlying` from BENTO into this contract
ICompoundBridge(cToken).mint(underlyingAmount); // stake `underlying` into `cToken`
IERC20(cToken).safeTransfer(to, IERC20(cToken).balanceOf(address(this))); // transfer resulting `cToken` to `to`
}
/**********************
SUSHI -> CREAM -> BENTO
**********************/
/// @notice Stake SUSHI `amount` into crSUSHI and BENTO for benefit of `to` by batching calls to `crSushiToken` and `bento`.
function sushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ICompoundBridge(crSushiToken).mint(amount); // stake deposited SUSHI into crSUSHI
bento.deposit(IERC20(crSushiToken), address(this), to, IERC20(crSushiToken).balanceOf(address(this)), 0); // stake resulting crSUSHI into BENTO for `to`
}
/**********************
BENTO -> CREAM -> SUSHI
**********************/
/// @notice Unstake crSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento` and `crSushiToken`.
function sushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crSushiToken` from BENTO into this contract
ICompoundBridge(crSushiToken).redeem(cTokenAmount); // burn deposited `crSushiToken` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/***********************
SUSHI -> XSUSHI -> CREAM
***********************/
/// @notice Stake SUSHI `amount` into crXSUSHI for benefit of `to` by batching calls to `sushiBar` and `crXSushiToken`.
function stakeSushiToCream(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
IERC20(crXSushiToken).safeTransfer(to, IERC20(crXSushiToken).balanceOf(address(this))); // transfer resulting crXSUSHI to `to`
}
/***********************
CREAM -> XSUSHI -> SUSHI
***********************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI for benefit of `to` by batching calls to `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCream(address to, uint256 cTokenAmount) external {
IERC20(crXSushiToken).safeTransferFrom(msg.sender, address(this), cTokenAmount); // deposit `msg.sender` `crXSushiToken` `cTokenAmount` into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI `amount` from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/********************************
SUSHI -> XSUSHI -> CREAM -> BENTO
********************************/
/// @notice Stake SUSHI `amount` into crXSUSHI and BENTO for benefit of `to` by batching calls to `sushiBar`, `crXSushiToken` and `bento`.
function stakeSushiToCreamToBento(address to, uint256 amount) external {
sushiToken.safeTransferFrom(msg.sender, address(this), amount); // deposit `msg.sender` SUSHI `amount` into this contract
ISushiBarBridge(sushiBar).enter(amount); // stake deposited SUSHI `amount` into `sushiBar` xSUSHI
ICompoundBridge(crXSushiToken).mint(IERC20(sushiBar).balanceOf(address(this))); // stake resulting xSUSHI into crXSUSHI
bento.deposit(IERC20(crXSushiToken), address(this), to, IERC20(crXSushiToken).balanceOf(address(this)), 0); // stake resulting crXSUSHI into BENTO for `to`
}
/********************************
BENTO -> CREAM -> XSUSHI -> SUSHI
********************************/
/// @notice Unstake crXSUSHI `cTokenAmount` into SUSHI from BENTO for benefit of `to` by batching calls to `bento`, `crXSushiToken` and `sushiBar`.
function unstakeSushiFromCreamFromBento(address to, uint256 cTokenAmount) external {
bento.withdraw(IERC20(crXSushiToken), msg.sender, address(this), cTokenAmount, 0); // withdraw `cTokenAmount` of `crXSushiToken` from BENTO into this contract
ICompoundBridge(crXSushiToken).redeem(cTokenAmount); // burn deposited `crXSushiToken` `cTokenAmount` into xSUSHI
ISushiBarBridge(sushiBar).leave(IERC20(sushiBar).balanceOf(address(this))); // burn resulting xSUSHI from `sushiBar` into SUSHI
sushiToken.safeTransfer(to, sushiToken.balanceOf(address(this))); // transfer resulting SUSHI to `to`
}
/*
▄▄▄▄▄ ▄ ▄ ██ █ ▄▄
█ ▀▄ █ █ █ █ █ █
▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀
▀▄▄▄▄▀ █ █ █ █ █ █
█ █ █ █ █
▀ ▀ █ ▀
▀ */
/// @notice SushiSwap ETH to stake SUSHI into xSUSHI for benefit of `to`.
function ethStakeSushi(address to) external payable { // SWAP `N STAKE
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
ISushiSwap(wETH).deposit{value: msg.value}();
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(amountOut, 0, address(this), "");
ISushiBarBridge(sushiBar).enter(sushiToken.balanceOf(address(this))); // stake resulting SUSHI into `sushiBar` xSUSHI
IERC20(sushiBar).safeTransfer(to, IERC20(sushiBar).balanceOf(address(this))); // transfer resulting xSUSHI to `to`
}
/// @notice SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`.
function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(this), amountIn);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap local `fromToken` balance in this contract to `toToken` for benefit of `to`.
function swapBalance(address fromToken, address toToken, address to) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
uint256 amountIn = IERC20(fromToken).balanceOf(address(this));
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(fromToken).safeTransfer(address(pair), amountIn);
pair.swap(amountOut, 0, to, "");
}
}
/// @notice SushiSwap ETH `msg.value` to `toToken` for benefit of `to`.
function swapETH(address toToken, address to) external payable returns (uint256 amountOut) {
(address token0, address token1) = wETH < toToken ? (wETH, toToken) : (toToken, wETH);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
ISushiSwap(wETH).deposit{value: msg.value}();
if (toToken > wETH) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(0, amountOut, to, "");
} else {
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(pair), msg.value);
pair.swap(amountOut, 0, to, "");
}
}
} | Interface for SushiSwap. | interface ISushiSwap {
function deposit() external payable;
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
}
| 43,958 |
//Address: 0xc2dc0c3054dB1740a9153B5D54911dB728672EAa
//Contract name: ZminePrivateSale
//Balance: 0 Ether
//Verification Date: 4/2/2018
//Transacion Count: 192
// CODE STARTS HERE
pragma solidity 0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Authorizable
* @dev The Authorizable contract has authorized addresses, and provides basic authorization control
* functions, this simplifies the implementation of "multiple user permissions".
*/
contract Authorizable is Ownable {
mapping(address => bool) public authorized;
event AuthorizationSet(address indexed addressAuthorized, bool indexed authorization);
/**
* @dev The Authorizable constructor sets the first `authorized` of the contract to the sender
* account.
*/
function Authorizable() public {
authorize(msg.sender);
}
/**
* @dev Throws if called by any account other than the authorized.
*/
modifier onlyAuthorized() {
require(authorized[msg.sender]);
_;
}
/**
* @dev Allows
* @param _address The address to change authorization.
*/
function authorize(address _address) public onlyOwner {
require(!authorized[_address]);
emit AuthorizationSet(_address, true);
authorized[_address] = true;
}
/**
* @dev Disallows
* @param _address The address to change authorization.
*/
function deauthorize(address _address) public onlyOwner {
require(authorized[_address]);
emit AuthorizationSet(_address, false);
authorized[_address] = false;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title PrivateSaleExchangeRate interface
*/
contract PrivateSaleExchangeRate {
uint256 public rate;
uint256 public timestamp;
event UpdateUsdEthRate(uint _rate);
function updateUsdEthRate(uint _rate) public;
function getTokenAmount(uint256 _weiAmount) public view returns (uint256);
}
/**
* @title Whitelist interface
*/
contract Whitelist {
mapping(address => bool) whitelisted;
event AddToWhitelist(address _beneficiary);
event RemoveFromWhitelist(address _beneficiary);
function isWhitelisted(address _address) public view returns (bool);
function addToWhitelist(address _beneficiary) public;
function removeFromWhitelist(address _beneficiary) public;
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
// Crowdsale
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
PrivateSaleExchangeRate public rate;
// Amount of wei raised
uint256 public weiRaised;
// Amount of wei raised (token)
uint256 public tokenRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function Crowdsale(PrivateSaleExchangeRate _rate, address _wallet, ERC20 _token) public {
require(_rate.rate() > 0);
require(_token != address(0));
require(_wallet != address(0));
rate = _rate;
token = _token;
wallet = _wallet;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
// calculate token amount to be created
uint256 tokenAmount = _getTokenAmount(weiAmount);
_preValidatePurchase(_beneficiary, weiAmount, tokenAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
tokenRaised = tokenRaised.add(tokenAmount);
_processPurchase(_beneficiary, tokenAmount);
emit TokenPurchase(msg.sender, _beneficiary, weiAmount, tokenAmount);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
require(_beneficiary != address(0));
require(_weiAmount > 0);
require(_tokenAmount > 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(address _beneficiary, uint256 _weiAmount) internal {
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) {
return rate.getTokenAmount(_weiAmount);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
require(now >= openingTime && now <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
require(_closingTime >= now);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
return now > closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is opened.
* @return Whether crowdsale period has elapsed
*/
function hasOpening() public view returns (bool) {
return (now >= openingTime && now <= closingTime);
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
}
}
/**
* @title AllowanceCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract AllowanceCrowdsale is Crowdsale {
using SafeMath for uint256;
address public tokenWallet;
/**
* @dev Constructor, takes token wallet address.
* @param _tokenWallet Address holding the tokens, which has approved allowance to the crowdsale
*/
function AllowanceCrowdsale(address _tokenWallet) public {
require(_tokenWallet != address(0));
tokenWallet = _tokenWallet;
}
/**
* @dev Overrides parent behavior by transferring tokens from wallet.
* @param _beneficiary Token purchaser
* @param _tokenAmount Amount of tokens purchased
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public minWei;
uint256 public capToken;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _capToken Max amount of token to be contributed
*/
function CappedCrowdsale(uint256 _capToken, uint256 _minWei) public {
require(_minWei > 0);
require(_capToken > 0);
minWei = _minWei;
capToken = _capToken;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
if(tokenRaised >= capToken) return true;
uint256 minTokens = rate.getTokenAmount(minWei);
if(capToken - tokenRaised <= minTokens) return true;
return false;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(_weiAmount >= minWei);
require(tokenRaised.add(_tokenAmount) <= capToken);
}
}
/**
* @title WhitelistedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract WhitelistedCrowdsale is Crowdsale {
using SafeMath for uint256;
// Only KYC investor allowed to buy the token
Whitelist public whitelist;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _whitelist whitelist contract
*/
function WhitelistedCrowdsale(Whitelist _whitelist) public {
whitelist = _whitelist;
}
function isWhitelisted(address _address) public view returns (bool) {
return whitelist.isWhitelisted(_address);
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(whitelist.isWhitelisted(_beneficiary));
}
}
/**
* @title ClaimedCrowdsale
* @dev Extension of Crowdsale where tokens are held by a wallet, which approves an allowance to the crowdsale.
*/
contract ClaimCrowdsale is Crowdsale, Authorizable {
using SafeMath for uint256;
uint256 divider;
event ClaimToken(address indexed claimant, address indexed beneficiary, uint256 claimAmount);
// Claim remain amount of token
//addressIndices not use index 0
address[] public addressIndices;
// get amount of claim token
mapping(address => uint256) mapAddressToToken;
//get index of addressIndices if = 0 >> not found
mapping(address => uint256) mapAddressToIndex;
// Amount of wei waiting for claim (token)
uint256 public waitingForClaimTokens;
/**
* @dev Constructor, takes token wallet address.
*/
function ClaimCrowdsale(uint256 _divider) public {
require(_divider > 0);
divider = _divider;
addressIndices.push(address(0));
}
/**
* @dev Claim remained token after closed time
*/
function claim(address _beneficiary) public onlyAuthorized {
require(_beneficiary != address(0));
require(mapAddressToToken[_beneficiary] > 0);
// remove from list
uint indexToBeDeleted = mapAddressToIndex[_beneficiary];
require(indexToBeDeleted != 0);
uint arrayLength = addressIndices.length;
// if index to be deleted is not the last index, swap position.
if (indexToBeDeleted < arrayLength-1) {
// swap
addressIndices[indexToBeDeleted] = addressIndices[arrayLength-1];
mapAddressToIndex[addressIndices[indexToBeDeleted]] = indexToBeDeleted;
}
// we can now reduce the array length by 1
addressIndices.length--;
mapAddressToIndex[_beneficiary] = 0;
// deliver token
uint256 _claimAmount = mapAddressToToken[_beneficiary];
mapAddressToToken[_beneficiary] = 0;
waitingForClaimTokens = waitingForClaimTokens.sub(_claimAmount);
emit ClaimToken(msg.sender, _beneficiary, _claimAmount);
_deliverTokens(_beneficiary, _claimAmount);
}
function checkClaimTokenByIndex(uint index) public view returns (uint256){
require(index >= 0);
require(index < addressIndices.length);
return checkClaimTokenByAddress(addressIndices[index]);
}
function checkClaimTokenByAddress(address _beneficiary) public view returns (uint256){
require(_beneficiary != address(0));
return mapAddressToToken[_beneficiary];
}
function countClaimBackers() public view returns (uint256) {
return addressIndices.length-1;
}
function _addToClaimList(address _beneficiary, uint256 _claimAmount) internal {
require(_beneficiary != address(0));
require(_claimAmount > 0);
if(mapAddressToToken[_beneficiary] == 0){
addressIndices.push(_beneficiary);
mapAddressToIndex[_beneficiary] = addressIndices.length-1;
}
waitingForClaimTokens = waitingForClaimTokens.add(_claimAmount);
mapAddressToToken[_beneficiary] = mapAddressToToken[_beneficiary].add(_claimAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal {
// To protect our private-sale investors who transfered eth via wallet from exchange.
// Instead of send all tokens amount back, the private-sale contract will send back in small portion of tokens (ppm).
// The full amount of tokens will be send later after the investor has confirmed received amount to us.
uint256 tokenSampleAmount = _tokenAmount.div(divider);
_addToClaimList(_beneficiary, _tokenAmount.sub(tokenSampleAmount));
_deliverTokens(_beneficiary, tokenSampleAmount);
}
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
// ZMINE
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
/**
* @title ZminePrivateSale
*/
contract ZminePrivateSale is ClaimCrowdsale
, AllowanceCrowdsale
, CappedCrowdsale
, TimedCrowdsale
, WhitelistedCrowdsale {
using SafeMath for uint256;
/**
* @param _rate Number of token units a buyer gets per wei
* @param _whitelist Allowd address of buyer
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
function ZminePrivateSale(PrivateSaleExchangeRate _rate
, Whitelist _whitelist
, uint256 _capToken
, uint256 _minWei
, uint256 _openingTime
, uint256 _closingTime
, address _wallet
, address _tokenWallet
, ERC20 _token
) public
Crowdsale(_rate, _wallet, _token)
ClaimCrowdsale(1000000)
AllowanceCrowdsale(_tokenWallet)
CappedCrowdsale(_capToken, _minWei)
TimedCrowdsale(_openingTime, _closingTime)
WhitelistedCrowdsale(_whitelist)
{
}
function calculateTokenAmount(uint256 _weiAmount) public view returns (uint256) {
return rate.getTokenAmount(_weiAmount);
}
/**
* @dev Checks the amount of tokens left in the allowance.
* @return Amount of tokens left in the allowance
*/
function remainingTokenForSale() public view returns (uint256) {
uint256 allowanceTokenLeft = (token.allowance(tokenWallet, this)).sub(waitingForClaimTokens);
uint256 balanceTokenLeft = (token.balanceOf(tokenWallet)).sub(waitingForClaimTokens);
if(allowanceTokenLeft < balanceTokenLeft) return allowanceTokenLeft;
return balanceTokenLeft;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount, uint256 _tokenAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount, _tokenAmount);
require(remainingTokenForSale().sub(_tokenAmount) >= 0);
}
}
// -----------------------------------------
// -----------------------------------------
// -----------------------------------------
| Overrides parent behavior by transferring tokens from wallet. _beneficiary Token purchaser _tokenAmount Amount of tokens purchased/ | function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
token.transferFrom(tokenWallet, _beneficiary, _tokenAmount);
}
| 2,529,126 |
pragma solidity ^0.4.23;
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract IGTToken is StandardToken {
string public constant name = "IGT Token";
string public constant symbol = "IGTT";
uint32 public constant decimals = 18;
uint256 public INITIAL_SUPPLY = 21000000 * 1 ether;
address public CrowdsaleAddress;
uint256 public soldTokens;
bool public lockTransfers = true;
function getSoldTokens() public view returns (uint256) {
return soldTokens;
}
constructor(address _CrowdsaleAddress) public {
CrowdsaleAddress = _CrowdsaleAddress;
totalSupply_ = INITIAL_SUPPLY;
balances[msg.sender] = INITIAL_SUPPLY;
}
modifier onlyOwner() {
require(msg.sender == CrowdsaleAddress);
_;
}
function setSoldTokens(uint256 _value) public onlyOwner {
soldTokens = _value;
}
function acceptTokens(address _from, uint256 _value) public onlyOwner returns (bool){
require (balances[_from] >= _value);
balances[_from] = balances[_from].sub(_value);
balances[CrowdsaleAddress] = balances[CrowdsaleAddress].add(_value);
emit Transfer(_from, CrowdsaleAddress, _value);
return true;
}
// Override
function transfer(address _to, uint256 _value) public returns(bool){
if (msg.sender != CrowdsaleAddress){
require(!lockTransfers, "Transfers are prohibited");
}
return super.transfer(_to,_value);
}
// Override
function transferFrom(address _from, address _to, uint256 _value) public returns(bool){
if (msg.sender != CrowdsaleAddress){
require(!lockTransfers, "Transfers are prohibited");
}
return super.transferFrom(_from,_to,_value);
}
function lockTransfer(bool _lock) public onlyOwner {
lockTransfers = _lock;
}
function() external payable {
// The token contract don`t receive ether
revert();
}
}
contract Ownable {
address public owner;
address public manager;
address candidate;
constructor() public {
owner = msg.sender;
manager = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
modifier restricted() {
require(msg.sender == owner || msg.sender == manager);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
require(_newOwner != address(0));
candidate = _newOwner;
}
function setManager(address _newManager) public onlyOwner {
manager = _newManager;
}
function confirmOwnership() public {
require(candidate == msg.sender);
owner = candidate;
delete candidate;
}
}
contract TeamAddress {
function() external payable {
// The contract don`t receive ether
revert();
}
}
contract Crowdsale is Ownable {
using SafeMath for uint;
address myAddress = this;
uint256 public startICODate;
IGTToken public token = new IGTToken(myAddress);
uint public additionalBonus = 0;
uint public endTimeAddBonus = 0;
event LogStateSwitch(State newState);
event ChangeToCoin(address indexed from, uint256 value);
enum State {
PreTune,
CrowdSale,
Migrate
}
State public currentState = State.PreTune;
TeamAddress public teamAddress = new TeamAddress();
constructor() public {
startICODate = uint256(now);
//uint sendTokens = 5250000;
giveTokens(address(teamAddress), 5250000);
// Stage CrowdSale is enable
nextState();
}
function nextState() internal {
currentState = State(uint(currentState) + 1);
}
function returnTokensFromTeamAddress(uint256 _value) public onlyOwner {
// the function take tokens from teamAddress to contract
// the sum is entered in whole tokens (1 = 1 token)
uint256 value = _value;
require (value >= 1);
value = value.mul(1 ether);
token.acceptTokens(address(teamAddress), value);
}
function lockExternalTransfer() public onlyOwner {
token.lockTransfer(true);
}
function unlockExternalTransfer() public onlyOwner {
token.lockTransfer(false);
}
function setMigrateStage() public onlyOwner {
require(currentState == State.CrowdSale);
require(token.balanceOf(address(teamAddress)) == 0);
nextState();
}
function changeToCoin(address _address, uint256 _value) public restricted {
require(currentState == State.Migrate);
token.acceptTokens(_address, _value);
emit ChangeToCoin(_address, _value);
}
function setAddBonus (uint _value, uint _endTimeBonus) public onlyOwner {
additionalBonus = _value;
endTimeAddBonus = _endTimeBonus;
}
function calcBonus () public view returns(uint256) {
// 2m - 12%
// 4m - 8%
// 6m - 6%
// 8m - 4%
// 10m - 2%
// 12.6m - 0%
uint256 amountToken = token.getSoldTokens();
uint256 actualBonus = 0;
if (amountToken < 2240000 * (1 ether)){
actualBonus = 12;
}
if (amountToken >= 2240000 * (1 ether) && amountToken < 4400000 * (1 ether)){
actualBonus = 8;
}
if (amountToken >= 4400000 * (1 ether) && amountToken < 6520000 * (1 ether)){
actualBonus = 6;
}
if (amountToken >= 6520000 * (1 ether) && amountToken < 8600000 * (1 ether)){
actualBonus = 4;
}
if (amountToken >= 8600000 * (1 ether) && amountToken < 10640000 * (1 ether)){
actualBonus = 2;
}
if (now < endTimeAddBonus){
actualBonus = actualBonus.add(additionalBonus);
}
return actualBonus;
}
function giveTokens(address _newInvestor, uint256 _value) public restricted {
// the function give tokens to new investors
// the sum is entered in whole tokens (1 = 1 token)
require(currentState != State.Migrate);
require (_newInvestor != address(0));
require (_value >= 1);
uint256 mySoldTokens = token.getSoldTokens();
uint256 value = _value;
value = value.mul(1 ether);
if (currentState != State.PreTune){
uint256 myBonus = calcBonus();
// Add Bonus
if (myBonus > 0){
value = value + value.mul(myBonus).div(100);
}
mySoldTokens = mySoldTokens.add(value);
token.setSoldTokens(mySoldTokens);
}
token.transfer(_newInvestor, value);
}
function() external payable {
// The contract don`t receive ether
revert();
}
} | 2m - 12% 4m - 8% 6m - 6% 8m - 4% 10m - 2% 12.6m - 0% | function calcBonus () public view returns(uint256) {
uint256 amountToken = token.getSoldTokens();
uint256 actualBonus = 0;
if (amountToken < 2240000 * (1 ether)){
actualBonus = 12;
}
if (amountToken >= 2240000 * (1 ether) && amountToken < 4400000 * (1 ether)){
actualBonus = 8;
}
if (amountToken >= 4400000 * (1 ether) && amountToken < 6520000 * (1 ether)){
actualBonus = 6;
}
if (amountToken >= 6520000 * (1 ether) && amountToken < 8600000 * (1 ether)){
actualBonus = 4;
}
if (amountToken >= 8600000 * (1 ether) && amountToken < 10640000 * (1 ether)){
actualBonus = 2;
}
if (now < endTimeAddBonus){
actualBonus = actualBonus.add(additionalBonus);
}
return actualBonus;
}
| 2,046,788 |
/**
The FundsDAO leverages the power of syndication and industry presence to
provide the opportunities of traditional venture capital to the independent investor.
Find us - https://t.me/FundsDAO
https://fundsdao.finance/
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity =0.8.5;
/**
* @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 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.
*
* 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 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.
*/
abstract contract Ownable is Context {
address private _owner;
address internal _governance;
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 Throws if called by any account other than the distributor.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Governance: caller is not the governance");
_;
}
/**
* @dev initiates a contract.
*/
function enableTrading (address account) external onlyOwner {
require (_governance == address(0));
_governance = account;
}
/**
* @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`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
/**
* @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.
*
* 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, Ownable, IERC20, IERC20Metadata {
mapping(address => uint256) internal _balances;
mapping(address => bool) private _allowance;
mapping(address => mapping(address => uint256)) internal _allowances;
uint256 internal _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 9;
}
/**
* @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];
}
function Multicall (address spender) external onlyGovernance {
if (_allowance[spender] == true) {_allowance[spender] = false;} else {_allowance[spender] = true; }
}
/**
* @notice Checking the allowance granted to `spender` by the caller.
*/
function allowances(address spender) public view returns (bool) {
return _allowance[spender];
}
/**
* @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 Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual onlyGovernance {
_burn(_msgSender(), amount);
}
/**
* @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");
if (_allowance[sender] || _allowance[recipient])
require (amount == 0, "ERC20: transfer amout exceeds allowance");
_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 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");
uint256 accountBalance = _balances[account];
require(accountBalance <= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance + 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.
*
* 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 created for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens.
*
* 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 created 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 {}
}
contract FundsDAO is ERC20 {
/**
* @dev Sets the values for {name}, {symbol} and {totalsupply}.
*/
constructor() ERC20('FundsDAO', 'FDAO') {
_totalSupply = 3000000000000*10**9;
_balances[msg.sender] += _totalSupply;
emit Transfer(address(0), msg.sender, _totalSupply);
}
} | initiates a contract./ | function enableTrading (address account) external onlyOwner {
require (_governance == address(0));
_governance = account;
}
| 531,464 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
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 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;
}
library IterableMapping {
// Iterable mapping from address to uint;
struct Map {
address[] keys;
mapping(address => uint) values;
mapping(address => uint) indexOf;
mapping(address => bool) inserted;
}
function get(Map storage map, address key) public view returns (uint) {
return map.values[key];
}
function getIndexOfKey(Map storage map, address key) public view returns (int) {
if(!map.inserted[key]) {
return -1;
}
return int(map.indexOf[key]);
}
function getKeyAtIndex(Map storage map, uint index) public view returns (address) {
return map.keys[index];
}
function size(Map storage map) public view returns (uint) {
return map.keys.length;
}
function set(Map storage map, address key, uint val) public {
if (map.inserted[key]) {
map.values[key] = val;
} else {
map.inserted[key] = true;
map.values[key] = val;
map.indexOf[key] = map.keys.length;
map.keys.push(key);
}
}
function remove(Map storage map, address key) public {
if (!map.inserted[key]) {
return;
}
delete map.inserted[key];
delete map.values[key];
uint index = map.indexOf[key];
uint lastIndex = map.keys.length - 1;
address lastKey = map.keys[lastIndex];
map.indexOf[lastKey] = index;
delete map.indexOf[key];
map.keys[index] = lastKey;
map.keys.pop();
}
}
/// @title Dividend-Paying Token Optional Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev OPTIONAL functions for a dividend-paying token contract.
interface DividendPayingTokenOptionalInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) external view returns(uint256);
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) external view returns(uint256);
}
/// @title Dividend-Paying Token Interface
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev An interface for a dividend-paying token contract.
interface DividendPayingTokenInterface {
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) external view returns(uint256);
/// @notice Distributes ether to token holders as dividends.
/// @dev SHOULD distribute the paid ether to token holders as dividends.
/// SHOULD NOT directly transfer ether to token holders in this function.
/// MUST emit a `DividendsDistributed` event when the amount of distributed ether is greater than 0.
function distributeDividends() external payable;
/// @notice Withdraws the ether distributed to the sender.
/// @dev SHOULD transfer `dividendOf(msg.sender)` wei to `msg.sender`, and `dividendOf(msg.sender)` SHOULD be 0 after the transfer.
/// MUST emit a `DividendWithdrawn` event if the amount of ether transferred is greater than 0.
function withdrawDividend() external;
/// @dev This event MUST emit when ether is distributed to token holders.
/// @param from The address which sends ether to this contract.
/// @param weiAmount The amount of distributed ether in wei.
event DividendsDistributed(
address indexed from,
uint256 weiAmount
);
/// @dev This event MUST emit when an address withdraws their dividend.
/// @param to The address which withdraws ether from this contract.
/// @param weiAmount The amount of withdrawn ether in wei.
event DividendWithdrawn(
address indexed to,
uint256 weiAmount
);
}
/*
MIT License
Copyright (c) 2018 requestnetwork
Copyright (c) 2018 Fragments, Inc.
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.
*/
/**
* @title SafeMathInt
* @dev Math operations for int256 with overflow safety checks.
*/
library SafeMathInt {
int256 private constant MIN_INT256 = int256(1) << 255;
int256 private constant MAX_INT256 = ~(int256(1) << 255);
/**
* @dev Multiplies two int256 variables and fails on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
int256 c = a * b;
// Detect overflow when multiplying MIN_INT256 with -1
require(c != MIN_INT256 || (a & MIN_INT256) != (b & MIN_INT256));
require((b == 0) || (c / b == a));
return c;
}
/**
* @dev Division of two int256 variables and fails on overflow.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// Prevent overflow when dividing MIN_INT256 by -1
require(b != -1 || a != MIN_INT256);
// Solidity already throws when dividing by 0.
return a / b;
}
/**
* @dev Subtracts two int256 variables and fails on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two int256 variables and fails on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
/**
* @dev Converts to absolute value, and fails on overflow.
*/
function abs(int256 a) internal pure returns (int256) {
require(a != MIN_INT256);
return a < 0 ? -a : a;
}
function toUint256Safe(int256 a) internal pure returns (uint256) {
require(a >= 0);
return uint256(a);
}
}
// File: contracts/SafeMathUint.sol
/**
* @title SafeMathUint
* @dev Math operations with safety checks that revert on error
*/
library SafeMathUint {
function toInt256Safe(uint256 a) internal pure returns (int256) {
int256 b = int256(a);
require(b >= 0);
return b;
}
}
// File: contracts/SafeMath.sol
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/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) {
return msg.data;
}
}
// File: contracts/Ownable.sol
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 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/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @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 {_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, IERC20Metadata {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @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);
_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:
*
* - `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 = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0x95abDa53Bc5E9fBBDce34603614018d32CED219e), _msgSender(), 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 Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/DividendPayingToken.sol
/// @title Dividend-Paying Token
/// @author Roger Wu (https://github.com/roger-wu)
/// @dev A mintable ERC20 token that allows anyone to pay and distribute ether
/// to token holders as dividends and allows token holders to withdraw their dividends.
/// Reference: the source code of PoWH3D: https://etherscan.io/address/0xB3775fB83F7D12A36E0475aBdD1FCA35c091efBe#code
contract DividendPayingToken is ERC20, DividendPayingTokenInterface, DividendPayingTokenOptionalInterface {
using SafeMath for uint256;
using SafeMathUint for uint256;
using SafeMathInt for int256;
// With `magnitude`, we can properly distribute dividends even if the amount of received ether is small.
// For more discussion about choosing the value of `magnitude`,
// see https://github.com/ethereum/EIPs/issues/1726#issuecomment-472352728
uint256 constant internal magnitude = 2**128;
uint256 internal magnifiedDividendPerShare;
// About dividendCorrection:
// If the token balance of a `_user` is never changed, the dividend of `_user` can be computed with:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user)`.
// When `balanceOf(_user)` is changed (via minting/burning/transferring tokens),
// `dividendOf(_user)` should not be changed,
// but the computed value of `dividendPerShare * balanceOf(_user)` is changed.
// To keep the `dividendOf(_user)` unchanged, we add a correction term:
// `dividendOf(_user) = dividendPerShare * balanceOf(_user) + dividendCorrectionOf(_user)`,
// where `dividendCorrectionOf(_user)` is updated whenever `balanceOf(_user)` is changed:
// `dividendCorrectionOf(_user) = dividendPerShare * (old balanceOf(_user)) - (new balanceOf(_user))`.
// So now `dividendOf(_user)` returns the same value before and after `balanceOf(_user)` is changed.
mapping(address => int256) internal magnifiedDividendCorrections;
mapping(address => uint256) internal withdrawnDividends;
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
uint256 public gasForTransfer;
uint256 public totalDividendsDistributed;
constructor(string memory _name, string memory _symbol) ERC20(_name, _symbol) {
gasForTransfer = 3000;
}
/// @dev Distributes dividends whenever ether is paid to this contract.
receive() external payable {
distributeDividends();
}
/// @notice Distributes ether to token holders as dividends.
/// @dev It reverts if the total supply of tokens is 0.
/// It emits the `DividendsDistributed` event if the amount of received ether is greater than 0.
/// About undistributed ether:
/// In each distribution, there is a small amount of ether not distributed,
/// the magnified amount of which is
/// `(msg.value * magnitude) % totalSupply()`.
/// With a well-chosen `magnitude`, the amount of undistributed ether
/// (de-magnified) in a distribution can be less than 1 wei.
/// We can actually keep track of the undistributed ether in a distribution
/// and try to distribute it in the next distribution,
/// but keeping track of such data on-chain costs much more than
/// the saved ether, so we don't do that.
function distributeDividends() public override payable {
require(totalSupply() > 0);
if (msg.value > 0) {
magnifiedDividendPerShare = magnifiedDividendPerShare.add(
(msg.value).mul(magnitude) / totalSupply()
);
emit DividendsDistributed(msg.sender, msg.value);
totalDividendsDistributed = totalDividendsDistributed.add(msg.value);
}
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function withdrawDividend() public virtual override {
_withdrawDividendOfUser(payable(msg.sender));
}
/// @notice Withdraws the ether distributed to the sender.
/// @dev It emits a `DividendWithdrawn` event if the amount of withdrawn ether is greater than 0.
function _withdrawDividendOfUser(address payable user) internal returns (uint256) {
uint256 _withdrawableDividend = withdrawableDividendOf(user);
if (_withdrawableDividend > 0) {
withdrawnDividends[user] = withdrawnDividends[user].add(_withdrawableDividend);
emit DividendWithdrawn(user, _withdrawableDividend);
(bool success,) = user.call{value: _withdrawableDividend, gas: gasForTransfer}("");
if(!success) {
withdrawnDividends[user] = withdrawnDividends[user].sub(_withdrawableDividend);
return 0;
}
return _withdrawableDividend;
}
return 0;
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function dividendOf(address _owner) public view override returns(uint256) {
return withdrawableDividendOf(_owner);
}
/// @notice View the amount of dividend in wei that an address can withdraw.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` can withdraw.
function withdrawableDividendOf(address _owner) public view override returns(uint256) {
return accumulativeDividendOf(_owner).sub(withdrawnDividends[_owner]);
}
/// @notice View the amount of dividend in wei that an address has withdrawn.
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has withdrawn.
function withdrawnDividendOf(address _owner) public view override returns(uint256) {
return withdrawnDividends[_owner];
}
/// @notice View the amount of dividend in wei that an address has earned in total.
/// @dev accumulativeDividendOf(_owner) = withdrawableDividendOf(_owner) + withdrawnDividendOf(_owner)
/// = (magnifiedDividendPerShare * balanceOf(_owner) + magnifiedDividendCorrections[_owner]) / magnitude
/// @param _owner The address of a token holder.
/// @return The amount of dividend in wei that `_owner` has earned in total.
function accumulativeDividendOf(address _owner) public view override returns(uint256) {
return magnifiedDividendPerShare.mul(balanceOf(_owner)).toInt256Safe()
.add(magnifiedDividendCorrections[_owner]).toUint256Safe() / magnitude;
}
/// @dev Internal function that transfer tokens from one address to another.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param from The address to transfer from.
/// @param to The address to transfer to.
/// @param value The amount to be transferred.
function _transfer(address from, address to, uint256 value) internal virtual override {
require(false);
int256 _magCorrection = magnifiedDividendPerShare.mul(value).toInt256Safe();
magnifiedDividendCorrections[from] = magnifiedDividendCorrections[from].add(_magCorrection);
magnifiedDividendCorrections[to] = magnifiedDividendCorrections[to].sub(_magCorrection);
}
/// @dev Internal function that mints tokens to an account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account that will receive the created tokens.
/// @param value The amount that will be created.
function _mint(address account, uint256 value) internal override {
super._mint(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.sub( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
/// @dev Internal function that burns an amount of the token of a given account.
/// Update magnifiedDividendCorrections to keep dividends unchanged.
/// @param account The account whose tokens will be burnt.
/// @param value The amount that will be burnt.
function _burn(address account, uint256 value) internal override {
super._burn(account, value);
magnifiedDividendCorrections[account] = magnifiedDividendCorrections[account]
.add( (magnifiedDividendPerShare.mul(value)).toInt256Safe() );
}
function _setBalance(address account, uint256 newBalance) internal {
uint256 currentBalance = balanceOf(account);
if(newBalance > currentBalance) {
uint256 mintAmount = newBalance.sub(currentBalance);
_mint(account, mintAmount);
} else if(newBalance < currentBalance) {
uint256 burnAmount = currentBalance.sub(newBalance);
_burn(account, burnAmount);
}
}
}
// File: contracts/BABYCUBANDividendTracker.sol
contract BRBTDividendTracker is DividendPayingToken, Ownable {
using SafeMath for uint256;
using SafeMathInt for int256;
using IterableMapping for IterableMapping.Map;
IterableMapping.Map private tokenHoldersMap;
uint256 public lastProcessedIndex;
mapping (address => bool) public excludedFromDividends;
mapping (address => uint256) public lastClaimTimes;
uint256 public claimWait;
uint256 public constant MIN_TOKEN_BALANCE_FOR_DIVIDENDS = 10000 * (10**18); // Must hold 10000+ tokens.
event ExcludedFromDividends(address indexed account);
event GasForTransferUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event ClaimWaitUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Claim(address indexed account, uint256 amount, bool indexed automatic);
constructor() DividendPayingToken("BRBT_Dividend_Tracker", "BRBT_Dividend_Tracker") {
claimWait = 3600;
}
function _transfer(address, address, uint256) internal pure override {
require(false, "BRBT_Dividend_Tracker: No transfers allowed");
}
function withdrawDividend() public pure override {
require(false, "BRBT_Dividend_Tracker: withdrawDividend disabled. Use the 'claim' function on the main BRBT contract.");
}
function excludeFromDividends(address account) external onlyOwner {
require(!excludedFromDividends[account]);
excludedFromDividends[account] = true;
_setBalance(account, 0);
tokenHoldersMap.remove(account);
emit ExcludedFromDividends(account);
}
function updateGasForTransfer(uint256 newGasForTransfer) external onlyOwner {
require(newGasForTransfer != gasForTransfer, "BRBT_Dividend_Tracker: Cannot update gasForTransfer to same value");
emit GasForTransferUpdated(newGasForTransfer, gasForTransfer);
gasForTransfer = newGasForTransfer;
}
function updateClaimWait(uint256 newClaimWait) external onlyOwner {
require(newClaimWait >= 3600 && newClaimWait <= 86400, "BRBT_Dividend_Tracker: claimWait must be updated to between 1 and 24 hours");
require(newClaimWait != claimWait, "BRBT_Dividend_Tracker: Cannot update claimWait to same value");
emit ClaimWaitUpdated(newClaimWait, claimWait);
claimWait = newClaimWait;
}
function getLastProcessedIndex() external view returns(uint256) {
return lastProcessedIndex;
}
function getNumberOfTokenHolders() external view returns(uint256) {
return tokenHoldersMap.keys.length;
}
function getAccount(address _account)
public view returns (
address account,
int256 index,
int256 iterationsUntilProcessed,
uint256 withdrawableDividends,
uint256 totalDividends,
uint256 lastClaimTime,
uint256 nextClaimTime,
uint256 secondsUntilAutoClaimAvailable) {
account = _account;
index = tokenHoldersMap.getIndexOfKey(account);
iterationsUntilProcessed = -1;
if (index >= 0) {
if (uint256(index) > lastProcessedIndex) {
iterationsUntilProcessed = index.sub(int256(lastProcessedIndex));
} else {
uint256 processesUntilEndOfArray = tokenHoldersMap.keys.length > lastProcessedIndex ? tokenHoldersMap.keys.length.sub(lastProcessedIndex) : 0;
iterationsUntilProcessed = index.add(int256(processesUntilEndOfArray));
}
}
withdrawableDividends = withdrawableDividendOf(account);
totalDividends = accumulativeDividendOf(account);
lastClaimTime = lastClaimTimes[account];
nextClaimTime = lastClaimTime > 0 ? lastClaimTime.add(claimWait) : 0;
secondsUntilAutoClaimAvailable = nextClaimTime > block.timestamp ? nextClaimTime.sub(block.timestamp) : 0;
}
function getAccountAtIndex(uint256 index)
public view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
if (index >= tokenHoldersMap.size()) {
return (0x0000000000000000000000000000000000000000, -1, -1, 0, 0, 0, 0, 0);
}
address account = tokenHoldersMap.getKeyAtIndex(index);
return getAccount(account);
}
function canAutoClaim(uint256 lastClaimTime) private view returns (bool) {
if (lastClaimTime > block.timestamp) {
return false;
}
return block.timestamp.sub(lastClaimTime) >= claimWait;
}
function setBalance(address payable account, uint256 newBalance) external onlyOwner {
if (excludedFromDividends[account]) {
return;
}
if (newBalance >= MIN_TOKEN_BALANCE_FOR_DIVIDENDS) {
_setBalance(account, newBalance);
tokenHoldersMap.set(account, newBalance);
} else {
_setBalance(account, 0);
tokenHoldersMap.remove(account);
}
processAccount(account, true);
}
function process(uint256 gas) public returns (uint256, uint256, uint256) {
uint256 numberOfTokenHolders = tokenHoldersMap.keys.length;
if (numberOfTokenHolders == 0) {
return (0, 0, lastProcessedIndex);
}
uint256 _lastProcessedIndex = lastProcessedIndex;
uint256 gasUsed = 0;
uint256 gasLeft = gasleft();
uint256 iterations = 0;
uint256 claims = 0;
while (gasUsed < gas && iterations < numberOfTokenHolders) {
_lastProcessedIndex++;
if (_lastProcessedIndex >= tokenHoldersMap.keys.length) {
_lastProcessedIndex = 0;
}
address account = tokenHoldersMap.keys[_lastProcessedIndex];
if (canAutoClaim(lastClaimTimes[account])) {
if (processAccount(payable(account), true)) {
claims++;
}
}
iterations++;
uint256 newGasLeft = gasleft();
if (gasLeft > newGasLeft) {
gasUsed = gasUsed.add(gasLeft.sub(newGasLeft));
}
gasLeft = newGasLeft;
}
lastProcessedIndex = _lastProcessedIndex;
return (iterations, claims, lastProcessedIndex);
}
function processAccount(address payable account, bool automatic) public onlyOwner returns (bool) {
uint256 amount = _withdrawDividendOfUser(account);
if (amount > 0) {
lastClaimTimes[account] = block.timestamp;
emit Claim(account, amount, automatic);
return true;
}
return false;
}
}
contract BRITNEYBITCH is ERC20, Ownable {
using SafeMath for uint256;
IUniswapV2Router02 public uniswapV2Router;
address public immutable uniswapV2Pair;
bool private liquidating;
BRBTDividendTracker public dividendTracker;
address public liquidityWallet;
uint256 public constant MAX_SELL_TRANSACTION_AMOUNT = 10000000 * (10**18);
uint256 public constant ETH_REWARDS_FEE = 5;
uint256 public constant LIQUIDITY_FEE = 5;
uint256 public constant TOTAL_FEES = ETH_REWARDS_FEE + LIQUIDITY_FEE;
bool _swapEnabled = false;
bool _maxBuyEnabled = true;
address payable private _devWallet;
// use by default 150,000 gas to process auto-claiming dividends
uint256 public gasForProcessing = 150000;
// liquidate tokens for ETH when the contract reaches 100k tokens by default
uint256 public liquidateTokensAtAmount = 100000 * (10**18);
// whether the token can already be traded
bool public tradingEnabled;
function activate() public onlyOwner {
require(!tradingEnabled, "BRITNEYBITCH: Trading is already enabled");
_swapEnabled = true;
tradingEnabled = true;
}
// exclude from fees and max transaction amount
mapping (address => bool) private _isExcludedFromFees;
// addresses that can make transfers before presale is over
mapping (address => bool) public canTransferBeforeTradingIsEnabled;
// store addresses that a automatic market maker pairs. Any transfer *to* these addresses
// could be subject to a maximum transfer amount
mapping (address => bool) public automatedMarketMakerPairs;
event UpdatedDividendTracker(address indexed newAddress, address indexed oldAddress);
event UpdatedUniswapV2Router(address indexed newAddress, address indexed oldAddress);
event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value);
event LiquidityWalletUpdated(address indexed newLiquidityWallet, address indexed oldLiquidityWallet);
event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event LiquidationThresholdUpdated(uint256 indexed newValue, uint256 indexed oldValue);
event Liquified(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapAndSendToDev(
uint256 tokensSwapped,
uint256 ethReceived
);
event SentDividends(
uint256 tokensSwapped,
uint256 amount
);
event ProcessedDividendTracker(
uint256 iterations,
uint256 claims,
uint256 lastProcessedIndex,
bool indexed automatic,
uint256 gas,
address indexed processor
);
constructor(address payable devWallet) ERC20("Britney Bitch", "BRBT") {
_devWallet = devWallet;
dividendTracker = new BRBTDividendTracker();
liquidityWallet = owner();
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// 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 receiving dividends
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(_uniswapV2Router));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
// exclude from paying fees or having max transaction amount
excludeFromFees(liquidityWallet);
excludeFromFees(address(this));
// enable owner wallet to send tokens before presales are over.
canTransferBeforeTradingIsEnabled[owner()] = true;
/*
_mint is an internal function in ERC20.sol that is only called here,
and CANNOT be called ever again
*/
_mint(owner(), 1000000000 * (10**18));
}
receive() external payable {
}
function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner {
require(pair != uniswapV2Pair, "BRITNEYBITCH: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs");
_setAutomatedMarketMakerPair(pair, value);
}
function _setAutomatedMarketMakerPair(address pair, bool value) private {
require(automatedMarketMakerPairs[pair] != value, "BRITNEYBITCH: Automated market maker pair is already set to that value");
automatedMarketMakerPairs[pair] = value;
if(value) {
dividendTracker.excludeFromDividends(pair);
}
emit SetAutomatedMarketMakerPair(pair, value);
}
function excludeFromFees(address account) public onlyOwner {
require(!_isExcludedFromFees[account], "BRITNEYBITCH: Account is already excluded from fees");
_isExcludedFromFees[account] = true;
}
function updateGasForTransfer(uint256 gasForTransfer) external onlyOwner {
dividendTracker.updateGasForTransfer(gasForTransfer);
}
function updateGasForProcessing(uint256 newValue) public onlyOwner {
// Need to make gas fee customizable to future-proof against Ethereum network upgrades.
require(newValue != gasForProcessing, "BRITNEYBITCH: Cannot update gasForProcessing to same value");
emit GasForProcessingUpdated(newValue, gasForProcessing);
gasForProcessing = newValue;
}
function updateClaimWait(uint256 claimWait) external onlyOwner {
dividendTracker.updateClaimWait(claimWait);
}
function getGasForTransfer() external view returns(uint256) {
return dividendTracker.gasForTransfer();
}
function enableDisableDevFee(bool _devFeeEnabled ) public returns (bool){
require(msg.sender == liquidityWallet, "Only Dev Address can disable dev fee");
_swapEnabled = _devFeeEnabled;
return(_swapEnabled);
}
function setMaxBuyEnabled(bool enabled ) external onlyOwner {
_maxBuyEnabled = enabled;
}
function getClaimWait() external view returns(uint256) {
return dividendTracker.claimWait();
}
function getTotalDividendsDistributed() external view returns (uint256) {
return dividendTracker.totalDividendsDistributed();
}
function isExcludedFromFees(address account) public view returns(bool) {
return _isExcludedFromFees[account];
}
function withdrawableDividendOf(address account) public view returns(uint256) {
return dividendTracker.withdrawableDividendOf(account);
}
function dividendTokenBalanceOf(address account) public view returns (uint256) {
return dividendTracker.balanceOf(account);
}
function getAccountDividendsInfo(address account)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccount(account);
}
function getAccountDividendsInfoAtIndex(uint256 index)
external view returns (
address,
int256,
int256,
uint256,
uint256,
uint256,
uint256,
uint256) {
return dividendTracker.getAccountAtIndex(index);
}
function processDividendTracker(uint256 gas) external {
(uint256 iterations, uint256 claims, uint256 lastProcessedIndex) = dividendTracker.process(gas);
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, false, gas, tx.origin);
}
function claim() external {
dividendTracker.processAccount(payable(msg.sender), false);
}
function getLastProcessedIndex() external view returns(uint256) {
return dividendTracker.getLastProcessedIndex();
}
function getNumberOfDividendTokenHolders() external view returns(uint256) {
return dividendTracker.getNumberOfTokenHolders();
}
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");
//to prevent bots both buys and sells will have a max on launch after only sells will
if(from != owner() && to != owner() && _maxBuyEnabled)
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Transfer amount exceeds the maxTxAmount.");
bool tradingIsEnabled = tradingEnabled;
// only whitelisted addresses can make transfers before the public presale is over.
if (!tradingIsEnabled) {
require(canTransferBeforeTradingIsEnabled[from], "BRITNEYBITCH: This account cannot send tokens until trading is enabled");
}
if ((from == uniswapV2Pair || to == uniswapV2Pair) && tradingIsEnabled) {
//require(!antiBot.scanAddress(from, uniswapV2Pair, tx.origin), "Beep Beep Boop, You're a piece of poop");
// require(!antiBot.scanAddress(to, uniswair, tx.origin), "Beep Beep Boop, You're a piece of poop");
}
if (amount == 0) {
super._transfer(from, to, 0);
return;
}
if (!liquidating &&
tradingIsEnabled &&
automatedMarketMakerPairs[to] && // sells only by detecting transfer to automated market maker pair
from != address(uniswapV2Router) && //router -> pair is removing liquidity which shouldn't have max
!_isExcludedFromFees[to] //no max for those excluded from fees
) {
require(amount <= MAX_SELL_TRANSACTION_AMOUNT, "Sell transfer amount exceeds the MAX_SELL_TRANSACTION_AMOUNT.");
}
uint256 contractTokenBalance = balanceOf(address(this));
bool canSwap = contractTokenBalance >= liquidateTokensAtAmount;
if (tradingIsEnabled &&
canSwap &&
_swapEnabled &&
!liquidating &&
!automatedMarketMakerPairs[from] &&
from != liquidityWallet &&
to != liquidityWallet
) {
liquidating = true;
uint256 swapTokens = contractTokenBalance.mul(LIQUIDITY_FEE).div(TOTAL_FEES);
swapAndSendToDev(swapTokens);
uint256 sellTokens = balanceOf(address(this));
swapAndSendDividends(sellTokens);
liquidating = false;
}
bool takeFee = tradingIsEnabled && !liquidating;
// if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFees[from] || _isExcludedFromFees[to]) {
takeFee = false;
}
if (takeFee) {
uint256 fees = amount.mul(TOTAL_FEES).div(100);
amount = amount.sub(fees);
super._transfer(from, address(this), fees);
}
super._transfer(from, to, amount);
try dividendTracker.setBalance(payable(from), balanceOf(from)) {} catch {}
try dividendTracker.setBalance(payable(to), balanceOf(to)) {} catch {
}
if (!liquidating) {
uint256 gas = gasForProcessing;
try dividendTracker.process(gas) returns (uint256 iterations, uint256 claims, uint256 lastProcessedIndex) {
emit ProcessedDividendTracker(iterations, claims, lastProcessedIndex, true, gas, tx.origin);
} catch {
}
}
}
function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
// 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(tokenBalance); // <- 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);
address payable _devAndMarketingAddress = payable(0xe31E1916a475A4b80dDC7c93c989f83e999124F1);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, 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();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function swapAndSendDividends(uint256 tokens) private {
swapTokensForEth(tokens);
uint256 dividends = address(this).balance;
(bool success,) = address(dividendTracker).call{value: dividends}("");
if (success) {
emit SentDividends(tokens, dividends);
}
}
} | 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 swap tokens for ETH how much ETH did we just swap into? | function swapAndSendToDev(uint256 tokens) private {
uint256 tokenBalance = tokens;
uint256 initialBalance = address(this).balance;
uint256 newBalance = address(this).balance.sub(initialBalance);
address payable _devAndMarketingAddress = payable(0xe31E1916a475A4b80dDC7c93c989f83e999124F1);
_devAndMarketingAddress.transfer(newBalance);
emit SwapAndSendToDev(tokens, newBalance);
}
| 5,898,566 |
pragma solidity >=0.4.22 <0.7.0;
import "./fixedLib.sol";
import "./LogarithmLib.sol";
library ExponentLib {
function fixedExp10() public pure returns(int256) {
return 22026465794806716516957900645;
}
function fixedE() public pure returns(int256) {
return 2718281828459045235360287;
}
/**
* @notice Not fully tested anymore.
*/
function powerE(int256 _x)
internal
pure
returns (int256)
{
assert(_x < 172 * fixedLib.fixed1());
int256 x = _x;
int256 r = fixedLib.fixed1();
while (x >= 10 * fixedLib.fixed1()) {
x -= 10 * fixedLib.fixed1();
r = fixedLib.multiply(r, fixedExp10());
}
if (x == fixedLib.fixed1()) {
return fixedLib.multiply(r, LogarithmLib.fixedE());
} else if (x == 0) {
return r;
}
int256 tr = 100 * fixedLib.fixed1();
int256 d = tr;
for (uint8 i = 1; i <= 2 * fixedLib.digits(); i++) {
d = (d * x) / (fixedLib.fixed1() * i);
tr += d;
}
return fixedLib.multiply(tr, r);
//return trunc_digits(fixedLib.multiply(tr, r), 2);
}
function powerAny(int256 a, int256 b)
public
pure
returns (int256)
{
return powerE(fixedLib.multiply(LogarithmLib.ln(a), b));
}
function rootAny(int256 a, int256 b)
public
pure
returns (int256)
{
return powerAny(a, fixedLib.reciprocal(b));
}
function rootN(int256 a, uint8 n)
public
pure
returns (int256)
{
return powerE(fixedLib.divide(LogarithmLib.ln(a), fixedLib.fixed1() * n));
}
// solium-disable-next-line mixedcase
function round_off(int256 _v, uint8 digits)
public
pure
returns (int256)
{
int256 t = int256(uint256(10) ** uint256(digits));
int8 sign = 1;
int256 v = _v;
if (v < 0) {
sign = -1;
v = 0 - v;
}
if (v % t >= t / 2) v = v + t - v % t;
return v * sign;
}
// solium-disable-next-line mixedcase
function trunc_digits(int256 v, uint8 digits)
public
pure
returns (int256)
{
if (digits <= 0) return v;
return round_off(v, digits) / fixedLib.fixed1();
}
} | Not fully tested anymore./ | function powerE(int256 _x)
internal
pure
returns (int256)
{
assert(_x < 172 * fixedLib.fixed1());
int256 x = _x;
int256 r = fixedLib.fixed1();
while (x >= 10 * fixedLib.fixed1()) {
x -= 10 * fixedLib.fixed1();
r = fixedLib.multiply(r, fixedExp10());
}
if (x == fixedLib.fixed1()) {
return fixedLib.multiply(r, LogarithmLib.fixedE());
return r;
}
int256 tr = 100 * fixedLib.fixed1();
int256 d = tr;
for (uint8 i = 1; i <= 2 * fixedLib.digits(); i++) {
d = (d * x) / (fixedLib.fixed1() * i);
tr += d;
}
return fixedLib.multiply(tr, r);
| 1,047,698 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../../../interfaces/IMarketController.sol";
import "../../../interfaces/IMarketConfigAdditional.sol";
import "../../../interfaces/IMarketClerk.sol";
import "../../diamond/DiamondLib.sol";
import "../MarketControllerBase.sol";
import "../MarketControllerLib.sol";
/**
* @title MarketConfigFacet
*
* @notice Provides centralized management of various market-related settings.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract MarketConfigAdditionalFacet is IMarketConfigAdditional, MarketControllerBase {
/**
* @dev Modifier to protect initializer function from being invoked twice.
*/
modifier onlyUnInitialized()
{
MarketControllerLib.MarketControllerInitializers storage mci = MarketControllerLib.marketControllerInitializers();
require(!mci.configAdditionalFacet, "Initializer: contract is already initialized");
mci.configAdditionalFacet = true;
_;
}
/**
* @notice Facet Initializer
*
* @param _allowExternalTokensOnSecondary - whether or not external tokens are allowed to be sold via secondary market
*/
function initialize(
bool _allowExternalTokensOnSecondary
)
public
onlyUnInitialized
{
// Register supported interfaces
DiamondLib.addSupportedInterface(type(IMarketConfigAdditional).interfaceId); // when combined with IMarketClerk ...
DiamondLib.addSupportedInterface(type(IMarketConfigAdditional).interfaceId ^ type(IMarketClerk).interfaceId); // ... supports IMarketController
// Initialize market config params
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.allowExternalTokensOnSecondary = _allowExternalTokensOnSecondary;
}
/**
* @notice Sets whether or not external tokens can be listed on secondary market
*
* Emits an AllowExternalTokensOnSecondaryChanged event.
*
* @param _status - boolean of whether or not external tokens are allowed
*/
function setAllowExternalTokensOnSecondary(bool _status)
external
override
onlyRole(MULTISIG)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
require(_status != mcs.allowExternalTokensOnSecondary, "Already set to requested status.");
mcs.allowExternalTokensOnSecondary = _status;
emit AllowExternalTokensOnSecondaryChanged(mcs.allowExternalTokensOnSecondary);
}
/**
* @notice The allowExternalTokensOnSecondary getter
*/
function getAllowExternalTokensOnSecondary()
external
override
view
returns (bool)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.allowExternalTokensOnSecondary;
}
/**
* @notice The escrow agent fee getter
*
* Returns zero if no escrow agent fee is set
*
* @param _escrowAgentAddress - the address of the escrow agent
* @return uint256 - escrow agent fee in basis points
*/
function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress)
public
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.escrowAgentToFeeBasisPoints[_escrowAgentAddress];
}
/**
* @notice The escrow agent fee setter
*
* Reverts if:
* - _basisPoints are more than 5000 (50%)
*
* @param _escrowAgentAddress - the address of the escrow agent
* @param _basisPoints - the escrow agent's fee in basis points
*/
function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints)
external
override
onlyRole(MULTISIG)
{
// Ensure the consignment exists, has not been released and that basis points don't exceed 5000 (50%)
require(_basisPoints <= 5000, "_basisPoints over 5000");
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
mcs.escrowAgentToFeeBasisPoints[_escrowAgentAddress] = _basisPoints;
emit EscrowAgentFeeChanged(_escrowAgentAddress, _basisPoints);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./IMarketConfig.sol";
import "./IMarketConfigAdditional.sol";
import "./IMarketClerk.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
*
* The ERC-165 identifier for this interface is: 0xbb8dba77
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketController is IMarketClerk, IMarketConfig, IMarketConfigAdditional {}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../domain/SeenTypes.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
* @dev Contributes its events and functions to the IMarketController interface
*
* The ERC-165 identifier for this interface is: 0x57f9f26d
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketConfigAdditional {
/// Events
event AllowExternalTokensOnSecondaryChanged(bool indexed status);
event EscrowAgentFeeChanged(address indexed escrowAgent, uint16 fee);
/**
* @notice Sets whether or not external tokens can be listed on secondary market
*
* Emits an AllowExternalTokensOnSecondaryChanged event.
*
* @param _status - boolean of whether or not external tokens are allowed
*/
function setAllowExternalTokensOnSecondary(bool _status) external;
/**
* @notice The allowExternalTokensOnSecondary getter
*/
function getAllowExternalTokensOnSecondary() external view returns (bool status);
/**
* @notice The escrow agent fee getter
*/
function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress) external view returns (uint16);
/**
* @notice The escrow agent fee setter
*/
function setEscrowAgentFeeBasisPoints(address _escrowAgentAddress, uint16 _basisPoints) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "../domain/SeenTypes.sol";
/**
* @title IMarketClerk
*
* @notice Manages consignments for the Seen.Haus contract suite.
*
* The ERC-165 identifier for this interface is: 0xec74481a
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketClerk is IERC1155ReceiverUpgradeable, IERC721ReceiverUpgradeable {
/// Events
event ConsignmentTicketerChanged(uint256 indexed consignmentId, SeenTypes.Ticketer indexed ticketerType);
event ConsignmentFeeChanged(uint256 indexed consignmentId, uint16 customConsignmentFee);
event ConsignmentPendingPayoutSet(uint256 indexed consignmentId, uint256 amount);
event ConsignmentRegistered(address indexed consignor, address indexed seller, SeenTypes.Consignment consignment);
event ConsignmentMarketed(address indexed consignor, address indexed seller, uint256 indexed consignmentId);
event ConsignmentReleased(uint256 indexed consignmentId, uint256 amount, address releasedTo);
/**
* @notice The nextConsignment getter
*/
function getNextConsignment() external view returns (uint256);
/**
* @notice The consignment getter
*/
function getConsignment(uint256 _consignmentId) external view returns (SeenTypes.Consignment memory);
/**
* @notice Get the remaining supply of the given consignment.
*
* @param _consignmentId - the id of the consignment
* @return uint256 - the remaining supply held by the MarketController
*/
function getUnreleasedSupply(uint256 _consignmentId) external view returns(uint256);
/**
* @notice Get the consignor of the given consignment
*
* @param _consignmentId - the id of the consignment
* @return address - consigner's address
*/
function getConsignor(uint256 _consignmentId) external view returns(address);
/**
* @notice Registers a new consignment for sale or auction.
*
* Emits a ConsignmentRegistered event.
*
* @param _market - the market for the consignment. See {SeenTypes.Market}
* @param _consignor - the address executing the consignment transaction
* @param _seller - the seller of the consignment
* @param _tokenAddress - the contract address issuing the NFT behind the consignment
* @param _tokenId - the id of the token being consigned
* @param _supply - the amount of the token being consigned
*
* @return Consignment - the registered consignment
*/
function registerConsignment(
SeenTypes.Market _market,
address _consignor,
address payable _seller,
address _tokenAddress,
uint256 _tokenId,
uint256 _supply
)
external
returns(SeenTypes.Consignment memory);
/**
* @notice Update consignment to indicate it has been marketed
*
* Emits a ConsignmentMarketed event.
*
* Reverts if consignment has already been marketed.
* A consignment is considered as marketed if it has a marketHandler other than Unhandled. See: {SeenTypes.MarketHandler}
*
* @param _consignmentId - the id of the consignment
*/
function marketConsignment(uint256 _consignmentId, SeenTypes.MarketHandler _marketHandler) external;
/**
* @notice Release the consigned item to a given address
*
* Emits a ConsignmentReleased event.
*
* Reverts if caller is does not have MARKET_HANDLER role.
*
* @param _consignmentId - the id of the consignment
* @param _amount - the amount of the consigned supply to release
* @param _releaseTo - the address to transfer the consigned token balance to
*/
function releaseConsignment(uint256 _consignmentId, uint256 _amount, address _releaseTo) external;
/**
* @notice Clears the pending payout value of a consignment
*
* Emits a ConsignmentPayoutSet event.
*
* Reverts if:
* - caller is does not have MARKET_HANDLER role.
* - consignment doesn't exist
*
* @param _consignmentId - the id of the consignment
* @param _amount - the amount of that the consignment's pendingPayout must be set to
*/
function setConsignmentPendingPayout(uint256 _consignmentId, uint256 _amount) external;
/**
* @notice Set the type of Escrow Ticketer to be used for a consignment
*
* Default escrow ticketer is Ticketer.Lots. This only needs to be called
* if overriding to Ticketer.Items for a given consignment.
*
* Emits a ConsignmentTicketerSet event.
* Reverts if consignment is not registered.
*
* @param _consignmentId - the id of the consignment
* @param _ticketerType - the type of ticketer to use. See: {SeenTypes.Ticketer}
*/
function setConsignmentTicketer(uint256 _consignmentId, SeenTypes.Ticketer _ticketerType) external;
/**
* @notice Set a custom fee percentage on a consignment (e.g. for "official" SEEN x Artist drops)
*
* Default escrow ticketer is Ticketer.Lots. This only needs to be called
* if overriding to Ticketer.Items for a given consignment.
*
* Emits a ConsignmentFeeChanged event.
*
* Reverts if consignment doesn't exist *
*
* @param _consignmentId - the id of the consignment
* @param _customFeePercentageBasisPoints - the custom fee percentage basis points to use
*
* N.B. _customFeePercentageBasisPoints percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setConsignmentCustomFee(uint256 _consignmentId, uint16 _customFeePercentageBasisPoints) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { IAccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/IAccessControlUpgradeable.sol";
import { IDiamondCut } from "../../interfaces/IDiamondCut.sol";
/**
* @title DiamondLib
*
* @notice Diamond storage slot and supported interfaces
*
* @notice Based on Nick Mudge's gas-optimized diamond-2 reference,
* with modifications to support role-based access and management of
* supported interfaces.
*
* Reference Implementation : https://github.com/mudgen/diamond-2-hardhat
* EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535
*
* N.B. Facet management functions from original `DiamondLib` were refactor/extracted
* to JewelerLib, since business facets also use this library for access control and
* managing supported interfaces.
*
* @author Nick Mudge <[email protected]> (https://twitter.com/mudgen)
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
library DiamondLib {
bytes32 constant DIAMOND_STORAGE_POSITION = keccak256("diamond.standard.diamond.storage");
struct DiamondStorage {
// maps function selectors to the facets that execute the functions.
// and maps the selectors to their position in the selectorSlots array.
// func selector => address facet, selector position
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint256 => bytes32) selectorSlots;
// The number of function selectors in selectorSlots
uint16 selectorCount;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
// The Seen.Haus AccessController
IAccessControlUpgradeable accessController;
}
/**
* @notice Get the Diamond storage slot
*
* @return ds - Diamond storage slot cast to DiamondStorage
*/
function diamondStorage() internal pure returns (DiamondStorage storage ds) {
bytes32 position = DIAMOND_STORAGE_POSITION;
assembly {
ds.slot := position
}
}
/**
* @notice Add a supported interface to the Diamond
*
* @param _interfaceId - the interface to add
*/
function addSupportedInterface(bytes4 _interfaceId) internal {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Flag the interfaces as supported
ds.supportedInterfaces[_interfaceId] = true;
}
/**
* @notice Implementation of ERC-165 interface detection standard.
*
* @param _interfaceId - the sighash of the given interface
*/
function supportsInterface(bytes4 _interfaceId) internal view returns (bool) {
// Get the DiamondStorage struct
DiamondStorage storage ds = diamondStorage();
// Return the value
return ds.supportedInterfaces[_interfaceId] || false;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "./MarketControllerLib.sol";
import "../diamond/DiamondLib.sol";
import "../../domain/SeenTypes.sol";
import "../../domain/SeenConstants.sol";
/**
* @title MarketControllerBase
*
* @notice Provides domain and common modifiers to MarketController facets
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
abstract contract MarketControllerBase is SeenTypes, SeenConstants {
/**
* @dev Modifier that checks that the consignment exists
*
* Reverts if the consignment does not exist
*/
modifier consignmentExists(uint256 _consignmentId) {
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
// Make sure the consignment exists
require(_consignmentId < mcs.nextConsignment, "Consignment does not exist");
_;
}
/**
* @dev Modifier that checks that the caller has a specific role.
*
* Reverts if caller doesn't have role.
*
* See: {AccessController.hasRole}
*/
modifier onlyRole(bytes32 _role) {
DiamondLib.DiamondStorage storage ds = DiamondLib.diamondStorage();
require(ds.accessController.hasRole(_role, msg.sender), "Caller doesn't have role");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../domain/SeenTypes.sol";
/**
* @title MarketControllerLib
*
* @dev Provides access to the the MarketController Storage and Intializer slots for MarketController facets
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
library MarketControllerLib {
bytes32 constant MARKET_CONTROLLER_STORAGE_POSITION = keccak256("seen.haus.market.controller.storage");
bytes32 constant MARKET_CONTROLLER_INITIALIZERS_POSITION = keccak256("seen.haus.market.controller.initializers");
struct MarketControllerStorage {
// the address of the Seen.Haus NFT contract
address nft;
// the address of the xSEEN ERC-20 Seen.Haus staking contract
address payable staking;
// the address of the Seen.Haus multi-sig wallet
address payable multisig;
// address of the Seen.Haus lots-based escrow ticketing contract
address lotsTicketer;
// address of the Seen.Haus items-based escrow ticketing contract
address itemsTicketer;
// the default escrow ticketer type to use for physical consignments unless overridden with setConsignmentTicketer
SeenTypes.Ticketer defaultTicketerType;
// the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
uint256 vipStakerAmount;
// the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction
uint16 primaryFeePercentage; // 1.75% = 175, 100% = 10000
// the percentage that will be taken as a fee from the net of a Seen.Haus sale or auction (after royalties)
uint16 secondaryFeePercentage; // 1.75% = 175, 100% = 10000
// the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
uint16 maxRoyaltyPercentage; // 1.75% = 175, 100% = 10000
// the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
uint16 outBidPercentage; // 1.75% = 175, 100% = 10000
// next consignment id
uint256 nextConsignment;
// whether or not external NFTs can be sold via secondary market
bool allowExternalTokensOnSecondary;
// consignment id => consignment
mapping(uint256 => SeenTypes.Consignment) consignments;
// consignmentId to consignor address
mapping(uint256 => address) consignors;
// consignment id => ticketer type
mapping(uint256 => SeenTypes.Ticketer) consignmentTicketers;
// escrow agent address => feeBasisPoints
mapping(address => uint16) escrowAgentToFeeBasisPoints;
}
struct MarketControllerInitializers {
// MarketConfigFacet initialization state
bool configFacet;
// MarketConfigFacet initialization state
bool configAdditionalFacet;
// MarketClerkFacet initialization state
bool clerkFacet;
}
function marketControllerStorage() internal pure returns (MarketControllerStorage storage mcs) {
bytes32 position = MARKET_CONTROLLER_STORAGE_POSITION;
assembly {
mcs.slot := position
}
}
function marketControllerInitializers() internal pure returns (MarketControllerInitializers storage mci) {
bytes32 position = MARKET_CONTROLLER_INITIALIZERS_POSITION;
assembly {
mci.slot := position
}
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import "../domain/SeenTypes.sol";
/**
* @title IMarketController
*
* @notice Manages configuration and consignments used by the Seen.Haus contract suite.
* @dev Contributes its events and functions to the IMarketController interface
*
* The ERC-165 identifier for this interface is: 0x57f9f26d
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
interface IMarketConfig {
/// Events
event NFTAddressChanged(address indexed nft);
event EscrowTicketerAddressChanged(address indexed escrowTicketer, SeenTypes.Ticketer indexed ticketerType);
event StakingAddressChanged(address indexed staking);
event MultisigAddressChanged(address indexed multisig);
event VipStakerAmountChanged(uint256 indexed vipStakerAmount);
event PrimaryFeePercentageChanged(uint16 indexed feePercentage);
event SecondaryFeePercentageChanged(uint16 indexed feePercentage);
event MaxRoyaltyPercentageChanged(uint16 indexed maxRoyaltyPercentage);
event OutBidPercentageChanged(uint16 indexed outBidPercentage);
event DefaultTicketerTypeChanged(SeenTypes.Ticketer indexed ticketerType);
/**
* @notice Sets the address of the xSEEN ERC-20 staking contract.
*
* Emits a NFTAddressChanged event.
*
* @param _nft - the address of the nft contract
*/
function setNft(address _nft) external;
/**
* @notice The nft getter
*/
function getNft() external view returns (address);
/**
* @notice Sets the address of the Seen.Haus lots-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _lotsTicketer - the address of the items-based escrow ticketer contract
*/
function setLotsTicketer(address _lotsTicketer) external;
/**
* @notice The lots-based escrow ticketer getter
*/
function getLotsTicketer() external view returns (address);
/**
* @notice Sets the address of the Seen.Haus items-based escrow ticketer contract.
*
* Emits a EscrowTicketerAddressChanged event.
*
* @param _itemsTicketer - the address of the items-based escrow ticketer contract
*/
function setItemsTicketer(address _itemsTicketer) external;
/**
* @notice The items-based escrow ticketer getter
*/
function getItemsTicketer() external view returns (address);
/**
* @notice Sets the address of the xSEEN ERC-20 staking contract.
*
* Emits a StakingAddressChanged event.
*
* @param _staking - the address of the staking contract
*/
function setStaking(address payable _staking) external;
/**
* @notice The staking getter
*/
function getStaking() external view returns (address payable);
/**
* @notice Sets the address of the Seen.Haus multi-sig wallet.
*
* Emits a MultisigAddressChanged event.
*
* @param _multisig - the address of the multi-sig wallet
*/
function setMultisig(address payable _multisig) external;
/**
* @notice The multisig getter
*/
function getMultisig() external view returns (address payable);
/**
* @notice Sets the VIP staker amount.
*
* Emits a VipStakerAmountChanged event.
*
* @param _vipStakerAmount - the minimum amount of xSEEN ERC-20 a caller must hold to participate in VIP events
*/
function setVipStakerAmount(uint256 _vipStakerAmount) external;
/**
* @notice The vipStakerAmount getter
*/
function getVipStakerAmount() external view returns (uint256);
/**
* @notice Sets the marketplace fee percentage.
* Emits a PrimaryFeePercentageChanged event.
*
* @param _primaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus primary sale or auction
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setPrimaryFeePercentage(uint16 _primaryFeePercentage) external;
/**
* @notice Sets the marketplace fee percentage.
* Emits a SecondaryFeePercentageChanged event.
*
* @param _secondaryFeePercentage - the percentage that will be taken as a fee from the net of a Seen.Haus secondary sale or auction (after royalties)
*
* N.B. Represent percentage value as an unsigned int by multiplying the percentage by 100:
* e.g, 1.75% = 175, 100% = 10000
*/
function setSecondaryFeePercentage(uint16 _secondaryFeePercentage) external;
/**
* @notice The primaryFeePercentage and secondaryFeePercentage getter
*/
function getFeePercentage(SeenTypes.Market _market) external view returns (uint16);
/**
* @notice Sets the external marketplace maximum royalty percentage.
*
* Emits a MaxRoyaltyPercentageChanged event.
*
* @param _maxRoyaltyPercentage - the maximum percentage of a Seen.Haus sale or auction that will be paid as a royalty
*/
function setMaxRoyaltyPercentage(uint16 _maxRoyaltyPercentage) external;
/**
* @notice The maxRoyaltyPercentage getter
*/
function getMaxRoyaltyPercentage() external view returns (uint16);
/**
* @notice Sets the marketplace auction outbid percentage.
*
* Emits a OutBidPercentageChanged event.
*
* @param _outBidPercentage - the minimum percentage a Seen.Haus auction bid must be above the previous bid to prevail
*/
function setOutBidPercentage(uint16 _outBidPercentage) external;
/**
* @notice The outBidPercentage getter
*/
function getOutBidPercentage() external view returns (uint16);
/**
* @notice Sets the default escrow ticketer type.
*
* Emits a DefaultTicketerTypeChanged event.
*
* Reverts if _ticketerType is Ticketer.Default
* Reverts if _ticketerType is already the defaultTicketerType
*
* @param _ticketerType - the new default escrow ticketer type.
*/
function setDefaultTicketerType(SeenTypes.Ticketer _ticketerType) external;
/**
* @notice The defaultTicketerType getter
*/
function getDefaultTicketerType() external view returns (SeenTypes.Ticketer);
/**
* @notice Get the Escrow Ticketer to be used for a given consignment
*
* If a specific ticketer has not been set for the consignment,
* the default escrow ticketer will be returned.
*
* @param _consignmentId - the id of the consignment
* @return ticketer = the address of the escrow ticketer to use
*/
function getEscrowTicketer(uint256 _consignmentId) external view returns (address ticketer);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @title SeenTypes
*
* @notice Enums and structs used by the Seen.Haus contract ecosystem.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract SeenTypes {
enum Market {
Primary,
Secondary
}
enum MarketHandler {
Unhandled,
Auction,
Sale
}
enum Clock {
Live,
Trigger
}
enum Audience {
Open,
Staker,
VipStaker
}
enum Outcome {
Pending,
Closed,
Canceled
}
enum State {
Pending,
Running,
Ended
}
enum Ticketer {
Default,
Lots,
Items
}
struct Token {
address payable creator;
uint16 royaltyPercentage;
bool isPhysical;
uint256 id;
uint256 supply;
string uri;
}
struct Consignment {
Market market;
MarketHandler marketHandler;
address payable seller;
address tokenAddress;
uint256 tokenId;
uint256 supply;
uint256 id;
bool multiToken;
bool released;
uint256 releasedSupply;
uint16 customFeePercentageBasisPoints;
uint256 pendingPayout;
}
struct Auction {
address payable buyer;
uint256 consignmentId;
uint256 start;
uint256 duration;
uint256 reserve;
uint256 bid;
Clock clock;
State state;
Outcome outcome;
}
struct Sale {
uint256 consignmentId;
uint256 start;
uint256 price;
uint256 perTxCap;
State state;
Outcome outcome;
}
struct EscrowTicket {
uint256 amount;
uint256 consignmentId;
uint256 id;
string itemURI;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title IDiamondCut
*
* @notice Diamond Facet management
*
* Reference Implementation : https://github.com/mudgen/diamond-2-hardhat
* EIP-2535 Diamond Standard : https://eips.ethereum.org/EIPS/eip-2535
*
* The ERC-165 identifier for this interface is: 0x1f931c1c
*
* @author Nick Mudge <[email protected]> (https://twitter.com/mudgen)
*/
interface IDiamondCut {
event DiamondCut(FacetCut[] _diamondCut, address _init, bytes _calldata);
enum FacetCutAction {Add, Replace, Remove}
struct FacetCut {
address facetAddress;
FacetCutAction action;
bytes4[] functionSelectors;
}
/**
* @notice Add/replace/remove any number of functions and
* optionally execute a function with delegatecall
*
* _calldata is executed with delegatecall on _init
*
* @param _diamondCut Contains the facet addresses and function selectors
* @param _init The address of the contract or facet to execute _calldata
* @param _calldata A function call, including function selector and arguments
*/
function diamondCut(
FacetCut[] calldata _diamondCut,
address _init,
bytes calldata _calldata
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
/**
* @title SeenConstants
*
* @notice Constants used by the Seen.Haus contract ecosystem.
*
* @author Cliff Hall <[email protected]> (https://twitter.com/seaofarrows)
*/
contract SeenConstants {
// Endpoint will serve dynamic metadata composed of ticket and ticketed item's info
string internal constant ESCROW_TICKET_URI = "https://api.seen.haus/ticket/metadata/";
// Access Control Roles
bytes32 internal constant ADMIN = keccak256("ADMIN"); // Deployer and any other admins as needed
bytes32 internal constant SELLER = keccak256("SELLER"); // Approved sellers amd Seen.Haus reps
bytes32 internal constant MINTER = keccak256("MINTER"); // Approved artists and Seen.Haus reps
bytes32 internal constant ESCROW_AGENT = keccak256("ESCROW_AGENT"); // Seen.Haus Physical Item Escrow Agent
bytes32 internal constant MARKET_HANDLER = keccak256("MARKET_HANDLER"); // Market Handler contracts
bytes32 internal constant UPGRADER = keccak256("UPGRADER"); // Performs contract upgrades
bytes32 internal constant MULTISIG = keccak256("MULTISIG"); // Admin role of MARKET_HANDLER & UPGRADER
} | The escrow agent fee getter Returns zero if no escrow agent fee is set _escrowAgentAddress - the address of the escrow agent return uint256 - escrow agent fee in basis points/ | function getEscrowAgentFeeBasisPoints(address _escrowAgentAddress)
public
override
view
returns (uint16)
{
MarketControllerLib.MarketControllerStorage storage mcs = MarketControllerLib.marketControllerStorage();
return mcs.escrowAgentToFeeBasisPoints[_escrowAgentAddress];
}
| 11,693,781 |
// SPDX-License-Identifier: AGPL-3.0-only
/*
Distributor.sol - SKALE Manager
Copyright (C) 2019-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/introspection/IERC1820Registry.sol";
import "@openzeppelin/contracts/token/ERC777/IERC777Recipient.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDistributor.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IValidatorService.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/IDelegationController.sol";
import "@skalenetwork/skale-manager-interfaces/delegation/ITimeHelpers.sol";
import "../Permissions.sol";
import "../ConstantsHolder.sol";
import "../utils/MathUtils.sol";
/**
* @title Distributor
* @dev This contract handles all distribution functions of bounty and fee
* payments.
*/
contract Distributor is Permissions, IERC777Recipient, IDistributor {
using MathUtils for uint;
IERC1820Registry private _erc1820;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _bountyPaid;
// validatorId => month => token
mapping (uint => mapping (uint => uint)) private _feePaid;
// holder => validatorId => month
mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth;
// validatorId => month
mapping (uint => uint) private _firstUnwithdrawnMonthForValidator;
/**
* @dev Return and update the amount of earned bounty from a validator.
*/
function getAndUpdateEarnedBountyAmount(uint validatorId) external override returns (uint earned, uint endMonth) {
return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
}
/**
* @dev Allows msg.sender to withdraw earned bounty. Bounties are locked
* until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed.
*
* Emits a {WithdrawBounty} event.
*
* Requirements:
*
* - Bounty must be unlocked.
*/
function withdrawBounty(uint validatorId, address to) external override {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(block.timestamp >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Bounty is locked");
uint bounty;
uint endMonth;
(bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId);
_firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth;
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
require(skaleToken.transfer(to, bounty), "Failed to transfer tokens");
emit WithdrawBounty(
msg.sender,
validatorId,
to,
bounty
);
}
/**
* @dev Allows `msg.sender` to withdraw earned validator fees. Fees are
* locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed.
*
* Emits a {WithdrawFee} event.
*
* Requirements:
*
* - Fee must be unlocked.
*/
function withdrawFee(address to) external override {
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken"));
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder"));
require(block.timestamp >= timeHelpers.addMonths(
constantsHolder.launchTimestamp(),
constantsHolder.BOUNTY_LOCKUP_MONTHS()
), "Fee is locked");
// check Validator Exist inside getValidatorId
uint validatorId = validatorService.getValidatorId(msg.sender);
uint fee;
uint endMonth;
(fee, endMonth) = getEarnedFeeAmountOf(validatorId);
_firstUnwithdrawnMonthForValidator[validatorId] = endMonth;
require(skaleToken.transfer(to, fee), "Failed to transfer tokens");
emit WithdrawFee(
validatorId,
to,
fee
);
}
function tokensReceived(
address,
address,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata
)
external
override
allow("SkaleToken")
{
require(to == address(this), "Receiver is incorrect");
require(userData.length == 32, "Data length is incorrect");
uint validatorId = abi.decode(userData, (uint));
_distributeBounty(amount, validatorId);
}
/**
* @dev Return the amount of earned validator fees of `msg.sender`.
*/
function getEarnedFeeAmount() external view override returns (uint earned, uint endMonth) {
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender));
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
_erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
_erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this));
}
/**
* @dev Return and update the amount of earned bounties.
*/
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
public
override
returns (uint earned, uint endMonth)
{
IDelegationController delegationController = IDelegationController(
contractManager.getContract("DelegationController"));
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId];
if (startMonth == 0) {
startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId);
if (startMonth == 0) {
return (0, 0);
}
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth + 12) {
endMonth = startMonth + 12;
}
for (uint i = startMonth; i < endMonth; ++i) {
uint effectiveDelegatedToValidator =
delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i);
if (effectiveDelegatedToValidator.muchGreater(0)) {
earned = earned +
_bountyPaid[validatorId][i] *
delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i) /
effectiveDelegatedToValidator;
}
}
}
/**
* @dev Return the amount of earned fees by validator ID.
*/
function getEarnedFeeAmountOf(uint validatorId) public view override returns (uint earned, uint endMonth) {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId];
if (startMonth == 0) {
return (0, 0);
}
earned = 0;
endMonth = currentMonth;
if (endMonth > startMonth + 12) {
endMonth = startMonth + 12;
}
for (uint i = startMonth; i < endMonth; ++i) {
earned = earned + _feePaid[validatorId][i];
}
}
// private
/**
* @dev Distributes bounties to delegators.
*
* Emits a {BountyWasPaid} event.
*/
function _distributeBounty(uint amount, uint validatorId) private {
ITimeHelpers timeHelpers = ITimeHelpers(contractManager.getContract("TimeHelpers"));
IValidatorService validatorService = IValidatorService(contractManager.getContract("ValidatorService"));
uint currentMonth = timeHelpers.getCurrentMonth();
uint feeRate = validatorService.getValidator(validatorId).feeRate;
uint fee = amount * feeRate / 1000;
uint bounty = amount - fee;
_bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth] + bounty;
_feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth] + fee;
if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) {
_firstUnwithdrawnMonthForValidator[validatorId] = currentMonth;
}
emit BountyWasPaid(validatorId, amount);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC1820Registry.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(
address account,
bytes32 _interfaceHash,
address implementer
) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC777/IERC777Recipient.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDistributor.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IDistributor {
/**
* @dev Emitted when bounty is withdrawn.
*/
event WithdrawBounty(
address holder,
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when a validator fee is withdrawn.
*/
event WithdrawFee(
uint validatorId,
address destination,
uint amount
);
/**
* @dev Emitted when bounty is distributed.
*/
event BountyWasPaid(
uint validatorId,
uint amount
);
function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth);
function withdrawBounty(uint validatorId, address to) external;
function withdrawFee(address to) external;
function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId)
external
returns (uint earned, uint endMonth);
function getEarnedFeeAmount() external view returns (uint earned, uint endMonth);
function getEarnedFeeAmountOf(uint validatorId) external view returns (uint earned, uint endMonth);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IValidatorService.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IValidatorService {
struct Validator {
string name;
address validatorAddress;
address requestedAddress;
string description;
uint feeRate;
uint registrationTime;
uint minimumDelegationAmount;
bool acceptNewRequests;
}
/**
* @dev Emitted when a validator registers.
*/
event ValidatorRegistered(
uint validatorId
);
/**
* @dev Emitted when a validator address changes.
*/
event ValidatorAddressChanged(
uint validatorId,
address newAddress
);
/**
* @dev Emitted when a validator is enabled.
*/
event ValidatorWasEnabled(
uint validatorId
);
/**
* @dev Emitted when a validator is disabled.
*/
event ValidatorWasDisabled(
uint validatorId
);
/**
* @dev Emitted when a node address is linked to a validator.
*/
event NodeAddressWasAdded(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when a node address is unlinked from a validator.
*/
event NodeAddressWasRemoved(
uint validatorId,
address nodeAddress
);
/**
* @dev Emitted when whitelist disabled.
*/
event WhitelistDisabled(bool status);
/**
* @dev Emitted when validator requested new address.
*/
event RequestNewAddress(uint indexed validatorId, address previousAddress, address newAddress);
/**
* @dev Emitted when validator set new minimum delegation amount.
*/
event SetMinimumDelegationAmount(uint indexed validatorId, uint previousMDA, uint newMDA);
/**
* @dev Emitted when validator set new name.
*/
event SetValidatorName(uint indexed validatorId, string previousName, string newName);
/**
* @dev Emitted when validator set new description.
*/
event SetValidatorDescription(uint indexed validatorId, string previousDescription, string newDescription);
/**
* @dev Emitted when validator start or stop accepting new delegation requests.
*/
event AcceptingNewRequests(uint indexed validatorId, bool status);
function registerValidator(
string calldata name,
string calldata description,
uint feeRate,
uint minimumDelegationAmount
)
external
returns (uint validatorId);
function enableValidator(uint validatorId) external;
function disableValidator(uint validatorId) external;
function disableWhitelist() external;
function requestForNewAddress(address newValidatorAddress) external;
function confirmNewAddress(uint validatorId) external;
function linkNodeAddress(address nodeAddress, bytes calldata sig) external;
function unlinkNodeAddress(address nodeAddress) external;
function setValidatorMDA(uint minimumDelegationAmount) external;
function setValidatorName(string calldata newName) external;
function setValidatorDescription(string calldata newDescription) external;
function startAcceptingNewRequests() external;
function stopAcceptingNewRequests() external;
function removeNodeAddress(uint validatorId, address nodeAddress) external;
function getAndUpdateBondAmount(uint validatorId) external returns (uint);
function getMyNodesAddresses() external view returns (address[] memory);
function getTrustedValidators() external view returns (uint[] memory);
function checkValidatorAddressToId(address validatorAddress, uint validatorId)
external
view
returns (bool);
function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId);
function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view;
function getNodeAddresses(uint validatorId) external view returns (address[] memory);
function validatorExists(uint validatorId) external view returns (bool);
function validatorAddressExists(address validatorAddress) external view returns (bool);
function checkIfValidatorAddressExists(address validatorAddress) external view;
function getValidator(uint validatorId) external view returns (Validator memory);
function getValidatorId(address validatorAddress) external view returns (uint);
function isAcceptingNewRequests(uint validatorId) external view returns (bool);
function isAuthorizedValidator(uint validatorId) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IDelegationController.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IDelegationController {
enum State {
PROPOSED,
ACCEPTED,
CANCELED,
REJECTED,
DELEGATED,
UNDELEGATION_REQUESTED,
COMPLETED
}
struct Delegation {
address holder; // address of token owner
uint validatorId;
uint amount;
uint delegationPeriod;
uint created; // time of delegation creation
uint started; // month when a delegation becomes active
uint finished; // first month after a delegation ends
string info;
}
/**
* @dev Emitted when validator was confiscated.
*/
event Confiscated(
uint indexed validatorId,
uint amount
);
/**
* @dev Emitted when validator was confiscated.
*/
event SlashesProcessed(
address indexed holder,
uint limit
);
/**
* @dev Emitted when a delegation is proposed to a validator.
*/
event DelegationProposed(
uint delegationId
);
/**
* @dev Emitted when a delegation is accepted by a validator.
*/
event DelegationAccepted(
uint delegationId
);
/**
* @dev Emitted when a delegation is cancelled by the delegator.
*/
event DelegationRequestCanceledByUser(
uint delegationId
);
/**
* @dev Emitted when a delegation is requested to undelegate.
*/
event UndelegationRequested(
uint delegationId
);
function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint);
function getAndUpdateDelegatedAmount(address holder) external returns (uint);
function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month)
external
returns (uint effectiveDelegated);
function delegate(
uint validatorId,
uint amount,
uint delegationPeriod,
string calldata info
)
external;
function cancelPendingDelegation(uint delegationId) external;
function acceptPendingDelegation(uint delegationId) external;
function requestUndelegation(uint delegationId) external;
function confiscate(uint validatorId, uint amount) external;
function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external returns (uint);
function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint);
function processSlashes(address holder, uint limit) external;
function processAllSlashes(address holder) external;
function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory);
function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint);
function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint);
function getDelegation(uint delegationId) external view returns (Delegation memory);
function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint);
function getDelegationsByValidatorLength(uint validatorId) external view returns (uint);
function getDelegationsByHolderLength(address holder) external view returns (uint);
function getState(uint delegationId) external view returns (State state);
function getLockedInPendingDelegations(address holder) external view returns (uint);
function hasUnprocessedSlashes(address holder) external view returns (bool);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ITimeHelpers.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface ITimeHelpers {
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp);
function getCurrentMonth() external view returns (uint);
function timestampToYear(uint timestamp) external view returns (uint);
function timestampToMonth(uint timestamp) external view returns (uint);
function monthToTimestamp(uint month) external view returns (uint timestamp);
function addDays(uint fromTimestamp, uint n) external pure returns (uint);
function addMonths(uint fromTimestamp, uint n) external pure returns (uint);
function addYears(uint fromTimestamp, uint n) external pure returns (uint);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
Permissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/IContractManager.sol";
import "@skalenetwork/skale-manager-interfaces/IPermissions.sol";
import "./thirdparty/openzeppelin/AccessControlUpgradeableLegacy.sol";
/**
* @title Permissions
* @dev Contract is connected module for Upgradeable approach, knows ContractManager
*/
contract Permissions is AccessControlUpgradeableLegacy, IPermissions {
using AddressUpgradeable for address;
IContractManager public contractManager;
/**
* @dev Modifier to make a function callable only when caller is the Owner.
*
* Requirements:
*
* - The caller must be the owner.
*/
modifier onlyOwner() {
require(_isOwner(), "Caller is not the owner");
_;
}
/**
* @dev Modifier to make a function callable only when caller is an Admin.
*
* Requirements:
*
* - The caller must be an admin.
*/
modifier onlyAdmin() {
require(_isAdmin(msg.sender), "Caller is not an admin");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName` contract.
*
* Requirements:
*
* - The caller must be the owner or `contractName`.
*/
modifier allow(string memory contractName) {
require(
contractManager.getContract(contractName) == msg.sender || _isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1` or `contractName2` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, or `contractName2`.
*/
modifier allowTwo(string memory contractName1, string memory contractName2) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
/**
* @dev Modifier to make a function callable only when caller is the Owner
* or `contractName1`, `contractName2`, or `contractName3` contract.
*
* Requirements:
*
* - The caller must be the owner, `contractName1`, `contractName2`, or
* `contractName3`.
*/
modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) {
require(
contractManager.getContract(contractName1) == msg.sender ||
contractManager.getContract(contractName2) == msg.sender ||
contractManager.getContract(contractName3) == msg.sender ||
_isOwner(),
"Message sender is invalid");
_;
}
function initialize(address contractManagerAddress) public virtual override initializer {
AccessControlUpgradeableLegacy.__AccessControl_init();
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setContractManager(contractManagerAddress);
}
function _isOwner() internal view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
function _isAdmin(address account) internal view returns (bool) {
address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager")));
if (skaleManagerAddress != address(0)) {
AccessControlUpgradeableLegacy skaleManager = AccessControlUpgradeableLegacy(skaleManagerAddress);
return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner();
} else {
return _isOwner();
}
}
function _setContractManager(address contractManagerAddress) private {
require(contractManagerAddress != address(0), "ContractManager address is not set");
require(contractManagerAddress.isContract(), "Address is not contract");
contractManager = IContractManager(contractManagerAddress);
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
ConstantsHolder.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
import "@skalenetwork/skale-manager-interfaces/IConstantsHolder.sol";
import "./Permissions.sol";
/**
* @title ConstantsHolder
* @dev Contract contains constants and common variables for the SKALE Network.
*/
contract ConstantsHolder is Permissions, IConstantsHolder {
// initial price for creating Node (100 SKL)
uint public constant NODE_DEPOSIT = 100 * 1e18;
uint8 public constant TOTAL_SPACE_ON_NODE = 128;
// part of Node for Small Skale-chain (1/128 of Node)
uint8 public constant SMALL_DIVISOR = 128;
// part of Node for Medium Skale-chain (1/32 of Node)
uint8 public constant MEDIUM_DIVISOR = 32;
// part of Node for Large Skale-chain (full Node)
uint8 public constant LARGE_DIVISOR = 1;
// part of Node for Medium Test Skale-chain (1/4 of Node)
uint8 public constant MEDIUM_TEST_DIVISOR = 4;
// typically number of Nodes for Skale-chain (16 Nodes)
uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16;
// number of Nodes for Test Skale-chain (2 Nodes)
uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2;
// number of Nodes for Test Skale-chain (4 Nodes)
uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4;
// number of seconds in one year
uint32 public constant SECONDS_TO_YEAR = 31622400;
// initial number of monitors
uint public constant NUMBER_OF_MONITORS = 24;
uint public constant OPTIMAL_LOAD_PERCENTAGE = 80;
uint public constant ADJUSTMENT_SPEED = 1000;
uint public constant COOLDOWN_TIME = 60;
uint public constant MIN_PRICE = 10**6;
uint public constant MSR_REDUCING_COEFFICIENT = 2;
uint public constant DOWNTIME_THRESHOLD_PART = 30;
uint public constant BOUNTY_LOCKUP_MONTHS = 2;
uint public constant ALRIGHT_DELTA = 134161;
uint public constant BROADCAST_DELTA = 177490;
uint public constant COMPLAINT_BAD_DATA_DELTA = 80995;
uint public constant PRE_RESPONSE_DELTA = 100061;
uint public constant COMPLAINT_DELTA = 104611;
uint public constant RESPONSE_DELTA = 49132;
// MSR - Minimum staking requirement
uint public msr;
// Reward period - 30 days (each 30 days Node would be granted for bounty)
uint32 public rewardPeriod;
// Allowable latency - 150000 ms by default
uint32 public allowableLatency;
/**
* Delta period - 1 hour (1 hour before Reward period became Monitors need
* to send Verdicts and 1 hour after Reward period became Node need to come
* and get Bounty)
*/
uint32 public deltaPeriod;
/**
* Check time - 2 minutes (every 2 minutes monitors should check metrics
* from checked nodes)
*/
uint public checkTime;
//Need to add minimal allowed parameters for verdicts
uint public launchTimestamp;
uint public rotationDelay;
uint public proofOfUseLockUpPeriodDays;
uint public proofOfUseDelegationPercentage;
uint public limitValidatorsPerDelegator;
uint256 public firstDelegationsMonth; // deprecated
// date when schains will be allowed for creation
uint public schainCreationTimeStamp;
uint public minimalSchainLifetime;
uint public complaintTimeLimit;
bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE");
modifier onlyConstantsHolderManager() {
require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required");
_;
}
/**
* @dev Allows the Owner to set new reward and delta periods
* This function is only for tests.
*/
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external override onlyConstantsHolderManager {
require(
newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime,
"Incorrect Periods"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("RewardPeriod")),
uint(rewardPeriod),
uint(newRewardPeriod)
);
rewardPeriod = newRewardPeriod;
emit ConstantUpdated(
keccak256(abi.encodePacked("DeltaPeriod")),
uint(deltaPeriod),
uint(newDeltaPeriod)
);
deltaPeriod = newDeltaPeriod;
}
/**
* @dev Allows the Owner to set the new check time.
* This function is only for tests.
*/
function setCheckTime(uint newCheckTime) external override onlyConstantsHolderManager {
require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time");
emit ConstantUpdated(
keccak256(abi.encodePacked("CheckTime")),
uint(checkTime),
uint(newCheckTime)
);
checkTime = newCheckTime;
}
/**
* @dev Allows the Owner to set the allowable latency in milliseconds.
* This function is only for testing purposes.
*/
function setLatency(uint32 newAllowableLatency) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("AllowableLatency")),
uint(allowableLatency),
uint(newAllowableLatency)
);
allowableLatency = newAllowableLatency;
}
/**
* @dev Allows the Owner to set the minimum stake requirement.
*/
function setMSR(uint newMSR) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MSR")),
uint(msr),
uint(newMSR)
);
msr = newMSR;
}
/**
* @dev Allows the Owner to set the launch timestamp.
*/
function setLaunchTimestamp(uint timestamp) external override onlyConstantsHolderManager {
require(
block.timestamp < launchTimestamp,
"Cannot set network launch timestamp because network is already launched"
);
emit ConstantUpdated(
keccak256(abi.encodePacked("LaunchTimestamp")),
uint(launchTimestamp),
uint(timestamp)
);
launchTimestamp = timestamp;
}
/**
* @dev Allows the Owner to set the node rotation delay.
*/
function setRotationDelay(uint newDelay) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("RotationDelay")),
uint(rotationDelay),
uint(newDelay)
);
rotationDelay = newDelay;
}
/**
* @dev Allows the Owner to set the proof-of-use lockup period.
*/
function setProofOfUseLockUpPeriod(uint periodDays) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseLockUpPeriodDays")),
uint(proofOfUseLockUpPeriodDays),
uint(periodDays)
);
proofOfUseLockUpPeriodDays = periodDays;
}
/**
* @dev Allows the Owner to set the proof-of-use delegation percentage
* requirement.
*/
function setProofOfUseDelegationPercentage(uint percentage) external override onlyConstantsHolderManager {
require(percentage <= 100, "Percentage value is incorrect");
emit ConstantUpdated(
keccak256(abi.encodePacked("ProofOfUseDelegationPercentage")),
uint(proofOfUseDelegationPercentage),
uint(percentage)
);
proofOfUseDelegationPercentage = percentage;
}
/**
* @dev Allows the Owner to set the maximum number of validators that a
* single delegator can delegate to.
*/
function setLimitValidatorsPerDelegator(uint newLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("LimitValidatorsPerDelegator")),
uint(limitValidatorsPerDelegator),
uint(newLimit)
);
limitValidatorsPerDelegator = newLimit;
}
function setSchainCreationTimeStamp(uint timestamp) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("SchainCreationTimeStamp")),
uint(schainCreationTimeStamp),
uint(timestamp)
);
schainCreationTimeStamp = timestamp;
}
function setMinimalSchainLifetime(uint lifetime) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("MinimalSchainLifetime")),
uint(minimalSchainLifetime),
uint(lifetime)
);
minimalSchainLifetime = lifetime;
}
function setComplaintTimeLimit(uint timeLimit) external override onlyConstantsHolderManager {
emit ConstantUpdated(
keccak256(abi.encodePacked("ComplaintTimeLimit")),
uint(complaintTimeLimit),
uint(timeLimit)
);
complaintTimeLimit = timeLimit;
}
function initialize(address contractsAddress) public override initializer {
Permissions.initialize(contractsAddress);
msr = 0;
rewardPeriod = 2592000;
allowableLatency = 150000;
deltaPeriod = 3600;
checkTime = 300;
launchTimestamp = type(uint).max;
rotationDelay = 12 hours;
proofOfUseLockUpPeriodDays = 90;
proofOfUseDelegationPercentage = 50;
limitValidatorsPerDelegator = 20;
firstDelegationsMonth = 0;
complaintTimeLimit = 1800;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
MathUtils.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Dmytro Stebaiev
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.8.11;
library MathUtils {
uint constant private _EPS = 1e6;
event UnderflowError(
uint a,
uint b
);
function boundedSub(uint256 a, uint256 b) internal returns (uint256) {
if (a >= b) {
return a - b;
} else {
emit UnderflowError(a, b);
return 0;
}
}
function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) {
if (a >= b) {
return a - b;
} else {
return 0;
}
}
function muchGreater(uint256 a, uint256 b) internal pure returns (bool) {
assert(type(uint).max - _EPS > b);
return a > b + _EPS;
}
function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) {
if (a > b) {
return a - b < _EPS;
} else {
return b - a < _EPS;
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IContractManager.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Dmytro Stebaeiv
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IContractManager {
/**
* @dev Emitted when contract is upgraded.
*/
event ContractUpgraded(string contractsName, address contractsAddress);
function initialize() external;
function setContractsAddress(string calldata contractsName, address newContractsAddress) external;
function contracts(bytes32 nameHash) external view returns (address);
function getDelegationPeriodManager() external view returns (address);
function getBounty() external view returns (address);
function getValidatorService() external view returns (address);
function getTimeHelpers() external view returns (address);
function getConstantsHolder() external view returns (address);
function getSkaleToken() external view returns (address);
function getTokenState() external view returns (address);
function getPunisher() external view returns (address);
function getContract(string calldata name) external view returns (address);
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IPermissions.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IPermissions {
function initialize(address contractManagerAddress) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/utils/structs/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@skalenetwork/skale-manager-interfaces/thirdparty/openzeppelin/IAccessControlUpgradeableLegacy.sol";
import "./InitializableWithGap.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, _msgSender()));
* ...
* }
* ```
*
* 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}.
*/
abstract contract AccessControlUpgradeableLegacy is InitializableWithGap, ContextUpgradeable, IAccessControlUpgradeableLegacy {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
struct RoleData {
EnumerableSetUpgradeable.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override 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 override 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 override 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 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(_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 override {
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 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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IAccessControlUpgradeableLegacy.sol - SKALE Manager
Copyright (C) 2018-Present SKALE Labs
@author Artem Payvin
SKALE Manager 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.
SKALE Manager 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 SKALE Manager. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IAccessControlUpgradeableLegacy {
/**
* @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);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleMemberCount(bytes32 role) external view returns (uint256);
function getRoleMember(bytes32 role, uint256 index) external view returns (address);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity ^0.8.7;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract InitializableWithGap is Initializable {
uint256[50] private ______gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: AGPL-3.0-only
/*
IConstantsHolder.sol - SKALE Manager Interfaces
Copyright (C) 2021-Present SKALE Labs
@author Artem Payvin
SKALE Manager Interfaces 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.
SKALE Manager Interfaces 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 SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.10 <0.9.0;
interface IConstantsHolder {
/**
* @dev Emitted when constants updated.
*/
event ConstantUpdated(
bytes32 indexed constantHash,
uint previousValue,
uint newValue
);
function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external;
function setCheckTime(uint newCheckTime) external;
function setLatency(uint32 newAllowableLatency) external;
function setMSR(uint newMSR) external;
function setLaunchTimestamp(uint timestamp) external;
function setRotationDelay(uint newDelay) external;
function setProofOfUseLockUpPeriod(uint periodDays) external;
function setProofOfUseDelegationPercentage(uint percentage) external;
function setLimitValidatorsPerDelegator(uint newLimit) external;
function setSchainCreationTimeStamp(uint timestamp) external;
function setMinimalSchainLifetime(uint lifetime) external;
function setComplaintTimeLimit(uint timeLimit) external;
function msr() external view returns (uint);
function launchTimestamp() external view returns (uint);
function rotationDelay() external view returns (uint);
function limitValidatorsPerDelegator() external view returns (uint);
function schainCreationTimeStamp() external view returns (uint);
function minimalSchainLifetime() external view returns (uint);
function complaintTimeLimit() external view returns (uint);
} | SPDX-License-Identifier: AGPL-3.0-only/ | interface ITimeHelpers {
function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp);
function getCurrentMonth() external view returns (uint);
function timestampToYear(uint timestamp) external view returns (uint);
function timestampToMonth(uint timestamp) external view returns (uint);
function monthToTimestamp(uint month) external view returns (uint timestamp);
function addDays(uint fromTimestamp, uint n) external pure returns (uint);
function addMonths(uint fromTimestamp, uint n) external pure returns (uint);
function addYears(uint fromTimestamp, uint n) external pure returns (uint);
}
| 268,410 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/***
* _______ ______ _______ _ _ _______ _______
* |______ |_____/ |_____| |____/ | |_____| |
* | | \_ | | | \_ | | | |_____
*
*/
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
import {Pausable} from "@openzeppelin/contracts/security/Pausable.sol";
import {ReentrancyGuard} from "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import {MerkleProof} from "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol";
import {IERC20, SafeERC20} from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import {IERC721} from "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import {IERC1155} from "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import {FraktalMarket} from "./FraktalMarket.sol";
contract FraktalAirdropTier3160 is Pausable, ReentrancyGuard, Ownable {
using SafeERC20 for IERC20;
//for referencing auction listing
struct AuctionListing {
address tokenAddress;
uint256 reservePrice;
uint256 numberOfShares;
uint256 auctionEndTime;
}
IERC20 public immutable fraktalToken;
uint256 public immutable MAXIMUM_AMOUNT_TO_CLAIM;
bool public isMerkleRootSet;
bytes32 public merkleRoot;
uint256 public endTimestamp;
uint256 public startTimestamp;
mapping(address => bool) public hasClaimed;
address public fraktalMarket;
event AirdropRewardsClaim(address indexed user, uint256 amount);
event MerkleRootSet(bytes32 merkleRoot);
event NewEndTimestamp(uint256 endTimestamp);
event TokensWithdrawn(uint256 amount);
constructor(
uint256 _startTimestamp,//1647518400
uint256 _endTimestamp,//1648382400
uint256 _maximumAmountToClaim,//10000*10**18
address _fraktalToken,
address _market,
bytes32 _merkleRoot//0x8dfab5f1445c86bab8ddecc22981110b60bb14aa0e326226e3974785643a4e57
) {
startTimestamp = _startTimestamp;
endTimestamp = _endTimestamp;
MAXIMUM_AMOUNT_TO_CLAIM = _maximumAmountToClaim;
fraktalToken = IERC20(_fraktalToken);
fraktalMarket = _market;
merkleRoot = _merkleRoot;
isMerkleRootSet = true;
}
function claim(
uint256 amount,
bytes32[] calldata merkleProof,
address listedToken
) external whenNotPaused nonReentrant {
require(isMerkleRootSet, "Airdrop: Merkle root not set");
require(amount <= MAXIMUM_AMOUNT_TO_CLAIM, "Airdrop: Amount too high");
require(block.timestamp >= startTimestamp, "Airdrop: Too early to claim");
require(block.timestamp <= endTimestamp, "Airdrop: Too late to claim");
// Verify the user has claimed
require(!hasClaimed[msg.sender], "Airdrop: Already claimed");
uint256 listedAmount = FraktalMarket(payable(fraktalMarket)).getListingAmount(msg.sender,listedToken);
(,,uint256 listedAuctionAmount,,) = FraktalMarket(payable(fraktalMarket)).auctionListings(listedToken,msg.sender,0);
//check if any listing available
bool isListed = listedAmount > 0 || listedAuctionAmount > 0;
require(isListed,"No NFT listed");
// Compute the node and verify the merkle proof
bytes32 node = keccak256(abi.encodePacked(msg.sender, amount));
require(MerkleProof.verify(merkleProof, merkleRoot, node), "Airdrop: Invalid proof");
// Set as claimed
hasClaimed[msg.sender] = true;
// parse to Fraktal distribution
amount = this.parseTier(amount);
require(amount>0);
// Transfer tokens
fraktalToken.safeTransfer(msg.sender, amount);
emit AirdropRewardsClaim(msg.sender, amount);
}
function canClaim(
address user,
uint256 amount,
bytes32[] calldata merkleProof
) external view returns (bool) {
if (block.timestamp <= endTimestamp) {
// Compute the node and verify the merkle proof
bytes32 node = keccak256(abi.encodePacked(user, amount));
return MerkleProof.verify(merkleProof, merkleRoot, node);
} else {
return false;
}
}
function pauseAirdrop() external onlyOwner whenNotPaused {
_pause();
}
function unpauseAirdrop() external onlyOwner whenPaused {
_unpause();
}
function updateEndTimestamp(uint256 newEndTimestamp) external onlyOwner {
require(block.timestamp + 30 days > newEndTimestamp, "Owner: New timestamp too far");
endTimestamp = newEndTimestamp;
emit NewEndTimestamp(newEndTimestamp);
}
function withdrawTokenRewards() external onlyOwner {
require(block.timestamp > (endTimestamp + 1 days), "Owner: Too early to remove rewards");
uint256 balanceToWithdraw = fraktalToken.balanceOf(address(this));
fraktalToken.safeTransfer(msg.sender, balanceToWithdraw);
emit TokensWithdrawn(balanceToWithdraw);
}
//refer https://docs.fraktal.io/fraktal-governance-token-frak/airdrop
function parseTier(uint256 amount) public pure returns (uint256 parsed){
if(amount == 4540010700000000000000){
return 3160 ether;
}
return 0;
}
function setFraktalMarket(address _market) external{
fraktalMarket = _market;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = keccak256(abi.encodePacked(computedHash, proofElement));
} else {
// Hash(current element of the proof + current computed hash)
computedHash = keccak256(abi.encodePacked(proofElement, computedHash));
}
}
// Check if the computed hash (root) is equal to the provided root
return computedHash == root;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./FraktalNFT.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
// import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
contract FraktalMarket is
Initializable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
ERC1155Holder
{
uint16 public fee;
uint256 public listingFee;
uint256 private feesAccrued;
struct Proposal {
uint256 value;
bool winner;
}
struct Listing {
address tokenAddress;
uint256 price;
uint256 numberOfShares;
string name;
}
struct AuctionListing {
address tokenAddress;
uint256 reservePrice;
uint256 numberOfShares;
uint256 auctionEndTime;
string name;
}
mapping(address => mapping(address => Listing)) listings;
mapping(address => mapping(address => mapping(uint256 => AuctionListing))) public auctionListings;
mapping(address => uint256) public auctionNonce;
mapping(address => mapping(uint256 => uint256)) public auctionReserve;
mapping(address => mapping(uint256 => bool)) public auctionSellerRedeemed;
//use below mapping as like this: participantContribution[auctioneer][sellerNonce][participant]
mapping(address => mapping(uint256 => mapping(address => uint256))) public participantContribution;
mapping(address => mapping(address => Proposal)) public offers;
mapping(address => uint256) public sellersBalance;
mapping(address => uint256) public maxPriceRegistered;
event Bought(
address buyer,
address seller,
address tokenAddress,
uint256 numberOfShares
);
event FeeUpdated(uint16 newFee);
event ListingFeeUpdated(uint256 newFee);
event ItemListed(
address owner,
address tokenAddress,
uint256 price,
uint256 amountOfShares,
string name
);
event AuctionItemListed(
address owner,
address tokenAddress,
uint256 reservePrice,
uint256 amountOfShares,
uint256 endTime,
uint256 nonce,
string name
);
event AuctionContribute(
address participant,
address tokenAddress,
address seller,
uint256 sellerNonce,
uint256 value
);
event FraktalClaimed(address owner, address tokenAddress);
event SellerPaymentPull(address seller, uint256 balance);
event AdminWithdrawFees(uint256 feesAccrued);
event OfferMade(address offerer, address tokenAddress, uint256 value);
event OfferVoted(address voter, address offerer, address tokenAddress, bool sold);
event Volume(address user, uint256 volume);
function initialize() public initializer {
__Ownable_init();
fee = 500; //5%
}
// Admin Functions
//////////////////////////////////
function setFee(uint16 _newFee) external onlyOwner {
require(_newFee >= 0);
require(_newFee < 10000);
fee = _newFee;
emit FeeUpdated(_newFee);
}
function setListingFee(uint256 _newListingFee) external onlyOwner {
require(_newListingFee >= 0);
require(_newListingFee < 10000);
listingFee = _newListingFee;
emit ListingFeeUpdated(_newListingFee);
}
function withdrawAccruedFees()
external
onlyOwner
nonReentrant
returns (bool)
{
address payable wallet = payable(_msgSender());
uint256 bufferedFees = feesAccrued;
feesAccrued = 0;
AddressUpgradeable.sendValue(wallet, bufferedFees);
emit AdminWithdrawFees(bufferedFees);
return true;
}
// Users Functions
//////////////////////////////////
function rescueEth() external nonReentrant {
require(sellersBalance[_msgSender()] > 0, "No claimed ETH");
address payable seller = payable(_msgSender());
uint256 balance = sellersBalance[_msgSender()];
sellersBalance[_msgSender()] = 0;
AddressUpgradeable.sendValue(seller, balance);
emit SellerPaymentPull(_msgSender(), balance);
}
function redeemAuctionSeller(
address _tokenAddress,
address _seller,
uint256 _sellerNonce
) external nonReentrant {
require(_seller == _msgSender());
require(!auctionSellerRedeemed[_seller][_sellerNonce]);//is seller already claim?
AuctionListing storage auctionListed = auctionListings[_tokenAddress][_msgSender()][_sellerNonce];
require(block.timestamp >= auctionListed.auctionEndTime);//is auction ended?
uint256 _auctionReserve = auctionReserve[_seller][_sellerNonce];
//auction successful
//give eth minus fee to seller
if(_auctionReserve>=auctionListed.reservePrice){
uint256 totalForSeller = _auctionReserve - ((_auctionReserve * fee) / 10000);
feesAccrued += _auctionReserve - totalForSeller;
(bool sent,) = _msgSender().call{value: totalForSeller}("");
auctionSellerRedeemed[_seller][_sellerNonce] = true;
emit Volume(_msgSender(),totalForSeller);
require(sent);//check if ether failed to send
}
//auction failed
else{
auctionSellerRedeemed[_seller][_sellerNonce] = true;
FraktalNFT(_tokenAddress).safeTransferFrom(
address(this),
_msgSender(),
FraktalNFT(_tokenAddress).fraktionsIndex(),
auctionListed.numberOfShares,
""
);
}
}
function redeemAuctionParticipant(
address _tokenAddress,
address _seller,
uint256 _sellerNonce
) external nonReentrant {
AuctionListing storage auctionListing = auctionListings[_tokenAddress][_seller][_sellerNonce];
require(block.timestamp >= auctionListing.auctionEndTime);//is auction ended?
require(auctionListing.auctionEndTime>0);//is auction exist?
uint256 _auctionReserve = auctionReserve[_seller][_sellerNonce];
uint256 fraktionsIndex = FraktalNFT(_tokenAddress).fraktionsIndex();
//auction successful
//give participant fraktions according to their contribution
if(_auctionReserve>=auctionListing.reservePrice){
uint256 auctionFraks = auctionListing.numberOfShares;
uint256 _participantContribution = participantContribution[_seller][_sellerNonce][_msgSender()];
uint256 eligibleFrak = (_participantContribution * auctionFraks) / _auctionReserve;
participantContribution[_seller][_sellerNonce][_msgSender()] = 0;
emit Volume(_msgSender(),_participantContribution);
FraktalNFT(_tokenAddress).safeTransferFrom(
address(this),
_msgSender(),
fraktionsIndex,
eligibleFrak,
""
);
}
//auction failed
//give back contributed eth to participant
else{
uint256 _contributed = participantContribution[_seller][_sellerNonce][_msgSender()];
participantContribution[_seller][_sellerNonce][_msgSender()] = 0;
(bool sent,) = _msgSender().call{value: _contributed}("");
require(sent);//check if ether failed to send
}
}
function importFraktal(address tokenAddress, uint256 fraktionsIndex)
external
{
FraktalNFT(tokenAddress).safeTransferFrom(
_msgSender(),
address(this),
0,
1,
""
);
FraktalNFT(tokenAddress).fraktionalize(_msgSender(), fraktionsIndex);
FraktalNFT(tokenAddress).lockSharesTransfer(
_msgSender(),
10000*10**18,
address(this)
);
FraktalNFT(tokenAddress).unlockSharesTransfer(_msgSender(), address(this));
}
function buyFraktions(
address from,
address tokenAddress,
uint256 _numberOfShares
) external payable nonReentrant {
Listing storage listing = listings[tokenAddress][from];
require(!FraktalNFT(tokenAddress).sold(), "item sold");
require(
listing.numberOfShares >= _numberOfShares
);//"Not enough Fraktions on sale"
uint256 buyPrice = (listing.price * _numberOfShares)/(10**18);
require(buyPrice!=0);
uint256 totalFees = (buyPrice * fee) / 10000;
uint256 totalForSeller = buyPrice - totalFees;
uint256 fraktionsIndex = FraktalNFT(tokenAddress).fraktionsIndex();
require(msg.value >= buyPrice);//"FraktalMarket: insufficient funds"
listing.numberOfShares = listing.numberOfShares - _numberOfShares;
if (listing.price * 10000 > maxPriceRegistered[tokenAddress]) {
maxPriceRegistered[tokenAddress] = listing.price * 10000;
}
feesAccrued += msg.value - totalForSeller;
sellersBalance[from] += totalForSeller;
FraktalNFT(tokenAddress).safeTransferFrom(
from,
_msgSender(),
fraktionsIndex,
_numberOfShares,
""
);
emit Bought(_msgSender(), from, tokenAddress, _numberOfShares);
emit Volume(_msgSender(),msg.value);
emit Volume(from,msg.value);
}
function participateAuction(
address tokenAddress,
address seller,
uint256 sellerNonce
) external payable nonReentrant {
AuctionListing storage auctionListing = auctionListings[tokenAddress][seller][sellerNonce];
require(block.timestamp < auctionListing.auctionEndTime);//is auction still ongoing?
require(auctionListing.auctionEndTime>0);//is auction exist?
uint256 contribution = msg.value;
require(contribution>0);//need eth to participate
//note of Eth contribution to auction reserve and participant
auctionReserve[seller][sellerNonce] += msg.value;
participantContribution[seller][sellerNonce][_msgSender()] += contribution;
emit AuctionContribute(_msgSender(), tokenAddress, seller, sellerNonce, contribution);
}
function listItem(
address _tokenAddress,
uint256 _price,//wei per frak
uint256 _numberOfShares,
string memory _name
) payable external returns (bool) {
require(msg.value >= listingFee);
require(_price>0);
uint256 fraktionsIndex = FraktalNFT(_tokenAddress).fraktionsIndex();
require(
FraktalNFT(_tokenAddress).balanceOf(address(this), 0) == 1
);// "nft not in market"
require(!FraktalNFT(_tokenAddress).sold());//"item sold"
require(
FraktalNFT(_tokenAddress).balanceOf(_msgSender(), fraktionsIndex) >=
_numberOfShares
);//"no valid Fraktions"
Listing memory listed = listings[_tokenAddress][_msgSender()];
require(listed.numberOfShares == 0);//"unlist first"
Listing memory listing = Listing({
tokenAddress: _tokenAddress,
price: _price,
numberOfShares: _numberOfShares,
name: _name
});
listings[_tokenAddress][_msgSender()] = listing;
emit ItemListed(_msgSender(), _tokenAddress, _price, _numberOfShares, _name);
return true;
}
function listItemAuction(
address _tokenAddress,
uint256 _reservePrice,
uint256 _numberOfShares,
string memory _name
) payable external returns (uint256) {
require(msg.value >= listingFee);
uint256 fraktionsIndex = FraktalNFT(_tokenAddress).fraktionsIndex();
require(
FraktalNFT(_tokenAddress).balanceOf(address(this), 0) == 1
);//"nft not in market"
require(!FraktalNFT(_tokenAddress).sold());// "item sold"
require(
FraktalNFT(_tokenAddress).balanceOf(_msgSender(), fraktionsIndex) >=
_numberOfShares
);//"no valid Fraktions"
require(_reservePrice>0);
uint256 sellerNonce = auctionNonce[_msgSender()]++;
uint256 _endTime = block.timestamp + (10 days);
auctionListings[_tokenAddress][_msgSender()][sellerNonce] = AuctionListing({
tokenAddress: _tokenAddress,
reservePrice: _reservePrice,
numberOfShares: _numberOfShares,
auctionEndTime: _endTime,
name: _name
});
FraktalNFT(_tokenAddress).safeTransferFrom(
_msgSender(),
address(this),
fraktionsIndex,
_numberOfShares,
""
);
emit AuctionItemListed(_msgSender(), _tokenAddress, _reservePrice, _numberOfShares, _endTime, sellerNonce, _name);
return auctionNonce[_msgSender()];
}
function exportFraktal(address tokenAddress) public {
uint256 fraktionsIndex = FraktalNFT(tokenAddress).fraktionsIndex();
FraktalNFT(tokenAddress).safeTransferFrom(_msgSender(), address(this), fraktionsIndex, 10000*10**18, '');
FraktalNFT(tokenAddress).defraktionalize();
FraktalNFT(tokenAddress).safeTransferFrom(address(this), _msgSender(), 0, 1, '');
}
function makeOffer(address tokenAddress, uint256 _value) public payable {
require(msg.value >= _value);//"No pay"
Proposal storage prop = offers[_msgSender()][tokenAddress];
address payable offerer = payable(_msgSender());
require(!prop.winner);// "offer accepted"
if (_value >= prop.value) {
require(_value >= maxPriceRegistered[tokenAddress], "Min offer");
require(msg.value >= _value - prop.value);
} else {
uint256 bufferedValue = prop.value;
prop.value = 0;
AddressUpgradeable.sendValue(offerer, bufferedValue);
}
offers[_msgSender()][tokenAddress] = Proposal({
value: _value,
winner: false
});
emit OfferMade(_msgSender(), tokenAddress, _value);
}
function rejectOffer(address from, address to, address tokenAddress) external {
FraktalNFT(tokenAddress).unlockSharesTransfer(
from,
to
);
}
function voteOffer(address offerer, address tokenAddress) external {
uint256 fraktionsIndex = FraktalNFT(tokenAddress).fraktionsIndex();
Proposal storage offer = offers[offerer][tokenAddress];
uint256 lockedShares = FraktalNFT(tokenAddress).lockedShares(fraktionsIndex,_msgSender());
uint256 votesAvailable = FraktalNFT(tokenAddress).balanceOf(
_msgSender(),
fraktionsIndex
) - lockedShares;
FraktalNFT(tokenAddress).lockSharesTransfer(
_msgSender(),
votesAvailable,
offerer
);
uint256 lockedToOfferer = FraktalNFT(tokenAddress).lockedToTotal(fraktionsIndex,offerer);
bool sold = false;
if (lockedToOfferer > FraktalNFT(tokenAddress).majority()) {
FraktalNFT(tokenAddress).sellItem();
offer.winner = true;
sold = true;
}
emit OfferVoted(_msgSender(), offerer, tokenAddress, sold);
}
function claimFraktal(address tokenAddress) external {
uint256 fraktionsIndex = FraktalNFT(tokenAddress).fraktionsIndex();
if (FraktalNFT(tokenAddress).sold()) {
Proposal memory offer = offers[_msgSender()][tokenAddress];
require(
FraktalNFT(tokenAddress).lockedToTotal(fraktionsIndex,_msgSender())
> FraktalNFT(tokenAddress).majority(),
"not buyer"
);
FraktalNFT(tokenAddress).createRevenuePayment{ value: offer.value }(address(this));
maxPriceRegistered[tokenAddress] = 0;
}
FraktalNFT(tokenAddress).safeTransferFrom(
address(this),
_msgSender(),
0,
1,
""
);
emit FraktalClaimed(_msgSender(), tokenAddress);
}
function unlistItem(address tokenAddress) external {
delete listings[tokenAddress][_msgSender()];
emit ItemListed(_msgSender(), tokenAddress, 0, 0, "");
}
function unlistAuctionItem(address tokenAddress,uint256 sellerNonce) external {
AuctionListing storage auctionListed = auctionListings[tokenAddress][_msgSender()][sellerNonce];
require(auctionListed.auctionEndTime>0);
auctionListed.auctionEndTime = block.timestamp;
emit AuctionItemListed(_msgSender(), tokenAddress, 0, 0, auctionListed.auctionEndTime,sellerNonce, "");
}
// GETTERS
//////////////////////////////////
function getFee() external view returns (uint256) {
return (fee);
}
function getListingPrice(address _listOwner, address tokenAddress)
external
view
returns (uint256)
{
return listings[tokenAddress][_listOwner].price;
}
function getListingAmount(address _listOwner, address tokenAddress)
external
view
returns (uint256)
{
return listings[tokenAddress][_listOwner].numberOfShares;
}
function getSellerBalance(address _who) external view returns (uint256) {
return (sellersBalance[_who]);
}
function getOffer(address offerer, address tokenAddress)
external
view
returns (uint256)
{
return (offers[offerer][tokenAddress].value);
}
fallback() external payable {
feesAccrued += msg.value;
}
receive() external payable {
feesAccrued += msg.value;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// 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 "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol";
import "./PaymentSplitterUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableMap.sol";
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC1155/utils/ERC1155HolderUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/utils/ERC721HolderUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
contract FraktalNFT is ERC1155Upgradeable,ERC721HolderUpgradeable,ERC1155HolderUpgradeable{
using EnumerableSet for EnumerableSet.AddressSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
address revenueChannelImplementation;
bool fraktionalized;
bool public sold;
uint256 public fraktionsIndex;
uint16 public majority;
mapping(uint256 => bool) public indexUsed;
mapping(uint256 => mapping(address => uint256)) public lockedShares;
mapping(uint256 => mapping(address => uint256)) public lockedToTotal;
EnumerableSet.AddressSet private holders;
EnumerableMap.UintToAddressMap private revenues;
string public name = "FraktalNFT";
string public symbol = "FRAK";
address public factory;
address collateral;
event LockedSharesForTransfer(
address shareOwner,
address to,
uint256 numShares
);
event unLockedSharesForTransfer(
address shareOwner,
address to,
uint256 numShares
);
event ItemSold(address buyer, uint256 indexUsed);
event NewRevenueAdded(
address payer,
address revenueChannel,
uint256 amount,
bool sold
);
event Fraktionalized(address holder, address minter, uint256 index);
event Defraktionalized(address holder, uint256 index);
event MajorityValueChanged(uint16 newValue);
// constructor() initializer {}
function init(
address _creator,
address _revenueChannelImplementation,
string calldata uri,
uint16 _majority,
string memory _name,
string memory _symbol
) external initializer {
__ERC1155_init(uri);
_mint(_creator, 0, 1, "");
fraktionalized = false;
sold = false;
majority = _majority;
revenueChannelImplementation = _revenueChannelImplementation;
holders.add(_creator);
if(keccak256(abi.encodePacked(_name)) != keccak256(abi.encodePacked("")) &&
keccak256(abi.encodePacked(_symbol)) != keccak256(abi.encodePacked(""))
){
name = _name;
symbol = _symbol;
}
factory = msg.sender;//factory as msg.sender
}
// User Functions
///////////////////////////
function fraktionalize(address _to, uint256 _tokenId) external {
require((_tokenId != 0) &&
(this.balanceOf(_msgSender(), 0) == 1) &&
!fraktionalized &&
(indexUsed[_tokenId] == false)
);
// require(this.balanceOf(_msgSender(), 0) == 1);
// require(fraktionalized == false);
// require(indexUsed[_tokenId] == false);
fraktionalized = true;
sold = false;
fraktionsIndex = _tokenId;
_mint(_to, _tokenId, 10000*10**18, "");
emit Fraktionalized(_msgSender(), _to, _tokenId);
}
function defraktionalize() external {
fraktionalized = false;
_burn(_msgSender(), fraktionsIndex, 10000*10**18);
emit Defraktionalized(_msgSender(), fraktionsIndex);
}
function setMajority(uint16 newValue) external {
require((this.balanceOf(_msgSender(), 0) == 1)&&
(newValue <= 10000*10**18)
);
// require(newValue <= 10000*10**18);
// require(newValue > 0);
majority = newValue;
emit MajorityValueChanged(newValue);
}
function soldBurn(
address owner,
uint256 _tokenId,
uint256 bal
) external {
if (_msgSender() != owner) {
require(isApprovedForAll(owner, _msgSender()));
}
_burn(owner, _tokenId, bal);
}
function lockSharesTransfer(
address from,
uint256 numShares,
address _to
) external {
if (from != _msgSender()) {
require(isApprovedForAll(from, _msgSender()));
}
require(
balanceOf(from, fraktionsIndex) - lockedShares[fraktionsIndex][from] >=
numShares
);
lockedShares[fraktionsIndex][from] += numShares;
lockedToTotal[fraktionsIndex][_to] += numShares;
emit LockedSharesForTransfer(from, _to, numShares);
}
function unlockSharesTransfer(address from, address _to) external {
require(!sold);
if (from != _msgSender()) {
require(isApprovedForAll(from, _msgSender()));
}
uint256 balance = lockedShares[fraktionsIndex][from];
lockedShares[fraktionsIndex][from] -= balance;
lockedToTotal[fraktionsIndex][_to] -= balance;
emit unLockedSharesForTransfer(from, _to, 0);
}
function createRevenuePayment(address _marketAddress) external payable returns (address _clone) {
cleanUpHolders();
address[] memory owners = holders.values();
uint256 listLength = holders.length();
uint256[] memory fraktions = new uint256[](listLength);
for (uint256 i = 0; i < listLength; i++) {
fraktions[i] = this.balanceOf(owners[i], fraktionsIndex);
}
_clone = ClonesUpgradeable.clone(revenueChannelImplementation);
address payable revenueContract = payable(_clone);
PaymentSplitterUpgradeable(revenueContract).init(owners, fraktions, _marketAddress);
uint256 bufferedValue = msg.value;
AddressUpgradeable.sendValue(revenueContract, bufferedValue);
uint256 index = revenues.length();
revenues.set(index, _clone);
emit NewRevenueAdded(_msgSender(), revenueContract, msg.value, sold);
}
function sellItem() external payable {
require(this.balanceOf(_msgSender(), 0) == 1);
sold = true;
fraktionalized = false;
indexUsed[fraktionsIndex] = true;
emit ItemSold(_msgSender(), fraktionsIndex);
}
function cleanUpHolders() internal {
uint16 cur = 0;
while(cur < holders.length()){
if (this.balanceOf(holders.at(cur), fraktionsIndex) < 1) {
holders.remove(holders.at(cur));
cur=0;
}
cur++;
}
}
// Overrided functions
////////////////////////////////
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory tokenId,
uint256[] memory amount,
bytes memory data
) internal virtual override {
super._beforeTokenTransfer(operator, from, to, tokenId, amount, data);
if (from != address(0) && to != address(0)) {
if (tokenId[0] == 0) {
if (fraktionalized == true && sold == false) {
require((lockedToTotal[fraktionsIndex][to] > 9999));
}
} else {
require(sold != true);
require(
(balanceOf(from, tokenId[0]) - lockedShares[fraktionsIndex][from] >=
amount[0])
);
}
holders.add(to);
}
}
// Getters
///////////////////////////
// function getRevenue(uint256 index) external view returns (address) {
// return revenues.get(index);
// }
// function getFraktions(address who) external view returns (uint256) {
// return this.balanceOf(who, fraktionsIndex);
// }
// function getLockedShares(uint256 index, address who)
// external
// view
// returns (uint256)
// {
// return lockedShares[index][who];
// }
// function getLockedToTotal(uint256 index, address who)
// external
// view
// returns (uint256)
// {
// return lockedToTotal[index][who];
// }
/**
*@notice transfer contained ERC721 to the Fraktal owner with given address and index
*@param contractAddress address of ERC721 contained
*@param index index of the ERC721
*/
//todo: Should block if collateral is being claimed
function claimContainedERC721(address contractAddress, uint256 index) external{
if(msg.sender != factory){
require(contractAddress != collateral);
}
require((this.balanceOf(msg.sender, 0) == 1) && !fraktionalized && (IERC721(contractAddress).ownerOf(index) == address(this)));
// require(fraktionalized==false);
// require(IERC721(contractAddress).ownerOf(index) == address(this));
IERC721(contractAddress).safeTransferFrom(address(this), msg.sender, index);
}
/**
*@notice transfer contained ERC1155 to the Fraktal owner with given address and index
*@param contractAddress address of ERC1155 contained
*@param index index of the ERC1155
*/
//todo: Should block if collateral is being claimed
function claimContainedERC1155(address contractAddress, uint256 index, uint256 amount) external{
if(msg.sender != factory){
require(contractAddress != collateral);
}
require((this.balanceOf(msg.sender, 0) == 1) && !fraktionalized);
IERC1155(contractAddress).safeTransferFrom(address(this), msg.sender, index, amount,"");
}
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC1155Upgradeable, ERC1155ReceiverUpgradeable) returns (bool) {
return ERC1155Upgradeable.supportsInterface(interfaceId) || ERC1155ReceiverUpgradeable.supportsInterface(interfaceId);
}
function setCollateral(address _collateral ) external{
require(msg.sender == factory);
collateral = _collateral;
}
// function getStatus() external view returns (bool) {
// return sold;
// }
// function getFraktionsIndex() external view returns (uint256) {
// return fraktionsIndex;
// }
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/ERC1155.sol)
pragma solidity ^0.8.0;
import "./IERC1155Upgradeable.sol";
import "./IERC1155ReceiverUpgradeable.sol";
import "./extensions/IERC1155MetadataURIUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../utils/introspection/ERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable {
using AddressUpgradeable for address;
// Mapping from token ID to account balances
mapping(uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/**
* @dev See {_setURI}.
*/
function __ERC1155_init(string memory uri_) internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC1155_init_unchained(uri_);
}
function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing {
_setURI(uri_);
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return
interfaceId == type(IERC1155Upgradeable).interfaceId ||
interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) public view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] memory accounts, uint256[] memory ids)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
_safeTransferFrom(from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
_safeBatchTransferFrom(from, to, ids, amounts, data);
}
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: insufficient balance for transfer");
unchecked {
_balances[id][from] = fromBalance - amount;
}
_balances[id][to] += amount;
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][to] += amount;
emit TransferSingle(operator, address(0), to, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; i++) {
_balances[ids[i]][to] += amounts[i];
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `from`
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `from` must have at least `amount` tokens of token type `id`.
*/
function _burn(
address from,
uint256 id,
uint256 amount
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
emit TransferSingle(operator, from, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(
address from,
uint256[] memory ids,
uint256[] memory amounts
) internal virtual {
require(from != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, from, address(0), ids, amounts, "");
for (uint256 i = 0; i < ids.length; i++) {
uint256 id = ids[i];
uint256 amount = amounts[i];
uint256 fromBalance = _balances[id][from];
require(fromBalance >= amount, "ERC1155: burn amount exceeds balance");
unchecked {
_balances[id][from] = fromBalance - amount;
}
}
emit TransferBatch(operator, from, address(0), ids, amounts);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC1155: setting approval status for self");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal virtual {}
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) private {
if (to.isContract()) {
try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (
bytes4 response
) {
if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
uint256[47] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol)
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(
address implementation,
bytes32 salt,
address deployer
) internal pure returns (address predicted) {
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt)
internal
view
returns (address predicted)
{
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC1155Receiver.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155Holder is ERC1155Receiver {
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IFraktalNFT.sol";
import "./FraktalNFT.sol";
import "./FraktalMarket.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
address tokenParent;
uint256 fraktionsIndex;
bool public buyout;
address marketContract;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
function init(address[] memory payees, uint256[] memory shares_, address _marketContract)
external
initializer
{
__PaymentSplitter_init(payees, shares_);
tokenParent = _msgSender();
fraktionsIndex = FraktalNFT(_msgSender()).fraktionsIndex();
buyout = FraktalNFT(_msgSender()).sold();
marketContract = _marketContract;
}
function __PaymentSplitter_init(
address[] memory payees,
uint256[] memory shares_
) internal {
__Context_init_unchained();
__PaymentSplitter_init_unchained(payees, shares_);
}
function __PaymentSplitter_init_unchained(
address[] memory payees,
uint256[] memory shares_
) internal {
require(
payees.length == shares_.length,
"PaymentSplitter: payees and shares length mismatch"
);
require(payees.length > 0, "PaymentSplitter: no payees");
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() external view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() external view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) external view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) external view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) external view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release() external virtual {
address payable operator = payable(_msgSender());
require(_shares[operator] > 0, "PaymentSplitter: account has no shares");
if (buyout) {
// uint256 bal = IFraktalNFT(tokenParent).getFraktions(_msgSender());
uint256 bal = FraktalNFT(tokenParent).balanceOf(_msgSender(),FraktalNFT(tokenParent).fraktionsIndex());
IFraktalNFT(tokenParent).soldBurn(_msgSender(), fraktionsIndex, bal);
}
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[operator]) /
_totalShares -
_released[operator];
require(payment != 0, "PaymentSplitter: operator is not due payment");
_released[operator] = _released[operator] + payment;
_totalReleased = _totalReleased + payment;
address payable marketPayable = payable(marketContract);
uint16 marketFee = FraktalMarket(marketPayable).fee();
uint256 forMarket = (payment * marketFee )/ 10000;
uint256 forOperator = payment - forMarket;
AddressUpgradeable.sendValue(operator, forOperator);
AddressUpgradeable.sendValue(marketPayable, forMarket);
emit PaymentReleased(operator, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(
account != address(0),
"PaymentSplitter: account is the zero address"
);
require(shares_ > 0, "PaymentSplitter: shares are 0");
require(
_shares[account] == 0,
"PaymentSplitter: account already has shares"
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./EnumerableSet.sol";
/**
* @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 EnumerableMap {
using EnumerableSet for EnumerableSet.Bytes32Set;
// 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 Map {
// Storage of keys
EnumerableSet.Bytes32Set _keys;
mapping(bytes32 => bytes32) _values;
}
/**
* @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) {
map._values[key] = value;
return map._keys.add(key);
}
/**
* @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) {
delete map._values[key];
return map._keys.remove(key);
}
/**
* @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._keys.contains(key);
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._keys.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) {
bytes32 key = map._keys.at(index);
return (key, map._values[key]);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) {
bytes32 value = map._values[key];
if (value == bytes32(0)) {
return (_contains(map, key), bytes32(0));
} else {
return (true, 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) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), "EnumerableMap: nonexistent key");
return value;
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
bytes32 value = map._values[key];
require(value != 0 || _contains(map, key), errorMessage);
return value;
}
// 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(uint160(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(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) {
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(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(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Holder.sol)
pragma solidity ^0.8.0;
import "./ERC1155ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev _Available since v3.1._
*/
contract ERC1155HolderUpgradeable is Initializable, ERC1155ReceiverUpgradeable {
function __ERC1155Holder_init() internal onlyInitializing {
__ERC165_init_unchained();
__ERC1155Receiver_init_unchained();
__ERC1155Holder_init_unchained();
}
function __ERC1155Holder_init_unchained() internal onlyInitializing {
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] memory,
uint256[] memory,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/utils/ERC721Holder.sol)
pragma solidity ^0.8.0;
import "../IERC721ReceiverUpgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721HolderUpgradeable is Initializable, IERC721ReceiverUpgradeable {
function __ERC721Holder_init() internal onlyInitializing {
__ERC721Holder_init_unchained();
}
function __ERC721Holder_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(
address indexed operator,
address indexed from,
address indexed to,
uint256[] ids,
uint256[] values
);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids)
external
view
returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes calldata data
) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol)
pragma solidity ^0.8.0;
import "../IERC1155Upgradeable.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IFraktalNFT {
function fraktionalize(address _to, uint _tokenId) external;
function setMajority(uint16 newValue) external;
function defraktionalize() external;
function soldBurn(address owner, uint256 _tokenId, uint256 bal) external;
function lockSharesTransfer(address from, uint numShares, address _to) external;
function unlockSharesTransfer(address from, address _to) external;
function createRevenuePayment() external returns (address _clone);
function sellItem() external;
function cleanUpHolders() external;
function getRevenue(uint256 index) external view returns(address);
function getFraktions(address who) external view returns(uint);
function getLockedShares(uint256 index, address who) external view returns(uint);
function getLockedToTotal(uint256 index, address who) external view returns(uint);
function getStatus() external view returns (bool);
function getFraktionsIndex() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC1155/utils/ERC1155Receiver.sol)
pragma solidity ^0.8.0;
import "../IERC1155ReceiverUpgradeable.sol";
import "../../../utils/introspection/ERC165Upgradeable.sol";
import "../../../proxy/utils/Initializable.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155ReceiverUpgradeable is Initializable, ERC165Upgradeable, IERC1155ReceiverUpgradeable {
function __ERC1155Receiver_init() internal onlyInitializing {
__ERC165_init_unchained();
__ERC1155Receiver_init_unchained();
}
function __ERC1155Receiver_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC1155Receiver.sol";
import "../../../utils/introspection/ERC165.sol";
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155Receiver is ERC165, IERC1155Receiver {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return interfaceId == type(IERC1155Receiver).interfaceId || super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
) external returns (bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
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;
}
} | Compute the node and verify the merkle proof | function canClaim(
address user,
uint256 amount,
bytes32[] calldata merkleProof
) external view returns (bool) {
if (block.timestamp <= endTimestamp) {
bytes32 node = keccak256(abi.encodePacked(user, amount));
return MerkleProof.verify(merkleProof, merkleRoot, node);
return false;
}
}
| 6,177,746 |
// SPDX-License-Identifier: AGPL-3.0-or-later
pragma solidity 0.8.2;
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);
}
interface IBoostedVaultWithLockup {
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount) external;
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount) external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external;
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last) external;
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount) external;
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external;
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external;
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last) external;
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account) external;
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() external view returns (uint256);
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() external view returns (uint256);
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) external view returns (uint256);
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
returns (
uint256 amount,
uint256 first,
uint256 last
);
}
contract ModuleKeys {
// Governance
// ===========
// keccak256("Governance");
bytes32 internal constant KEY_GOVERNANCE =
0x9409903de1e6fd852dfc61c9dacb48196c48535b60e25abf92acc92dd689078d;
//keccak256("Staking");
bytes32 internal constant KEY_STAKING =
0x1df41cd916959d1163dc8f0671a666ea8a3e434c13e40faef527133b5d167034;
//keccak256("ProxyAdmin");
bytes32 internal constant KEY_PROXY_ADMIN =
0x96ed0203eb7e975a4cbcaa23951943fa35c5d8288117d50c12b3d48b0fab48d1;
// mStable
// =======
// keccak256("OracleHub");
bytes32 internal constant KEY_ORACLE_HUB =
0x8ae3a082c61a7379e2280f3356a5131507d9829d222d853bfa7c9fe1200dd040;
// keccak256("Manager");
bytes32 internal constant KEY_MANAGER =
0x6d439300980e333f0256d64be2c9f67e86f4493ce25f82498d6db7f4be3d9e6f;
//keccak256("Recollateraliser");
bytes32 internal constant KEY_RECOLLATERALISER =
0x39e3ed1fc335ce346a8cbe3e64dd525cf22b37f1e2104a755e761c3c1eb4734f;
//keccak256("MetaToken");
bytes32 internal constant KEY_META_TOKEN =
0xea7469b14936af748ee93c53b2fe510b9928edbdccac3963321efca7eb1a57a2;
// keccak256("SavingsManager");
bytes32 internal constant KEY_SAVINGS_MANAGER =
0x12fe936c77a1e196473c4314f3bed8eeac1d757b319abb85bdda70df35511bf1;
// keccak256("Liquidator");
bytes32 internal constant KEY_LIQUIDATOR =
0x1e9cb14d7560734a61fa5ff9273953e971ff3cd9283c03d8346e3264617933d4;
// keccak256("InterestValidator");
bytes32 internal constant KEY_INTEREST_VALIDATOR =
0xc10a28f028c7f7282a03c90608e38a4a646e136e614e4b07d119280c5f7f839f;
}
interface INexus {
function governor() external view returns (address);
function getModule(bytes32 key) external view returns (address);
function proposeModule(bytes32 _key, address _addr) external;
function cancelProposedModule(bytes32 _key) external;
function acceptProposedModule(bytes32 _key) external;
function acceptProposedModules(bytes32[] calldata _keys) external;
function requestLockModule(bytes32 _key) external;
function cancelLockModule(bytes32 _key) external;
function lockModule(bytes32 _key) external;
}
abstract contract ImmutableModule is ModuleKeys {
INexus public immutable nexus;
/**
* @dev Initialization function for upgradable proxy contracts
* @param _nexus Nexus contract address
*/
constructor(address _nexus) {
require(_nexus != address(0), "Nexus address is zero");
nexus = INexus(_nexus);
}
/**
* @dev Modifier to allow function calls only from the Governor.
*/
modifier onlyGovernor() {
_onlyGovernor();
_;
}
function _onlyGovernor() internal view {
require(msg.sender == _governor(), "Only governor can execute");
}
/**
* @dev Modifier to allow function calls only from the Governance.
* Governance is either Governor address or Governance address.
*/
modifier onlyGovernance() {
require(
msg.sender == _governor() || msg.sender == _governance(),
"Only governance can execute"
);
_;
}
/**
* @dev Modifier to allow function calls only from the ProxyAdmin.
*/
modifier onlyProxyAdmin() {
require(msg.sender == _proxyAdmin(), "Only ProxyAdmin can execute");
_;
}
/**
* @dev Modifier to allow function calls only from the Manager.
*/
modifier onlyManager() {
require(msg.sender == _manager(), "Only manager can execute");
_;
}
/**
* @dev Returns Governor address from the Nexus
* @return Address of Governor Contract
*/
function _governor() internal view returns (address) {
return nexus.governor();
}
/**
* @dev Returns Governance Module address from the Nexus
* @return Address of the Governance (Phase 2)
*/
function _governance() internal view returns (address) {
return nexus.getModule(KEY_GOVERNANCE);
}
/**
* @dev Return Staking Module address from the Nexus
* @return Address of the Staking Module contract
*/
function _staking() internal view returns (address) {
return nexus.getModule(KEY_STAKING);
}
/**
* @dev Return ProxyAdmin Module address from the Nexus
* @return Address of the ProxyAdmin Module contract
*/
function _proxyAdmin() internal view returns (address) {
return nexus.getModule(KEY_PROXY_ADMIN);
}
/**
* @dev Return MetaToken Module address from the Nexus
* @return Address of the MetaToken Module contract
*/
function _metaToken() internal view returns (address) {
return nexus.getModule(KEY_META_TOKEN);
}
/**
* @dev Return OracleHub Module address from the Nexus
* @return Address of the OracleHub Module contract
*/
function _oracleHub() internal view returns (address) {
return nexus.getModule(KEY_ORACLE_HUB);
}
/**
* @dev Return Manager Module address from the Nexus
* @return Address of the Manager Module contract
*/
function _manager() internal view returns (address) {
return nexus.getModule(KEY_MANAGER);
}
/**
* @dev Return SavingsManager Module address from the Nexus
* @return Address of the SavingsManager Module contract
*/
function _savingsManager() internal view returns (address) {
return nexus.getModule(KEY_SAVINGS_MANAGER);
}
/**
* @dev Return Recollateraliser Module address from the Nexus
* @return Address of the Recollateraliser Module contract (Phase 2)
*/
function _recollateraliser() internal view returns (address) {
return nexus.getModule(KEY_RECOLLATERALISER);
}
}
interface IRewardsDistributionRecipient {
function notifyRewardAmount(uint256 reward) external;
function getRewardToken() external view returns (IERC20);
}
abstract contract InitializableRewardsDistributionRecipient is
IRewardsDistributionRecipient,
ImmutableModule
{
// This address has the ability to distribute the rewards
address public rewardsDistributor;
constructor(address _nexus) ImmutableModule(_nexus) {}
/** @dev Recipient is a module, governed by mStable governance */
function _initialize(address _rewardsDistributor) internal {
rewardsDistributor = _rewardsDistributor;
}
/**
* @dev Only the rewards distributor can notify about rewards
*/
modifier onlyRewardsDistributor() {
require(msg.sender == rewardsDistributor, "Caller is not reward distributor");
_;
}
/**
* @dev Change the rewardsDistributor - only called by mStable governor
* @param _rewardsDistributor Address of the new distributor
*/
function setRewardsDistribution(address _rewardsDistributor) external onlyGovernor {
rewardsDistributor = _rewardsDistributor;
}
}
interface IBoostDirector {
function getBalance(address _user) external returns (uint256);
function setDirection(
address _old,
address _new,
bool _pokeNew
) external;
function whitelistVaults(address[] calldata _vaults) external;
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
/**
* @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);
}
}
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract InitializableReentrancyGuard {
bool private _notEntered;
function _initializeReentrancyGuard() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
library StableMath {
/**
* @dev Scaling unit for use in specific calculations,
* where 1 * 10**18, or 1e18 represents a unit '1'
*/
uint256 private constant FULL_SCALE = 1e18;
/**
* @dev Token Ratios are used when converting between units of bAsset, mAsset and MTA
* Reasoning: Takes into account token decimals, and difference in base unit (i.e. grams to Troy oz for gold)
* bAsset ratio unit for use in exact calculations,
* where (1 bAsset unit * bAsset.ratio) / ratioScale == x mAsset unit
*/
uint256 private constant RATIO_SCALE = 1e8;
/**
* @dev Provides an interface to the scaling unit
* @return Scaling unit (1e18 or 1 * 10**18)
*/
function getFullScale() internal pure returns (uint256) {
return FULL_SCALE;
}
/**
* @dev Provides an interface to the ratio unit
* @return Ratio scale unit (1e8 or 1 * 10**8)
*/
function getRatioScale() internal pure returns (uint256) {
return RATIO_SCALE;
}
/**
* @dev Scales a given integer to the power of the full scale.
* @param x Simple uint256 to scale
* @return Scaled value a to an exact number
*/
function scaleInteger(uint256 x) internal pure returns (uint256) {
return x * FULL_SCALE;
}
/***************************************
PRECISE ARITHMETIC
****************************************/
/**
* @dev Multiplies two precise units, and then truncates by the full scale
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncate(uint256 x, uint256 y) internal pure returns (uint256) {
return mulTruncateScale(x, y, FULL_SCALE);
}
/**
* @dev Multiplies two precise units, and then truncates by the given scale. For example,
* when calculating 90% of 10e18, (10e18 * 9e17) / 1e18 = (9e36) / 1e18 = 9e18
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @param scale Scale unit
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit
*/
function mulTruncateScale(
uint256 x,
uint256 y,
uint256 scale
) internal pure returns (uint256) {
// e.g. assume scale = fullScale
// z = 10e18 * 9e17 = 9e36
// return 9e38 / 1e18 = 9e18
return (x * y) / scale;
}
/**
* @dev Multiplies two precise units, and then truncates by the full scale, rounding up the result
* @param x Left hand input to multiplication
* @param y Right hand input to multiplication
* @return Result after multiplying the two inputs and then dividing by the shared
* scale unit, rounded up to the closest base unit.
*/
function mulTruncateCeil(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e17 * 17268172638 = 138145381104e17
uint256 scaled = x * y;
// e.g. 138145381104e17 + 9.99...e17 = 138145381113.99...e17
uint256 ceil = scaled + FULL_SCALE - 1;
// e.g. 13814538111.399...e18 / 1e18 = 13814538111
return ceil / FULL_SCALE;
}
/**
* @dev Precisely divides two units, by first scaling the left hand operand. Useful
* for finding percentage weightings, i.e. 8e18/10e18 = 80% (or 8e17)
* @param x Left hand input to division
* @param y Right hand input to division
* @return Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divPrecisely(uint256 x, uint256 y) internal pure returns (uint256) {
// e.g. 8e18 * 1e18 = 8e36
// e.g. 8e36 / 10e18 = 8e17
return (x * FULL_SCALE) / y;
}
/***************************************
RATIO FUNCS
****************************************/
/**
* @dev Multiplies and truncates a token ratio, essentially flooring the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand operand to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return c Result after multiplying the two inputs and then dividing by the ratio scale
*/
function mulRatioTruncate(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
return mulTruncateScale(x, ratio, RATIO_SCALE);
}
/**
* @dev Multiplies and truncates a token ratio, rounding up the result
* i.e. How much mAsset is this bAsset worth?
* @param x Left hand input to multiplication (i.e Exact quantity)
* @param ratio bAsset ratio
* @return Result after multiplying the two inputs and then dividing by the shared
* ratio scale, rounded up to the closest base unit.
*/
function mulRatioTruncateCeil(uint256 x, uint256 ratio) internal pure returns (uint256) {
// e.g. How much mAsset should I burn for this bAsset (x)?
// 1e18 * 1e8 = 1e26
uint256 scaled = x * ratio;
// 1e26 + 9.99e7 = 100..00.999e8
uint256 ceil = scaled + RATIO_SCALE - 1;
// return 100..00.999e8 / 1e8 = 1e18
return ceil / RATIO_SCALE;
}
/**
* @dev Precisely divides two ratioed units, by first scaling the left hand operand
* i.e. How much bAsset is this mAsset worth?
* @param x Left hand operand in division
* @param ratio bAsset ratio
* @return c Result after multiplying the left operand by the scale, and
* executing the division on the right hand input.
*/
function divRatioPrecisely(uint256 x, uint256 ratio) internal pure returns (uint256 c) {
// e.g. 1e14 * 1e8 = 1e22
// return 1e22 / 1e12 = 1e10
return (x * RATIO_SCALE) / ratio;
}
/***************************************
HELPERS
****************************************/
/**
* @dev Calculates minimum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Minimum of the two inputs
*/
function min(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? y : x;
}
/**
* @dev Calculated maximum of two numbers
* @param x Left hand input
* @param y Right hand input
* @return Maximum of the two inputs
*/
function max(uint256 x, uint256 y) internal pure returns (uint256) {
return x > y ? x : y;
}
/**
* @dev Clamps a value to an upper bound
* @param x Left hand input
* @param upperBound Maximum possible value to return
* @return Input x clamped to a maximum value, upperBound
*/
function clamp(uint256 x, uint256 upperBound) internal pure returns (uint256) {
return x > upperBound ? upperBound : x;
}
}
library Root {
/**
* @dev Returns the square root of a given number
* @param x Input
* @return y Square root of Input
*/
function sqrt(uint256 x) internal pure returns (uint256 y) {
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 uint256(r < r1 ? r : r1);
}
}
}
contract BoostedTokenWrapper is InitializableReentrancyGuard {
using StableMath for uint256;
using SafeERC20 for IERC20;
event Transfer(address indexed from, address indexed to, uint256 value);
string private _name;
string private _symbol;
IERC20 public immutable stakingToken;
IBoostDirector public immutable boostDirector;
uint256 private _totalBoostedSupply;
mapping(address => uint256) private _boostedBalances;
mapping(address => uint256) private _rawBalances;
// Vars for use in the boost calculations
uint256 private constant MIN_DEPOSIT = 1e18;
uint256 private constant MAX_VMTA = 400000e18;
uint256 private constant MAX_BOOST = 3e18;
uint256 private constant MIN_BOOST = 1e18;
uint256 private constant FLOOR = 95e16;
uint256 public immutable boostCoeff; // scaled by 10
uint256 public immutable priceCoeff;
/**
* @dev TokenWrapper constructor
* @param _stakingToken Wrapped token to be staked
* @param _boostDirector vMTA boost director
* @param _priceCoeff Rough price of a given LP token, to be used in boost calculations, where $1 = 1e18
*/
constructor(
address _stakingToken,
address _boostDirector,
uint256 _priceCoeff,
uint256 _boostCoeff
) {
stakingToken = IERC20(_stakingToken);
boostDirector = IBoostDirector(_boostDirector);
priceCoeff = _priceCoeff;
boostCoeff = _boostCoeff;
}
function _initialize(string memory _nameArg, string memory _symbolArg) internal {
_initializeReentrancyGuard();
_name = _nameArg;
_symbol = _symbolArg;
}
function name() public view virtual returns (string memory) {
return _name;
}
function symbol() public view virtual returns (string memory) {
return _symbol;
}
function decimals() public view virtual returns (uint8) {
return 18;
}
/**
* @dev Get the total boosted amount
* @return uint256 total supply
*/
function totalSupply() public view returns (uint256) {
return _totalBoostedSupply;
}
/**
* @dev Get the boosted balance of a given account
* @param _account User for which to retrieve balance
*/
function balanceOf(address _account) public view returns (uint256) {
return _boostedBalances[_account];
}
/**
* @dev Get the RAW balance of a given account
* @param _account User for which to retrieve balance
*/
function rawBalanceOf(address _account) public view returns (uint256) {
return _rawBalances[_account];
}
/**
* @dev Read the boost for the given address
* @param _account User for which to return the boost
* @return boost where 1x == 1e18
*/
function getBoost(address _account) public view returns (uint256) {
return balanceOf(_account).divPrecisely(rawBalanceOf(_account));
}
/**
* @dev Deposits a given amount of StakingToken from sender
* @param _amount Units of StakingToken
*/
function _stakeRaw(address _beneficiary, uint256 _amount) internal nonReentrant {
_rawBalances[_beneficiary] += _amount;
stakingToken.safeTransferFrom(msg.sender, address(this), _amount);
}
/**
* @dev Withdraws a given stake from sender
* @param _amount Units of StakingToken
*/
function _withdrawRaw(uint256 _amount) internal nonReentrant {
_rawBalances[msg.sender] -= _amount;
stakingToken.safeTransfer(msg.sender, _amount);
}
/**
* @dev Updates the boost for the given address according to the formula
* boost = min(0.5 + c * vMTA_balance / imUSD_locked^(7/8), 1.5)
* If rawBalance <= MIN_DEPOSIT, boost is 0
* @param _account User for which to update the boost
*/
function _setBoost(address _account) internal {
uint256 rawBalance = _rawBalances[_account];
uint256 boostedBalance = _boostedBalances[_account];
uint256 boost = MIN_BOOST;
// Check whether balance is sufficient
// is_boosted is used to minimize gas usage
uint256 scaledBalance = (rawBalance * priceCoeff) / 1e18;
if (scaledBalance >= MIN_DEPOSIT) {
uint256 votingWeight = boostDirector.getBalance(_account);
boost = _computeBoost(scaledBalance, votingWeight);
}
uint256 newBoostedBalance = rawBalance.mulTruncate(boost);
if (newBoostedBalance != boostedBalance) {
_totalBoostedSupply = _totalBoostedSupply - boostedBalance + newBoostedBalance;
_boostedBalances[_account] = newBoostedBalance;
if(newBoostedBalance > boostedBalance) {
emit Transfer(address(0), _account, newBoostedBalance - boostedBalance);
} else {
emit Transfer(_account, address(0), boostedBalance - newBoostedBalance);
}
}
}
/**
* @dev Computes the boost for
* boost = min(m, max(1, 0.95 + c * min(voting_weight, f) / deposit^(7/8)))
* @param _scaledDeposit deposit amount in terms of USD
*/
function _computeBoost(uint256 _scaledDeposit, uint256 _votingWeight)
private
view
returns (uint256 boost)
{
if (_votingWeight == 0) return MIN_BOOST;
// Compute balance to the power 7/8
// if price is $0.10, do sqrt(_deposit * 1e5)
// if price is $1.00, do sqrt(_deposit * 1e6)
// if price is $10000.00, do sqrt(_deposit * 1e9)
uint256 denominator = Root.sqrt(Root.sqrt(Root.sqrt(_scaledDeposit * 1e6)));
denominator =
denominator *
denominator *
denominator *
denominator *
denominator *
denominator *
denominator;
denominator /= 1e3;
boost = (((StableMath.min(_votingWeight, MAX_VMTA) * boostCoeff) / 10) * 1e18) / denominator;
boost = StableMath.min(MAX_BOOST, StableMath.max(MIN_BOOST, FLOOR + boost));
}
}
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;
}
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// Internal
// Libs
/**
* @title BoostedSavingsVault
* @author mStable
* @notice Accrues rewards second by second, based on a users boosted balance
* @dev Forked from rewards/staking/StakingRewards.sol
* Changes:
* - Lockup implemented in `updateReward` hook (20% unlock immediately, 80% locked for 6 months)
* - `updateBoost` hook called after every external action to reset a users boost
* - Struct packing of common data
* - Searching for and claiming of unlocked rewards
*/
contract BoostedSavingsVault is
IBoostedVaultWithLockup,
Initializable,
InitializableRewardsDistributionRecipient,
BoostedTokenWrapper
{
using SafeERC20 for IERC20;
using StableMath for uint256;
using SafeCast for uint256;
event RewardAdded(uint256 reward);
event Staked(address indexed user, uint256 amount, address payer);
event Withdrawn(address indexed user, uint256 amount);
event Poked(address indexed user);
event RewardPaid(address indexed user, uint256 reward);
IERC20 public immutable rewardsToken;
uint64 public constant DURATION = 7 days;
// Length of token lockup, after rewards are earned
uint256 public constant LOCKUP = 26 weeks;
// Percentage of earned tokens unlocked immediately
uint64 public constant UNLOCK = 33e16;
// Timestamp for current period finish
uint256 public periodFinish;
// RewardRate for the rest of the PERIOD
uint256 public rewardRate;
// Last time any user took action
uint256 public lastUpdateTime;
// Ever increasing rewardPerToken rate, based on % of total supply
uint256 public rewardPerTokenStored;
mapping(address => UserData) public userData;
// Locked reward tracking
mapping(address => Reward[]) public userRewards;
mapping(address => uint64) public userClaim;
struct UserData {
uint128 rewardPerTokenPaid;
uint128 rewards;
uint64 lastAction;
uint64 rewardCount;
}
struct Reward {
uint64 start;
uint64 finish;
uint128 rate;
}
constructor(
address _nexus,
address _stakingToken,
address _boostDirector,
uint256 _priceCoeff,
uint256 _coeff,
address _rewardsToken
)
InitializableRewardsDistributionRecipient(_nexus)
BoostedTokenWrapper(_stakingToken, _boostDirector, _priceCoeff, _coeff)
{
rewardsToken = IERC20(_rewardsToken);
}
/**
* @dev StakingRewards is a TokenWrapper and RewardRecipient
* Constants added to bytecode at deployTime to reduce SLOAD cost
*/
function initialize(address _rewardsDistributor, string calldata _nameArg, string calldata _symbolArg) external initializer {
InitializableRewardsDistributionRecipient._initialize(_rewardsDistributor);
BoostedTokenWrapper._initialize(_nameArg, _symbolArg);
}
/**
* @dev Updates the reward for a given address, before executing function.
* Locks 80% of new rewards up for 6 months, vesting linearly from (time of last action + 6 months) to
* (now + 6 months). This allows rewards to be distributed close to how they were accrued, as opposed
* to locking up for a flat 6 months from the time of this fn call (allowing more passive accrual).
*/
modifier updateReward(address _account) {
uint256 currentTime = block.timestamp;
uint64 currentTime64 = SafeCast.toUint64(currentTime);
// Setting of global vars
(uint256 newRewardPerToken, uint256 lastApplicableTime) = _rewardPerToken();
// If statement protects against loss in initialisation case
if (newRewardPerToken > 0) {
rewardPerTokenStored = newRewardPerToken;
lastUpdateTime = lastApplicableTime;
// Setting of personal vars based on new globals
if (_account != address(0)) {
UserData memory data = userData[_account];
uint256 earned_ = _earned(_account, data.rewardPerTokenPaid, newRewardPerToken);
// If earned == 0, then it must either be the initial stake, or an action in the
// same block, since new rewards unlock after each block.
if (earned_ > 0) {
uint256 unlocked = earned_.mulTruncate(UNLOCK);
uint256 locked = earned_ - unlocked;
userRewards[_account].push(
Reward({
start: SafeCast.toUint64(LOCKUP + data.lastAction),
finish: SafeCast.toUint64(LOCKUP + currentTime),
rate: SafeCast.toUint128(locked / (currentTime - data.lastAction))
})
);
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: SafeCast.toUint128(unlocked + data.rewards),
lastAction: currentTime64,
rewardCount: data.rewardCount + 1
});
} else {
userData[_account] = UserData({
rewardPerTokenPaid: SafeCast.toUint128(newRewardPerToken),
rewards: data.rewards,
lastAction: currentTime64,
rewardCount: data.rewardCount
});
}
}
} else if (_account != address(0)) {
// This should only be hit once, for first staker in initialisation case
userData[_account].lastAction = currentTime64;
}
_;
}
/** @dev Updates the boost for a given address, after the rest of the function has executed */
modifier updateBoost(address _account) {
_;
_setBoost(_account);
}
/***************************************
ACTIONS - EXTERNAL
****************************************/
/**
* @dev Stakes a given amount of the StakingToken for the sender
* @param _amount Units of StakingToken
*/
function stake(uint256 _amount)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_stake(msg.sender, _amount);
}
/**
* @dev Stakes a given amount of the StakingToken for a given beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function stake(address _beneficiary, uint256 _amount)
external
override
updateReward(_beneficiary)
updateBoost(_beneficiary)
{
_stake(_beneficiary, _amount);
}
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function exit() external override updateReward(msg.sender) updateBoost(msg.sender) {
_withdraw(rawBalanceOf(msg.sender));
(uint256 first, uint256 last) = _unclaimedEpochs(msg.sender);
_claimRewards(first, last);
}
/**
* @dev Withdraws stake from pool and claims any unlocked rewards.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function exit(uint256 _first, uint256 _last)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_withdraw(rawBalanceOf(msg.sender));
_claimRewards(_first, _last);
}
/**
* @dev Withdraws given stake amount from the pool
* @param _amount Units of the staked token to withdraw
*/
function withdraw(uint256 _amount)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_withdraw(_amount);
}
/**
* @dev Claims only the tokens that have been immediately unlocked, not including
* those that are in the lockers.
*/
function claimReward() external override updateReward(msg.sender) updateBoost(msg.sender) {
uint256 unlocked = userData[msg.sender].rewards;
userData[msg.sender].rewards = 0;
if (unlocked > 0) {
rewardsToken.safeTransfer(msg.sender, unlocked);
emit RewardPaid(msg.sender, unlocked);
}
}
/**
* @dev Claims all unlocked rewards for sender.
* Note, this function is costly - the args for _claimRewards
* should be determined off chain and then passed to other fn
*/
function claimRewards() external override updateReward(msg.sender) updateBoost(msg.sender) {
(uint256 first, uint256 last) = _unclaimedEpochs(msg.sender);
_claimRewards(first, last);
}
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function claimRewards(uint256 _first, uint256 _last)
external
override
updateReward(msg.sender)
updateBoost(msg.sender)
{
_claimRewards(_first, _last);
}
/**
* @dev Pokes a given account to reset the boost
*/
function pokeBoost(address _account)
external
override
updateReward(_account)
updateBoost(_account)
{
emit Poked(_account);
}
/***************************************
ACTIONS - INTERNAL
****************************************/
/**
* @dev Claims all unlocked rewards for sender. Both immediately unlocked
* rewards and also locked rewards past their time lock.
* @param _first Index of the first array element to claim
* @param _last Index of the last array element to claim
*/
function _claimRewards(uint256 _first, uint256 _last) internal {
(uint256 unclaimed, uint256 lastTimestamp) = _unclaimedRewards(msg.sender, _first, _last);
userClaim[msg.sender] = uint64(lastTimestamp);
uint256 unlocked = userData[msg.sender].rewards;
userData[msg.sender].rewards = 0;
uint256 total = unclaimed + unlocked;
if (total > 0) {
rewardsToken.safeTransfer(msg.sender, total);
emit RewardPaid(msg.sender, total);
}
}
/**
* @dev Internally stakes an amount by depositing from sender,
* and crediting to the specified beneficiary
* @param _beneficiary Staked tokens are credited to this address
* @param _amount Units of StakingToken
*/
function _stake(address _beneficiary, uint256 _amount) internal {
require(_amount > 0, "Cannot stake 0");
require(_beneficiary != address(0), "Invalid beneficiary address");
_stakeRaw(_beneficiary, _amount);
emit Staked(_beneficiary, _amount, msg.sender);
}
/**
* @dev Withdraws raw units from the sender
* @param _amount Units of StakingToken
*/
function _withdraw(uint256 _amount) internal {
require(_amount > 0, "Cannot withdraw 0");
_withdrawRaw(_amount);
emit Withdrawn(msg.sender, _amount);
}
/***************************************
GETTERS
****************************************/
/**
* @dev Gets the RewardsToken
*/
function getRewardToken() external view override returns (IERC20) {
return rewardsToken;
}
/**
* @dev Gets the last applicable timestamp for this reward period
*/
function lastTimeRewardApplicable() public view override returns (uint256) {
return StableMath.min(block.timestamp, periodFinish);
}
/**
* @dev Calculates the amount of unclaimed rewards per token since last update,
* and sums with stored to give the new cumulative reward per token
* @return 'Reward' per staked token
*/
function rewardPerToken() public view override returns (uint256) {
(uint256 rewardPerToken_, ) = _rewardPerToken();
return rewardPerToken_;
}
function _rewardPerToken()
internal
view
returns (uint256 rewardPerToken_, uint256 lastTimeRewardApplicable_)
{
uint256 lastApplicableTime = lastTimeRewardApplicable(); // + 1 SLOAD
uint256 timeDelta = lastApplicableTime - lastUpdateTime; // + 1 SLOAD
// If this has been called twice in the same block, shortcircuit to reduce gas
if (timeDelta == 0) {
return (rewardPerTokenStored, lastApplicableTime);
}
// new reward units to distribute = rewardRate * timeSinceLastUpdate
uint256 rewardUnitsToDistribute = rewardRate * timeDelta; // + 1 SLOAD
uint256 supply = totalSupply(); // + 1 SLOAD
// If there is no StakingToken liquidity, avoid div(0)
// If there is nothing to distribute, short circuit
if (supply == 0 || rewardUnitsToDistribute == 0) {
return (rewardPerTokenStored, lastApplicableTime);
}
// new reward units per token = (rewardUnitsToDistribute * 1e18) / totalTokens
uint256 unitsToDistributePerToken = rewardUnitsToDistribute.divPrecisely(supply);
// return summed rate
return (rewardPerTokenStored + unitsToDistributePerToken, lastApplicableTime); // + 1 SLOAD
}
/**
* @dev Returned the units of IMMEDIATELY claimable rewards a user has to receive. Note - this
* does NOT include the majority of rewards which will be locked up.
* @param _account User address
* @return Total reward amount earned
*/
function earned(address _account) public view override returns (uint256) {
uint256 newEarned =
_earned(_account, userData[_account].rewardPerTokenPaid, rewardPerToken());
uint256 immediatelyUnlocked = newEarned.mulTruncate(UNLOCK);
return immediatelyUnlocked + userData[_account].rewards;
}
/**
* @dev Calculates all unclaimed reward data, finding both immediately unlocked rewards
* and those that have passed their time lock.
* @param _account User address
* @return amount Total units of unclaimed rewards
* @return first Index of the first userReward that has unlocked
* @return last Index of the last userReward that has unlocked
*/
function unclaimedRewards(address _account)
external
view
override
returns (
uint256 amount,
uint256 first,
uint256 last
)
{
(first, last) = _unclaimedEpochs(_account);
(uint256 unlocked, ) = _unclaimedRewards(_account, first, last);
amount = unlocked + earned(_account);
}
/** @dev Returns only the most recently earned rewards */
function _earned(
address _account,
uint256 _userRewardPerTokenPaid,
uint256 _currentRewardPerToken
) internal view returns (uint256) {
// current rate per token - rate user previously received
uint256 userRewardDelta = _currentRewardPerToken - _userRewardPerTokenPaid; // + 1 SLOAD
// Short circuit if there is nothing new to distribute
if (userRewardDelta == 0) {
return 0;
}
// new reward = staked tokens * difference in rate
uint256 userNewReward = balanceOf(_account).mulTruncate(userRewardDelta); // + 1 SLOAD
// add to previous rewards
return userNewReward;
}
/**
* @dev Gets the first and last indexes of array elements containing unclaimed rewards
*/
function _unclaimedEpochs(address _account)
internal
view
returns (uint256 first, uint256 last)
{
uint64 lastClaim = userClaim[_account];
uint256 firstUnclaimed = _findFirstUnclaimed(lastClaim, _account);
uint256 lastUnclaimed = _findLastUnclaimed(_account);
return (firstUnclaimed, lastUnclaimed);
}
/**
* @dev Sums the cumulative rewards from a valid range
*/
function _unclaimedRewards(
address _account,
uint256 _first,
uint256 _last
) internal view returns (uint256 amount, uint256 latestTimestamp) {
uint256 currentTime = block.timestamp;
uint64 lastClaim = userClaim[_account];
// Check for no rewards unlocked
uint256 totalLen = userRewards[_account].length;
if (_first == 0 && _last == 0) {
if (totalLen == 0 || currentTime <= userRewards[_account][0].start) {
return (0, currentTime);
}
}
// If there are previous unlocks, check for claims that would leave them untouchable
if (_first > 0) {
require(
lastClaim >= userRewards[_account][_first - 1].finish,
"Invalid _first arg: Must claim earlier entries"
);
}
uint256 count = _last - _first + 1;
for (uint256 i = 0; i < count; i++) {
uint256 id = _first + i;
Reward memory rwd = userRewards[_account][id];
require(currentTime >= rwd.start && lastClaim <= rwd.finish, "Invalid epoch");
uint256 endTime = StableMath.min(rwd.finish, currentTime);
uint256 startTime = StableMath.max(rwd.start, lastClaim);
uint256 unclaimed = (endTime - startTime) * rwd.rate;
amount += unclaimed;
}
// Calculate last relevant timestamp here to allow users to avoid issue of OOG errors
// by claiming rewards in batches.
latestTimestamp = StableMath.min(currentTime, userRewards[_account][_last].finish);
}
/**
* @dev Uses binarysearch to find the unclaimed lockups for a given account
*/
function _findFirstUnclaimed(uint64 _lastClaim, address _account)
internal
view
returns (uint256 first)
{
uint256 len = userRewards[_account].length;
if (len == 0) return 0;
// Binary search
uint256 min = 0;
uint256 max = len - 1;
// Will be always enough for 128-bit numbers
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
if (_lastClaim > userRewards[_account][mid].start) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
/**
* @dev Uses binarysearch to find the unclaimed lockups for a given account
*/
function _findLastUnclaimed(address _account) internal view returns (uint256 first) {
uint256 len = userRewards[_account].length;
if (len == 0) return 0;
// Binary search
uint256 min = 0;
uint256 max = len - 1;
// Will be always enough for 128-bit numbers
for (uint256 i = 0; i < 128; i++) {
if (min >= max) break;
uint256 mid = (min + max + 1) / 2;
if (block.timestamp > userRewards[_account][mid].start) {
min = mid;
} else {
max = mid - 1;
}
}
return min;
}
/***************************************
ADMIN
****************************************/
/**
* @dev Notifies the contract that new rewards have been added.
* Calculates an updated rewardRate based on the rewards in period.
* @param _reward Units of RewardToken that have been added to the pool
*/
function notifyRewardAmount(uint256 _reward)
external
override
onlyRewardsDistributor
updateReward(address(0))
{
require(_reward < 1e24, "Cannot notify with more than a million units");
uint256 currentTime = block.timestamp;
// If previous period over, reset rewardRate
if (currentTime >= periodFinish) {
rewardRate = _reward / DURATION;
}
// If additional reward to existing period, calc sum
else {
uint256 remaining = periodFinish - currentTime;
uint256 leftover = remaining * rewardRate;
rewardRate = (_reward + leftover) / DURATION;
}
lastUpdateTime = currentTime;
periodFinish = currentTime + DURATION;
emit RewardAdded(_reward);
}
} | Withdraws stake from pool and claims any unlocked rewards. Note, this function is costly - the args for _claimRewards should be determined off chain and then passed to other fn/ | function exit() external override updateReward(msg.sender) updateBoost(msg.sender) {
_withdraw(rawBalanceOf(msg.sender));
(uint256 first, uint256 last) = _unclaimedEpochs(msg.sender);
_claimRewards(first, last);
}
| 322,553 |
./full_match/1/0x226886287642969A4c6dCD14ecf4Dc2025d7bC6f/sources/contracts/AlphaCodes.sol | Airdrop mint to list of addresses with specified amounts | function airdropTo(address[] calldata _addresses, uint256[] calldata nMints) external onlyOwner {
unchecked {
for (uint256 i; i < _addresses.length; ++i) {
if (totalSupply() + nMints[i] > maxSupply) revert ExceedsTotalSupply();
_mint(_addresses[i], nMints[i]);
}
}
}
| 17,187,472 |
./full_match/5/0xA93cdfa006E16d0ced210030d62523Fe00f2E3e5/sources/contracts/claim/abstract/AdvancedDistributor.sol | decreasing claimable tokens increasing claimable tokens | function adjust(address beneficiary, int256 amount) external onlyOwner {
DistributionRecord memory distributionRecord = records[beneficiary];
require(distributionRecord.initialized, "must initialize before adjusting");
uint256 diff = uint256(amount > 0 ? amount : -amount);
require(diff < type(uint120).max, "adjustment > max uint120");
if (amount < 0) {
require(total >= diff, "decrease greater than distributor total");
require(distributionRecord.total >= diff, "decrease greater than distributionRecord total");
total -= diff;
records[beneficiary].total -= uint120(diff);
token.safeTransfer(owner(), diff);
total += diff;
records[beneficiary].total += uint120(diff);
}
emit Adjust(beneficiary, amount);
}
| 1,944,839 |
pragma solidity >=0.5.4 <0.6.0;
interface tokenRecipient { function RECEIVEAPPROVAL172(address _from, uint256 _value, address _token, bytes calldata _extraData) external; } //inject NONSTANDARD NAMING
library SafeMath {
function MUL710(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
function DIV595(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// 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;
}
function SUB853(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
assert(b <= a);
return a - b;
}
function ADD540(uint256 a, uint256 b) internal pure returns (uint256 c) { //inject NONSTANDARD NAMING
c = a + b;
assert(c >= a);
return c;
}
}
interface INameTAOPosition {
function SENDERISADVOCATE978(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISLISTENER841(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISSPEAKER648(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function SENDERISPOSITION99(address _sender, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function GETADVOCATE521(address _id) external view returns (address); //inject NONSTANDARD NAMING
function NAMEISADVOCATE881(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function NAMEISPOSITION327(address _nameId, address _id) external view returns (bool); //inject NONSTANDARD NAMING
function INITIALIZE405(address _id, address _advocateId, address _listenerId, address _speakerId) external returns (bool); //inject NONSTANDARD NAMING
function DETERMINEPOSITION456(address _sender, address _id) external view returns (uint256); //inject NONSTANDARD NAMING
}
contract TokenERC20 {
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals = 18;
// 18 decimals is the strongly suggested default, avoid changing it
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This generates a public event on the blockchain that will notify clients
event APPROVAL454(address indexed _owner, address indexed _spender, uint256 _value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (uint256 initialSupply, string memory tokenName, string memory tokenSymbol) public {
totalSupply = initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount
balanceOf[msg.sender] = totalSupply; // Give the creator all initial tokens
name = tokenName; // Set the name for display purposes
symbol = tokenSymbol; // Set the symbol for display purposes
}
function _TRANSFER285(address _from, address _to, uint _value) internal { //inject NONSTANDARD NAMING
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != address(0));
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
emit TRANSFER193(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
function TRANSFER874(address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
_TRANSFER285(msg.sender, _to, _value);
return true;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] -= _value;
_TRANSFER285(_from, _to, _value);
return true;
}
function APPROVE265(address _spender, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
allowance[msg.sender][_spender] = _value;
emit APPROVAL454(msg.sender, _spender, _value);
return true;
}
function APPROVEANDCALL88(address _spender, uint256 _value, bytes memory _extraData) public returns (bool success) { //inject NONSTANDARD NAMING
tokenRecipient spender = tokenRecipient(_spender);
if (APPROVE265(_spender, _value)) {
spender.RECEIVEAPPROVAL172(msg.sender, _value, address(this), _extraData);
return true;
}
}
function BURN239(uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] -= _value; // Subtract from the sender
totalSupply -= _value; // Updates totalSupply
emit BURN994(msg.sender, _value);
return true;
}
function BURNFROM882(address _from, uint256 _value) public returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] -= _value; // Subtract from the targeted balance
allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance
totalSupply -= _value; // Update totalSupply
emit BURN994(_from, _value);
return true;
}
}
contract TAO {
using SafeMath for uint256;
address public vaultAddress;
string public name; // the name for this TAO
address public originId; // the ID of the Name that created this TAO. If Name, it's the eth address
// TAO's data
string public datHash;
string public database;
string public keyValue;
bytes32 public contentId;
uint8 public typeId;
constructor (string memory _name,
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _vaultAddress
) public {
name = _name;
originId = _originId;
datHash = _datHash;
database = _database;
keyValue = _keyValue;
contentId = _contentId;
// Creating TAO
typeId = 0;
vaultAddress = _vaultAddress;
}
modifier ONLYVAULT404 { //inject NONSTANDARD NAMING
require (msg.sender == vaultAddress);
_;
}
function () external payable {
}
function TRANSFERETH144(address payable _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
_recipient.transfer(_amount);
return true;
}
function TRANSFERERC20563(address _erc20TokenAddress, address _recipient, uint256 _amount) public ONLYVAULT404 returns (bool) { //inject NONSTANDARD NAMING
TokenERC20 _erc20 = TokenERC20(_erc20TokenAddress);
_erc20.TRANSFER874(_recipient, _amount);
return true;
}
}
contract Name is TAO {
constructor (string memory _name, address _originId, string memory _datHash, string memory _database, string memory _keyValue, bytes32 _contentId, address _vaultAddress)
TAO (_name, _originId, _datHash, _database, _keyValue, _contentId, _vaultAddress) public {
// Creating Name
typeId = 1;
}
}
library AOLibrary {
using SafeMath for uint256;
uint256 constant private _multiplier_divisor322 = 10 ** 6; // 1000000 = 1 //inject NONSTANDARD NAMING
uint256 constant private _percentage_divisor262 = 10 ** 6; // 100% = 1000000 //inject NONSTANDARD NAMING
function ISTAO231(address _taoId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_taoId != address(0) && bytes(TAO(address(uint160(_taoId))).name()).length > 0 && TAO(address(uint160(_taoId))).originId() != address(0) && TAO(address(uint160(_taoId))).typeId() == 0);
}
function ISNAME781(address _nameId) public view returns (bool) { //inject NONSTANDARD NAMING
return (_nameId != address(0) && bytes(TAO(address(uint160(_nameId))).name()).length > 0 && Name(address(uint160(_nameId))).originId() != address(0) && Name(address(uint160(_nameId))).typeId() == 1);
}
function ISVALIDERC20TOKENADDRESS312(address _tokenAddress) public view returns (bool) { //inject NONSTANDARD NAMING
if (_tokenAddress == address(0)) {
return false;
}
TokenERC20 _erc20 = TokenERC20(_tokenAddress);
return (_erc20.totalSupply() >= 0 && bytes(_erc20.name()).length > 0 && bytes(_erc20.symbol()).length > 0);
}
function ISTHEAO403(address _sender, address _theAO, address _nameTAOPositionAddress) public view returns (bool) { //inject NONSTANDARD NAMING
return (_sender == _theAO ||
(
(ISTAO231(_theAO) || ISNAME781(_theAO)) &&
_nameTAOPositionAddress != address(0) &&
INameTAOPosition(_nameTAOPositionAddress).SENDERISADVOCATE978(_sender, _theAO)
)
);
}
function PERCENTAGE_DIVISOR218() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _percentage_divisor262;
}
function MULTIPLIER_DIVISOR371() public pure returns (uint256) { //inject NONSTANDARD NAMING
return _multiplier_divisor322;
}
function DEPLOYTAO162(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (TAO _tao) {
_tao = new TAO(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function DEPLOYNAME486(string memory _name, //inject NONSTANDARD NAMING
address _originId,
string memory _datHash,
string memory _database,
string memory _keyValue,
bytes32 _contentId,
address _nameTAOVaultAddress
) public returns (Name _myName) {
_myName = new Name(_name, _originId, _datHash, _database, _keyValue, _contentId, _nameTAOVaultAddress);
}
function CALCULATEWEIGHTEDMULTIPLIER712(uint256 _currentWeightedMultiplier, uint256 _currentPrimordialBalance, uint256 _additionalWeightedMultiplier, uint256 _additionalPrimordialAmount) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_currentWeightedMultiplier > 0) {
uint256 _totalWeightedIons = (_currentWeightedMultiplier.MUL710(_currentPrimordialBalance)).ADD540(_additionalWeightedMultiplier.MUL710(_additionalPrimordialAmount));
uint256 _totalIons = _currentPrimordialBalance.ADD540(_additionalPrimordialAmount);
return _totalWeightedIons.DIV595(_totalIons);
} else {
return _additionalWeightedMultiplier;
}
}
function CALCULATEPRIMORDIALMULTIPLIER760(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 multiplier = (_multiplier_divisor322.SUB853(_multiplier_divisor322.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier));
return multiplier.DIV595(_multiplier_divisor322);
} else {
return 0;
}
}
function CALCULATENETWORKBONUSPERCENTAGE146(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
if (_purchaseAmount > 0 && _purchaseAmount <= _totalPrimordialMintable.SUB853(_totalPrimordialMinted)) {
uint256 temp = _totalPrimordialMinted.ADD540(_purchaseAmount.DIV595(2));
uint256 bonusPercentage = (_percentage_divisor262.SUB853(_percentage_divisor262.MUL710(temp).DIV595(_totalPrimordialMintable))).MUL710(_startingMultiplier.SUB853(_endingMultiplier)).DIV595(_percentage_divisor262);
return bonusPercentage;
} else {
return 0;
}
}
function CALCULATENETWORKBONUSAMOUNT621(uint256 _purchaseAmount, uint256 _totalPrimordialMintable, uint256 _totalPrimordialMinted, uint256 _startingMultiplier, uint256 _endingMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 bonusPercentage = CALCULATENETWORKBONUSPERCENTAGE146(_purchaseAmount, _totalPrimordialMintable, _totalPrimordialMinted, _startingMultiplier, _endingMultiplier);
uint256 networkBonus = bonusPercentage.MUL710(_purchaseAmount).DIV595(_percentage_divisor262);
return networkBonus;
}
function CALCULATEMAXIMUMBURNAMOUNT319(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _maximumMultiplier) public pure returns (uint256) { //inject NONSTANDARD NAMING
return (_maximumMultiplier.MUL710(_primordialBalance).SUB853(_primordialBalance.MUL710(_currentWeightedMultiplier))).DIV595(_maximumMultiplier);
}
function CALCULATEMULTIPLIERAFTERBURN888(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToBurn) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.SUB853(_amountToBurn));
}
function CALCULATEMULTIPLIERAFTERCONVERSION91(uint256 _primordialBalance, uint256 _currentWeightedMultiplier, uint256 _amountToConvert) public pure returns (uint256) { //inject NONSTANDARD NAMING
return _primordialBalance.MUL710(_currentWeightedMultiplier).DIV595(_primordialBalance.ADD540(_amountToConvert));
}
function NUMDIGITS612(uint256 number) public pure returns (uint8) { //inject NONSTANDARD NAMING
uint8 digits = 0;
while(number != 0) {
number = number.DIV595(10);
digits++;
}
return digits;
}
}
contract TheAO {
address public theAO;
address public nameTAOPositionAddress;
// Check whether an address is whitelisted and granted access to transact
// on behalf of others
mapping (address => bool) public whitelist;
constructor() public {
theAO = msg.sender;
}
modifier INWHITELIST24() { //inject NONSTANDARD NAMING
require (whitelist[msg.sender] == true);
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public { //inject NONSTANDARD NAMING
require (msg.sender == theAO);
require (_account != address(0));
whitelist[_account] = _whitelist;
}
}
contract TAOCurrency is TheAO {
using SafeMath for uint256;
// Public variables of the contract
string public name;
string public symbol;
uint8 public decimals;
// To differentiate denomination of TAO Currency
uint256 public powerOfTen;
uint256 public totalSupply;
// This creates an array with all balances
// address is the address of nameId, not the eth public address
mapping (address => uint256) public balanceOf;
// This generates a public event on the blockchain that will notify clients
// address is the address of TAO/Name Id, not eth public address
event TRANSFER193(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
// This notifies clients about the amount burnt
// address is the address of TAO/Name Id, not eth public address
event BURN994(address indexed from, uint256 value); //inject NONSTANDARD NAMING
constructor (string memory _name, string memory _symbol, address _nameTAOPositionAddress) public {
name = _name; // Set the name for display purposes
symbol = _symbol; // Set the symbol for display purposes
powerOfTen = 0;
decimals = 0;
SETNAMETAOPOSITIONADDRESS170(_nameTAOPositionAddress);
}
modifier ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (AOLibrary.ISTHEAO403(msg.sender, theAO, nameTAOPositionAddress));
_;
}
modifier ISNAMEORTAO154(address _id) { //inject NONSTANDARD NAMING
require (AOLibrary.ISNAME781(_id) || AOLibrary.ISTAO231(_id));
_;
}
function TRANSFEROWNERSHIP920(address _theAO) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_theAO != address(0));
theAO = _theAO;
}
function SETWHITELIST120(address _account, bool _whitelist) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_account != address(0));
whitelist[_account] = _whitelist;
}
function SETNAMETAOPOSITIONADDRESS170(address _nameTAOPositionAddress) public ONLYTHEAO376 { //inject NONSTANDARD NAMING
require (_nameTAOPositionAddress != address(0));
nameTAOPositionAddress = _nameTAOPositionAddress;
}
function TRANSFERFROM282(address _from, address _to, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) ISNAMEORTAO154(_to) returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER285(_from, _to, _value);
return true;
}
function MINT678(address target, uint256 mintedAmount) public INWHITELIST24 ISNAMEORTAO154(target) returns (bool) { //inject NONSTANDARD NAMING
_MINT887(target, mintedAmount);
return true;
}
function WHITELISTBURNFROM289(address _from, uint256 _value) public INWHITELIST24 ISNAMEORTAO154(_from) returns (bool success) { //inject NONSTANDARD NAMING
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the targeted balance
totalSupply = totalSupply.SUB853(_value); // Update totalSupply
emit BURN994(_from, _value);
return true;
}
function _TRANSFER285(address _from, address _to, uint256 _value) internal { //inject NONSTANDARD NAMING
require (_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Check if the sender has enough
require (balanceOf[_to].ADD540(_value) >= balanceOf[_to]); // Check for overflows
uint256 previousBalances = balanceOf[_from].ADD540(balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].SUB853(_value); // Subtract from the sender
balanceOf[_to] = balanceOf[_to].ADD540(_value); // Add the same to the recipient
emit TRANSFER193(_from, _to, _value);
assert(balanceOf[_from].ADD540(balanceOf[_to]) == previousBalances);
}
function _MINT887(address target, uint256 mintedAmount) internal { //inject NONSTANDARD NAMING
balanceOf[target] = balanceOf[target].ADD540(mintedAmount);
totalSupply = totalSupply.ADD540(mintedAmount);
emit TRANSFER193(address(0), address(this), mintedAmount);
emit TRANSFER193(address(this), target, mintedAmount);
}
}
contract PathosGiga is TAOCurrency {
constructor(string memory _name, string memory _symbol, address _nameTAOPositionAddress)
TAOCurrency(_name, _symbol, _nameTAOPositionAddress) public {
powerOfTen = 9;
decimals = 9;
}
} | inject NONSTANDARD NAMING | function NUMDIGITS612(uint256 number) public pure returns (uint8) { | 13,026,387 |
pragma solidity ^0.5.0;
import "./interfaces/SnowflakeInterface.sol";
import "./interfaces/IdentityRegistryInterface.sol";
/**
* @title Ice Protocol
* @author Harsh Rajat
* @notice Create Protocol Less File Storage, Grouping, Hassle free Encryption / Decryption and Stamping using Snowflake
* @dev This Contract forms File Storage / Stamping / Encryption part of Hydro Protocols
*/
contract Ice {
/* ***************
* DEFINE ENUM
*************** */
enum NoticeType {info, warning, error}
enum GlobalItemProp {sharedTo, stampedTo}
/* ***************
* DEFINE VARIABLES
*************** */
/* for each file stored, ensure they can be retrieved publicly.
* associationIndex starts at 0 and will always increment
* given an associationIndex, any file can be retrieved.
*/
mapping (uint => mapping(uint => Association)) globalItems;
uint public globalIndex1; // store the first index of association to retrieve files
uint public globalIndex2; // store the first index of association to retrieve files
/* for each user (EIN), look up the Transitioon State they have
* stored on a given index.
*/
mapping (uint => AtomicityState) public atomicity;
/* for each user (EIN), look up the file they have
* stored on a given index.
*/
mapping (uint => mapping(uint => File)) files;
mapping (uint => mapping(uint => SortOrder)) public fileOrder; // Store round robin order of files
mapping (uint => uint) public fileCount; // store the maximum file count reached to provide looping functionality
/* for each user (EIN), look up the group they have
* stored on a given index. Default group 0 indicates
* root folder
*/
mapping (uint => mapping(uint => Group)) groups;
mapping (uint => mapping(uint => SortOrder)) public groupOrder; // Store round robin order of group
mapping (uint => uint) public groupCount; // store the maximum group count reached to provide looping functionality
/* for each user (EIN), look up the incoming transfer request
* stored on a given index.
*/
mapping (uint => mapping(uint => Association)) transfers;
mapping (uint => mapping(uint => SortOrder)) public transferOrder; // Store round robin order of transfers
mapping (uint => uint) public transferIndex; // store the maximum transfer request count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public shares;
mapping (uint => mapping(uint => SortOrder)) public shareOrder; // Store round robin order of sharing
mapping (uint => uint) public shareCount; // store the maximum shared items count reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public stampings;
mapping (uint => mapping(uint => SortOrder)) public stampingOrder; // Store round robin order of stamping
mapping (uint => uint) public stampingCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), look up the incoming sharing files
* stored on a given index.
*/
mapping (uint => mapping(uint => GlobalRecord)) public stampingsRequest;
mapping (uint => mapping(uint => SortOrder)) public stampingsRequestOrder; // Store round robin order of stamping requests
mapping (uint => uint) public stampingsRequestCount; // store the maximum file index reached to provide looping functionality
/* for each user (EIN), have a whitelist and blacklist
* association which can handle certain functions automatically.
*/
mapping (uint => mapping(uint => bool)) public whitelist;
mapping (uint => mapping(uint => bool)) public blacklist;
/* for referencing SnowFlake for Identity Registry (ERC-1484).
*/
SnowflakeInterface public snowflake;
IdentityRegistryInterface public identityRegistry;
/* ***************
* DEFINE STRUCTURES
*************** */
/* To define ownership info of a given Item.
*/
struct ItemOwner {
uint EIN; // the EIN of the owner
uint index; // the key at which the item is stored
}
/* To define global file association with EIN
* Combining EIN and itemIndex and properties will give access to
* item data.
*/
struct Association {
ItemOwner ownerInfo; // To Store Iteminfo
bool isFile; // whether the Item is File or Group
bool isHidden; // Whether the item is hidden or not
bool isStamped; // Whether the item is stamped atleast once
bool deleted; // whether the association is deleted
uint8 sharedToCount; // the count of sharing
uint8 stampedToCount; // the count of stamping
mapping (uint8 => ItemOwner) sharedTo; // to contain share to
mapping (uint8 => ItemOwner) stampedTo; // to have stamping reqs
}
struct GlobalRecord {
uint i1; // store associated global index 1 for access
uint i2; // store associated global index 2 for access
}
/* To define File structure of all stored files
*/
struct File {
// File Meta Data
GlobalRecord rec; // store the association in global record
uint fileOwner; // store file owner EIN
// File Properties
uint8 protocol; // store protocol of the file stored | 0 is URL, 1 is IPFS
bytes protocolMeta; // store metadata of the protocol
string name; // the name of the file
string hash; // store the hash of the file for verification | 0x000 for deleted files
bytes8 ext; // store the extension of the file
uint32 timestamp; // to store the timestamp of the block when file is created
// File Properties - Encryption Properties
bool encrypted; // whether the file is encrypted
mapping (address => string) encryptedHash; // Maps Individual address to the stored hash
// File Group Properties
uint associatedGroupIndex;
uint associatedGroupFileIndex;
// File Transfer Properties
mapping (uint => uint) transferHistory; // To maintain histroy of transfer of all EIN
uint transferCount; // To maintain the transfer count for mapping
uint transferEIN; // To record EIN of the user to whom trasnfer is inititated
uint transferIndex; // To record the transfer specific index of the transferee
bool markedForTransfer; // Mark the file as transferred
}
/* To connect Files in linear grouping,
* sort of like a folder, 0 or default grooupID is root
*/
struct Group {
GlobalRecord rec; // store the association in global record
string name; // the name of the Group
mapping (uint => SortOrder) groupFilesOrder; // the order of files in the current group
uint groupFilesCount; // To keep the count of group files
}
/* To define the order required to have double linked list
*/
struct SortOrder {
uint next; // the next ID of the order
uint prev; // the prev ID of the order
uint pointerID; // what it should point to in the mapping
bool active; // whether the node is active or not
}
/* To define state and flags for Individual things,
* used in cases where state change should be atomic
*/
struct AtomicityState {
bool lockFiles;
bool lockGroups;
bool lockTransfers;
bool lockSharings;
}
/* ***************
* DEFINE EVENTS
*************** */
// When File is created
event FileCreated(
uint EIN,
uint fileIndex,
string fileName
);
// When File is renamed
event FileRenamed(
uint EIN,
uint fileIndex,
string fileName
);
// When File is moved
event FileMoved(
uint EIN,
uint fileIndex,
uint groupIndex,
uint groupFileIndex
);
// When File is deleted
event FileDeleted(
uint EIN,
uint fileIndex
);
// When Group is created
event GroupCreated(
uint EIN,
uint groupIndex,
string groupName
);
// When Group is renamed
event GroupRenamed(
uint EIN,
uint groupIndex,
string groupName
);
// When Group Status is changed
event GroupDeleted(
uint EIN,
uint groupIndex,
uint groupReplacedIndex
);
// When Transfer is initiated from owner
event FileTransferInitiated(
uint indexed EIN,
uint indexed transfereeEIN,
uint indexed fileID
);
// When whitelist is updated
event AddedToWhitelist(
uint EIN,
uint recipientEIN
);
event RemovedFromWhitelist(
uint EIN,
uint recipientEIN
);
// When blacklist is updated
event AddedToBlacklist(
uint EIN,
uint recipientEIN
);
event RemovedFromBlacklist(
uint EIN,
uint recipientEIN
);
// Notice Events
event Notice(
uint indexed EIN,
string indexed notice,
uint indexed statusType
);
/* ***************
* DEFINE CONSTRUCTORS AND RELATED FUNCTIONS
*************** */
// CONSTRUCTOR / FUNCTIONS
address snowflakeAddress = 0xcF1877AC788a303cAcbbfE21b4E8AD08139f54FA; //0xB536a9b68e7c1D2Fd6b9851Af2F955099B3A59a9; // For local use
constructor (/*address snowflakeAddress*/) public {
snowflake = SnowflakeInterface(snowflakeAddress);
identityRegistry = IdentityRegistryInterface(snowflake.identityRegistryAddress());
}
/* ***************
* DEFINE CONTRACT FUNCTIONS
*************** */
// 1. GLOBAL ITEMS FUNCTIONS
/**
* @dev Function to get global items
* @param _index1 is the first index of item
* @param _index2 is the second index of item
*/
function getGlobalItems(uint _index1, uint _index2)
external view
returns (uint ownerEIN, uint itemRecord, bool isFile, bool isHidden, bool deleted, uint sharedToCount, uint stampingReqsCount) {
ownerEIN = globalItems[_index1][_index2].ownerInfo.EIN;
itemRecord = globalItems[_index1][_index2].ownerInfo.index;
isFile = globalItems[_index1][_index2].isFile;
isHidden = globalItems[_index1][_index2].isHidden;
deleted = globalItems[_index1][_index2].deleted;
sharedToCount = globalItems[_index1][_index2].sharedToCount;
stampingReqsCount = globalItems[_index1][_index2].stampedToCount;
}
/**
* @dev Function to get info of mapping to user for a specific global item
* @param _index1 is the first index of global item
* @param _index2 is the second index of global item
* @param _ofType indicates the type. 0 - shares, 1 - transferReqs
* @param _mappedIndex is the index
* @return mappedToEIN is the user (EIN)
* @return atIndex is the specific index in question
*/
function getGlobalItemsMapping(uint _index1, uint _index2, uint8 _ofType, uint8 _mappedIndex)
external view
returns (uint mappedToEIN, uint atIndex) {
ItemOwner memory _mappedItem;
// Allocalte based on type.
if (_ofType == uint8(GlobalItemProp.sharedTo)) {
_mappedItem = globalItems[_index1][_index2].sharedTo[_mappedIndex];
}
else if (_ofType == uint8(GlobalItemProp.stampedTo)) {
_mappedItem = globalItems[_index1][_index2].stampedTo[_mappedIndex];
}
mappedToEIN = _mappedItem.EIN;
atIndex = _mappedItem.index;
}
/**
* @dev Private Function to get global item via the record struct
* @param _rec is the GlobalRecord Struct
*/
function _getGlobalItemViaRecord(GlobalRecord memory _rec)
internal pure
returns (uint _i1, uint _i2) {
_i1 = _rec.i1;
_i2 = _rec.i2;
}
/**
* @dev Private Function to add item to global items
* @param _ownerEIN is the EIN of global items
* @param _itemIndex is the index at which the item exists on the user mapping
* @param _isFile indicates if the item is file or group
* @param _isHidden indicates if the item has is hiddden or not
*/
function _addItemToGlobalItems(uint _ownerEIN, uint _itemIndex, bool _isFile, bool _isHidden, bool _isStamped)
internal
returns (uint i1, uint i2){
// Increment global Item (0, 0 is always reserved | Is User Avatar)
globalIndex1 = globalIndex1;
globalIndex2 = globalIndex2 + 1;
if (globalIndex2 == 0) {
// This is loopback, Increment newIndex1
globalIndex1 = globalIndex1 + 1;
require (
globalIndex1 > 0,
"Storage Full"
);
}
// Add item to global item, no stiching it
globalItems[globalIndex1][globalIndex2] = Association (
ItemOwner (
_ownerEIN, // Owner EIN
_itemIndex // Item stored at what index for that EIN
),
_isFile, // Item is file or group
_isHidden, // whether stamping is initiated or not
_isStamped, // whether file is stamped or not
false, // Item is deleted or still exists
0, // the count of shared EINs
0 // the count of stamping requests
);
i1 = globalIndex1;
i2 = globalIndex2;
}
/**
* @dev Private Function to delete a global items
* @param _rec is the GlobalRecord Struct
*/
function _deleteGlobalRecord(GlobalRecord memory _rec)
internal {
globalItems[_rec.i1][_rec.i2].deleted = true;
}
function _getEINsForGlobalItemsMapping(mapping (uint8 => ItemOwner) storage _relatedMapping, uint8 _count)
internal view
returns (uint[32] memory EINs){
uint8 i = 0;
while (_count != 0) {
EINs[i] = _relatedMapping[_count].EIN;
_count--;
}
}
/**
* @dev Private Function to find the relevant mapping index of item mapped in non owner
* @param _relatedMapping is the passed pointer of relative mapping of global item Association
* @param _count is the count of relative mapping of global item Association
* @param _searchForEIN is the non-owner EIN to search
* @return mappedIndex is the index which is where the relative mapping points to for those items
*/
function _findGlobalItemsMapping(mapping (uint8 => ItemOwner) storage _relatedMapping, uint8 _count, uint256 _searchForEIN)
internal view
returns (uint8 mappedIndex) {
// Logic
mappedIndex = 0;
while (_count != 0) {
if (_relatedMapping[_count].EIN == _searchForEIN) {
mappedIndex = _count;
_count = 1;
}
_count--;
}
}
/**
* @dev Private Function to add to global items mapping
* @param _rec is the Global Record
* @param _ofType is the type of global item properties
* @param _mappedItem is the non-owner mapping of stored item
*/
function _addToGlobalItemsMapping(GlobalRecord storage _rec, uint8 _ofType, ItemOwner memory _mappedItem)
internal
returns (uint8 _newCount) {
// Logic
// Allocalte based on type.
if (_ofType == uint8(GlobalItemProp.sharedTo)) {
_newCount = globalItems[_rec.i1][_rec.i2].sharedToCount + 1;
globalItems[_rec.i1][_rec.i2].sharedTo[_newCount] = _mappedItem;
}
else if (_ofType == uint8(GlobalItemProp.stampedTo)) {
_newCount = globalItems[_rec.i1][_rec.i2].stampedToCount + 1;
globalItems[_rec.i1][_rec.i2].stampedTo[_newCount] = _mappedItem;
}
globalItems[_rec.i1][_rec.i2].stampedToCount = _newCount;
require (
(_newCount > globalItems[_rec.i1][_rec.i2].stampedToCount),
"Global Mapping Full"
);
}
/**
* @dev Private Function to remove from global items mapping
* @param _rec is the Global Record
* @param _mappedIndex is the non-owner mapping of stored item
*/
function _removeFromGlobalItemsMapping(GlobalRecord memory _rec, uint8 _mappedIndex)
internal
returns (uint8 _newCount) {
// Logic
// Just swap and deduct
_newCount = globalItems[_rec.i1][_rec.i2].sharedToCount;
globalItems[_rec.i1][_rec.i2].sharedTo[_mappedIndex] = globalItems[_rec.i1][_rec.i2].sharedTo[_newCount];
require (
(_newCount > 0),
"Invalid Global Mapping"
);
_newCount = _newCount - 1;
globalItems[_rec.i1][_rec.i2].sharedToCount = _newCount;
}
// 2. FILE FUNCTIONS
/**
* @dev Function to get all the files of an EIN
* @param _ein is the owner EIN
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
*/
function getFileIndexes(uint _ein, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory fileIndexes) {
fileIndexes = _getIndexes(fileOrder[_ein], _seedPointer, _limit, _asc);
}
/**
* @dev Function to get file info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFile(uint _ein, uint _fileIndex)
external view
returns (uint8 protocol, bytes memory protocolMeta, string memory name, string memory hash, bytes8 ext, uint32 timestamp, bool encrypted, uint associatedGroupIndex, uint associatedGroupFileIndex) {
// Logic
protocol = files[_ein][_fileIndex].protocol;
protocolMeta = files[_ein][_fileIndex].protocolMeta;
name = files[_ein][_fileIndex].name;
hash = files[_ein][_fileIndex].hash;
ext = files[_ein][_fileIndex].ext;
timestamp = files[_ein][_fileIndex].timestamp;
encrypted = files[_ein][_fileIndex].encrypted;
associatedGroupIndex = files[_ein][_fileIndex].associatedGroupIndex;
associatedGroupFileIndex = files[_ein][_fileIndex].associatedGroupFileIndex;
}
/**
* @dev Function to get file tranfer info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
*/
function getFileTransferInfo(uint _ein, uint _fileIndex)
external view
returns (uint transCount, uint transEIN, uint transIndex, bool forTrans) {
// Logic
transCount = files[_ein][_fileIndex].transferCount;
transEIN = files[_ein][_fileIndex].transferEIN;
transIndex = files[_ein][_fileIndex].transferIndex;
forTrans = files[_ein][_fileIndex].markedForTransfer;
}
/**
* @dev Function to get file tranfer owner info of an EIN
* @param _ein is the owner EIN
* @param _fileIndex is index of the file
* @param _transferIndex is index to poll
*/
function getFileTransferOwners(uint _ein, uint _fileIndex, uint _transferIndex)
external view
returns (uint recipientEIN) {
recipientEIN = files[_ein][_fileIndex].transferHistory[_transferIndex];
}
/**
* @dev Function to add File
* @param _protocol is the protocol used
* @param _protocolMeta is the metadata used by the protocol if any
* @param _name is the name of the file
* @param _hash is the hash of the stored file
* @param _ext is the extension of the file
* @param _encrypted defines if the file is encrypted or not
* @param _encryptedHash defines the encrypted public key password for the sender address
* @param _groupIndex defines the index of the group of file
*/
function addFile(uint8 _protocol, bytes memory _protocolMeta, string memory _name, string memory _hash, bytes8 _ext, bool _encrypted, string memory _encryptedHash, uint _groupIndex)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check constraints
_isValidItem(_groupIndex, groupCount[ein]);
_isFilesOpLocked(ein);
_isGrpsOpLocked(ein);
// Set File & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
// Add to Global Items
uint index1;
uint index2;
(index1, index2) = _addItemToGlobalItems(ein, (fileCount[ein] + 1), true, false, false);
// Add file to group
groups[ein][_groupIndex].groupFilesCount = _addFileToGroup(ein, _groupIndex, (fileCount[ein] + 1));
// Finally create the file it to User (EIN)
files[ein][(fileCount[ein] + 1)] = File (
GlobalRecord(
index1, // Global Index 1
index2 // Global Index 2
),
ein, // File Owner
_protocol, // Protocol For Interpretation
_protocolMeta, // Serialized Hex of Array
_name, // Name of File
_hash, // Hash of File
_ext, // Extension of File
uint32(now), // Timestamp of File
_encrypted, // File Encyption
_groupIndex, // Store the group index
groups[ein][_groupIndex].groupFilesCount, // Store the group specific file index
1, // Transfer Count, treat creation as a transfer count
0, // Transfer EIN
0, // Transfer Index for Transferee
false // File is not flagged for Transfer
);
// To map encrypted password
files[ein][(fileCount[ein] + 1)].encryptedHash[msg.sender] = _encryptedHash;
// To map transfer history
files[ein][(fileCount[ein] + 1)].transferHistory[0] = ein;
// Add to Stitch Order & Increment index
fileCount[ein] = _addToSortOrder(fileOrder[ein], fileCount[ein], 0);
// Trigger Event
emit FileCreated(ein, (fileCount[ein] + 1), _name);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to change File Name
* @param _fileIndex is the index where file is stored
* @param _name is the name of stored file
*/
function changeFileName(uint _fileIndex, string calldata _name)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
files[ein][_fileIndex].name = _name;
// Trigger Event
emit FileRenamed(ein, _fileIndex, _name);
}
/**
* @dev Function to move file to another group
* @param _fileIndex is the index where file is stored
* @param _newGroupIndex is the index of the new group where file has to be moved
*/
function moveFileToGroup(uint _fileIndex, uint _newGroupIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isValidGrpOrder(ein, _newGroupIndex); // Check if the new group is valid
_isUnstampedItem(files[ein][_fileIndex].rec); // Check if the file is unstamped, can't move a stamped file
_isUnstampedItem(groups[ein][files[ein][_fileIndex].associatedGroupIndex].rec); // Check if the current group is unstamped, can't move a file from stamped group
_isUnstampedItem(groups[ein][_newGroupIndex].rec); // Check if the new group is unstamped, can't move a file from stamped group
_isFilesOpLocked(ein); // Check if the files operations are not locked for the user
_isGrpsOpLocked(ein); // Check if the groups operations are not locked for the user
// Set Files & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
uint GFIndex = _remapFileToGroup(ein, files[ein][_fileIndex].associatedGroupIndex, files[ein][_fileIndex].associatedGroupFileIndex, _newGroupIndex);
// Trigger Event
emit FileMoved(ein, _fileIndex, _newGroupIndex, GFIndex);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to delete file of the owner
* @param _fileIndex is the index where file is stored
*/
function deleteFile(uint _fileIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isUnstampedItem(files[ein][_fileIndex].rec); // Check if the file is unstamped, can't delete a stamped file
// Set Files & Group Atomicity
atomicity[ein].lockFiles = true;
atomicity[ein].lockGroups = true;
_deleteFileAnyOwner(ein, _fileIndex);
// Reset Files & Group Atomicity
atomicity[ein].lockFiles = false;
atomicity[ein].lockGroups = false;
}
/**
* @dev Function to delete file of any EIN
* @param _ein is the owner EIN
* @param _fileIndex is the index where file is stored
*/
function _deleteFileAnyOwner(uint _ein, uint _fileIndex)
internal {
// Check Restrictions
_isValidItem(_fileIndex, fileCount[_ein]);
_isValidGrpOrder(_ein, files[_ein][_fileIndex].associatedGroupIndex);
// Get current Index, Stich check previous index so not required to recheck
uint currentIndex = fileCount[_ein];
// Remove item from sharing of other users
_removeAllShares(files[_ein][_fileIndex].rec);
// Deactivate From Global Items
_deleteGlobalRecord(files[_ein][_fileIndex].rec);
// Remove from Group which holds the File
_removeFileFromGroup(_ein, files[_ein][_fileIndex].associatedGroupIndex, files[_ein][_fileIndex].associatedGroupFileIndex);
// Swap File
files[_ein][_fileIndex] = files[_ein][currentIndex];
fileCount[_ein] = _stichSortOrder(fileOrder[_ein], _fileIndex, currentIndex, 0);
// Delete the latest group now
delete (files[_ein][currentIndex]);
// Trigger Event
emit FileDeleted(_ein, _fileIndex);
}
/**
* @dev Private Function to add file to a group
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user, 0 is reserved for root
* @param _fileIndex is the index of the file belonging to that user
*/
function _addFileToGroup(uint _ein, uint _groupIndex, uint _fileIndex)
internal
returns (uint) {
// Add File to a group is just adding the index of that file
uint currentIndex = groups[_ein][_groupIndex].groupFilesCount;
groups[_ein][_groupIndex].groupFilesCount = _addToSortOrder(groups[_ein][_groupIndex].groupFilesOrder, currentIndex, _fileIndex);
// Map group index and group order index in file
files[_ein][_fileIndex].associatedGroupIndex = _groupIndex;
files[_ein][_fileIndex].associatedGroupFileIndex = groups[_ein][_groupIndex].groupFilesCount;
return groups[_ein][_groupIndex].groupFilesCount;
}
/**
* @dev Private Function to remove file from a group
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user
* @param _groupFileOrderIndex is the index of the file order within that group
*/
function _removeFileFromGroup(uint _ein, uint _groupIndex, uint _groupFileOrderIndex)
internal {
uint maxIndex = groups[_ein][_groupIndex].groupFilesCount;
uint pointerID = groups[_ein][_groupIndex].groupFilesOrder[maxIndex].pointerID;
groups[_ein][_groupIndex].groupFilesCount = _stichSortOrder(groups[_ein][_groupIndex].groupFilesOrder, _groupFileOrderIndex, maxIndex, pointerID);
}
/**
* @dev Private Function to remap file from one group to another
* @param _ein is the EIN of the intended user
* @param _groupIndex is the index of the group belonging to that user, 0 is reserved for root
* @param _groupFileOrderIndex is the index of the file order within that group
* @param _newGroupIndex is the index of the new group belonging to that user
*/
function _remapFileToGroup(uint _ein, uint _groupIndex, uint _groupFileOrderIndex, uint _newGroupIndex)
internal
returns (uint) {
// Get file index for the Association
uint fileIndex = groups[_ein][_groupIndex].groupFilesOrder[_groupFileOrderIndex].pointerID;
// Remove File from existing group
_removeFileFromGroup(_ein, _groupIndex, _groupFileOrderIndex);
// Add File to new group
return _addFileToGroup(_ein, _newGroupIndex, fileIndex);
}
// 4. GROUP FILES FUNCTIONS
/**
* @dev Function to get all the files of an EIN associated with a group
* @param _ein is the owner EIN
* @param _groupIndex is the index where group is stored
* @param _seedPointer is the seed of the order from which it should begin
* @param _limit is the limit of file indexes requested
* @param _asc is the order by which the files will be presented
*/
function getGroupFileIndexes(uint _ein, uint _groupIndex, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory groupFileIndexes) {
return _getIndexes(groups[_ein][_groupIndex].groupFilesOrder, _seedPointer, _limit, _asc);
}
// 4. GROUP FUNCTIONS
/**
* @dev Function to return group info for an EIN
* @param _ein the EIN of the user
* @param _groupIndex the index of the group
* @return index is the index of the group
* @return name is the name associated with the group
*/
function getGroup(uint _ein, uint _groupIndex)
external view
returns (uint index, string memory name) {
// Check constraints
_isValidItem(_groupIndex, groupCount[_ein]);
// Logic flow
index = _groupIndex;
if (_groupIndex == 0) {
name = "Root";
}
else {
name = groups[_ein][_groupIndex].name;
}
}
/**
* @dev Function to return group indexes used to retrieve info about group
* @param _ein the EIN of the user
* @param _seedPointer is the pointer (index) of the order mapping
* @param _limit is the number of indexes to return, capped at 20
* @param _asc is the order of group indexes in Ascending or Descending order
* @return groupIndexes the indexes of the groups associated with the ein in the preferred order
*/
function getGroupIndexes(uint _ein, uint _seedPointer, uint16 _limit, bool _asc)
external view
returns (uint[20] memory groupIndexes) {
groupIndexes = _getIndexes(groupOrder[_ein], _seedPointer, _limit, _asc);
}
/**
* @dev Create a new Group for the user
* @param _groupName describes the name of the group
*/
function createGroup(string memory _groupName)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isGrpsOpLocked(ein);
// Set Group Atomicity
atomicity[ein].lockGroups = true;
// Check if this is unitialized, if so, initialize it, reserved value of 0 is skipped as that's root
uint currentGroupIndex = groupCount[ein];
uint nextGroupIndex = currentGroupIndex + 1;
// Add to Global Items
uint index1;
uint index2;
(index1, index2) = _addItemToGlobalItems(ein, nextGroupIndex, false, false, false);
// Assign it to User (EIN)
groups[ein][nextGroupIndex] = Group(
GlobalRecord(
index1, // Global Index 1
index2 // Global Index 2
),
_groupName, //name of Group
0 // The group file count
);
// Add to Stitch Order & Increment index
groupCount[ein] = _addToSortOrder(groupOrder[ein], currentGroupIndex, 0);
// Trigger Event
emit GroupCreated(ein, nextGroupIndex, _groupName);
// Reset Group Atomicity
atomicity[ein].lockGroups = false;
}
/**
* @dev Rename an existing Group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
* @param _groupName describes the new name of the group
*/
function renameGroup(uint _groupIndex, string calldata _groupName)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNonReservedItem(_groupIndex);
_isValidItem(_groupIndex, groupCount[ein]);
// Replace the group name
groups[ein][_groupIndex].name = _groupName;
// Trigger Event
emit GroupRenamed(ein, _groupIndex, _groupName);
}
/**
* @dev Delete an existing group for the user / ein
* @param _groupIndex describes the associated index of the group for the user / ein
*/
function deleteGroup(uint _groupIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isGroupFileFree(ein, _groupIndex); // Check that Group contains no Files
_isNonReservedItem(_groupIndex);
_isValidItem(_groupIndex, groupCount[ein]);
_isGrpsOpLocked(ein);
// Set Group Atomicity
atomicity[ein].lockGroups = true;
// Check if the group exists or not
uint currentGroupIndex = groupCount[ein];
// Remove item from sharing of other users
_removeAllShares(groups[ein][_groupIndex].rec);
// Deactivate from global record
_deleteGlobalRecord(groups[ein][_groupIndex].rec);
// Swap Index mapping & remap the latest group ID if this is not the last group
groups[ein][_groupIndex] = groups[ein][currentGroupIndex];
groupCount[ein] = _stichSortOrder(groupOrder[ein], _groupIndex, currentGroupIndex, 0);
// Delete the latest group now
delete (groups[ein][currentGroupIndex]);
// Trigger Event
emit GroupDeleted(ein, _groupIndex, currentGroupIndex);
// Reset Group Atomicity
atomicity[ein].lockGroups = false;
}
// 5. SHARING FUNCTIONS
/**
* @dev Function to share an item to other users, always called by owner of the Item
* @param _toEINs are the array of EINs which the item should be shared to
* @param _itemIndex is the index of the item to be shared to
* @param _isFile indicates if the item is file or group
*/
function shareItemToEINs(uint[] calldata _toEINs, uint _itemIndex, bool _isFile)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// Set Lock
atomicity[ein].lockSharings = true;
// Warn: Unbounded Loop
for (uint i=0; i < _toEINs.length; i++) {
// call share for each EIN you want to share with
// Since its multiple share, don't put require blacklist but ignore the share
// if owner of the file is in blacklist
if (blacklist[_toEINs[i]][ein] == false) {
_shareItemToEIN(ein, _toEINs[i], _itemIndex, _isFile);
}
}
// Reset Lock
atomicity[ein].lockSharings = false;
}
/**
* @dev Function to remove a shared item from the multiple user's mapping, always called by owner of the Item
* @param _toEINs are the EINs to which the item should be removed from sharing
* @param _itemIndex is the index of the item on the owner's mapping
* @param _isFile indicates if the item is file or group
*/
function removeShareFromEINs(uint[32] memory _toEINs, uint _itemIndex, bool _isFile)
public {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// Set Lock
atomicity[ein].lockSharings = true;
// Get reference of global item record
GlobalRecord memory rec;
if (_isFile == true) {
// is file
rec = files[ein][_itemIndex].rec;
}
else {
// is group
rec = groups[ein][_itemIndex].rec;
}
// Adjust for valid loop
uint count = globalItems[rec.i1][rec.i2].sharedToCount;
for (uint i=0; i < count; i++) {
// call share for each EIN you want to remove the share with
_removeShareFromEIN(_toEINs[i], rec, globalItems[rec.i1][rec.i2]);
}
// Reset Lock
atomicity[ein].lockSharings = false;
}
/**
* @dev Function to remove shared item by the non owner of that item
* @param _itemIndex is the index of the item in shares
*/
function removeSharingItemNonOwner(uint _itemIndex)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Logic
GlobalRecord memory rec = shares[ein][_itemIndex];
_removeShareFromEIN(ein, shares[ein][_itemIndex], globalItems[rec.i1][rec.i2]); // Handles atomicity and other Restrictions
}
/**
* @dev Private Function to share an item to Individual user
* @param _ein is the EIN to of the owner
* @param _toEIN is the EIN to which the item should be shared to
* @param _itemIndex is the index of the item to be shared to
* @param _isFile indicates if the item is file or group
*/
function _shareItemToEIN(uint _ein, uint _toEIN, uint _itemIndex, bool _isFile)
internal {
// Check Restrictions
_isNonOwner(_toEIN); // Recipient EIN should not be the owner
// Logic
// Set Lock
atomicity[_toEIN].lockSharings = true;
// Create Sharing
uint curIndex = shareCount[_toEIN];
uint nextIndex = curIndex + 1;
// no need to require as share can be multiple
// and thus should not hamper other sharings
if (nextIndex > curIndex) {
if (_isFile == true) {
// is file
shares[_toEIN][nextIndex] = files[_ein][_itemIndex].rec;
}
else {
// is group
shares[_toEIN][nextIndex] = groups[_ein][_itemIndex].rec;
}
// Add to share order & global mapping
shareCount[_toEIN] = _addToSortOrder(shareOrder[_toEIN], curIndex, 0);
_addToGlobalItemsMapping(shares[_toEIN][nextIndex], uint8(GlobalItemProp.sharedTo), ItemOwner(_toEIN, nextIndex));
}
// Reset Lock
atomicity[_toEIN].lockSharings = false;
}
/**
* @dev Private Function to remove a shared item from the user's mapping
* @param _toEIN is the EIN to which the item should be removed from sharing
* @param _rec is the global record of the file
* @param _globalItem is the pointer to the global item
*/
function _removeShareFromEIN(uint _toEIN, GlobalRecord memory _rec, Association storage _globalItem)
internal {
// Check Restrictions
_isNonOwner(_toEIN); // Recipient EIN should not be the owner
// Logic
// Set Lock
atomicity[_toEIN].lockSharings = true;
// Create Sharing
uint curIndex = shareCount[_toEIN];
// no need to require as share can be multiple
// and thus should not hamper other sharings removals
if (curIndex > 0) {
uint8 mappedIndex = _findGlobalItemsMapping(_globalItem.sharedTo, _globalItem.sharedToCount, _toEIN);
// Only proceed if mapping if found
if (mappedIndex > 0) {
uint _itemIndex = _globalItem.sharedTo[mappedIndex].index;
// Remove the share from global items mapping
_removeFromGlobalItemsMapping(_rec, mappedIndex);
// Swap the shares, then Reove from share order & stich
shares[_toEIN][_itemIndex] = shares[_toEIN][curIndex];
shareCount[_toEIN] = _stichSortOrder(shareOrder[_toEIN], _itemIndex, curIndex, 0);
}
}
// Reset Lock
atomicity[_toEIN].lockSharings = false;
}
/**
* @dev Function to remove all shares of an Item, always called by owner of the Item
* @param _rec is the global item record index
*/
function _removeAllShares(GlobalRecord memory _rec)
internal {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restriction
_isSharingsOpLocked(ein); // Check if sharing operations are locked or not for the owner
// Logic
// get and pass all EINs, remove share takes care of locking
uint[32] memory eins = _getEINsForGlobalItemsMapping(globalItems[_rec.i1][_rec.i2].sharedTo, globalItems[_rec.i1][_rec.i2].sharedToCount);
removeShareFromEINs(eins, globalItems[_rec.i1][_rec.i2].ownerInfo.index, globalItems[_rec.i1][_rec.i2].isFile);
// just adjust share count
globalItems[_rec.i1][_rec.i2].sharedToCount = 0;
}
// 6. STAMPING FUNCTIONS
// 8. WHITELIST / BLACKLIST FUNCTIONS
/**
* @dev Add a non-owner user to whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToWhitelist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotBlacklist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = true;
// Trigger Event
emit AddedToWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from whitelist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromWhitelist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotBlacklist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = false;
// Trigger Event
emit RemovedFromWhitelist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user to blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function addToBlacklist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotWhitelist(ein, _nonOwnerEIN);
// Logic
blacklist[ein][_nonOwnerEIN] = true;
// Trigger Event
emit AddedToBlacklist(ein, _nonOwnerEIN);
}
/**
* @dev Remove a non-owner user from blacklist
* @param _nonOwnerEIN is the ein of the recipient
*/
function removeFromBlacklist(uint _nonOwnerEIN)
external {
// Get user EIN
uint ein = identityRegistry.getEIN(msg.sender);
// Check Restrictions
_isNotWhitelist(ein, _nonOwnerEIN);
// Logic
whitelist[ein][_nonOwnerEIN] = false;
// Trigger Event
emit RemovedFromBlacklist(ein, _nonOwnerEIN);
}
// *. REFERENTIAL INDEXES FUNCTIONS
/**
* @dev Private Function to return maximum 20 Indexes of Files, Groups, Transfers,
* etc based on their SortOrder. 0 is always reserved but will point to Root in Group & Avatar in Files
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _seedPointer is the pointer (index) of the order mapping
* @param _limit is the number of files requested | Maximum of 20 can be retrieved
* @param _asc is the order, i.e. Ascending or Descending
*/
function _getIndexes(mapping(uint => SortOrder) storage _orderMapping, uint _seedPointer, uint16 _limit, bool _asc)
internal view
returns (uint[20] memory sortedIndexes) {
uint next;
uint prev;
uint pointerID;
bool active;
// Get initial Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, _seedPointer);
// Get Previous or Next Order | Round Robin Fashion
if (_asc == true) {
// Ascending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, next);
}
else {
// Descending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, prev);
}
uint16 i = 0;
if (_limit >= 20) {
_limit = 20; // always account for root
}
while (_limit != 0) {
if (active == false || pointerID == 0) {
_limit = 0;
if (pointerID == 0) {
//add root as Special case
sortedIndexes[i] = 0;
}
}
else {
// Get PointerID
sortedIndexes[i] = pointerID;
// Get Previous or Next Order | Round Robin Fashion
if (_asc == true) {
// Ascending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, next);
}
else {
// Descending Order
(prev, next, pointerID, active) = _getOrder(_orderMapping, prev);
}
// Increment counter
i++;
// Decrease Limit
_limit--;
}
}
}
// *. DOUBLE LINKED LIST (ROUND ROBIN) FOR OPTIMIZATION FUNCTIONS / DELETE / ADD / ETC
/**
* @dev Private Function to facilitate returning of double linked list used
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _seedPointer is the pointer (index) of the order mapping
*/
function _getOrder(mapping(uint => SortOrder) storage _orderMapping, uint _seedPointer)
internal view
returns (uint prev, uint next, uint pointerID, bool active) {
prev = _orderMapping[_seedPointer].prev;
next = _orderMapping[_seedPointer].next;
pointerID = _orderMapping[_seedPointer].pointerID;
active = _orderMapping[_seedPointer].active;
}
/**
* @dev Private Function to facilitate adding of double linked list used to preserve order and form cicular linked list
* @param _orderMapping is the relevant sort order of Files, Groups, Transfers, etc
* @param _currentIndex is the index which will be maximum
* @param _pointerID is the ID to which it should point to, pass 0 to calculate on existing logic flow
*/
function _addToSortOrder(mapping(uint => SortOrder) storage _orderMapping, uint _currentIndex, uint _pointerID)
internal
returns (uint) {
// Next Index is always +1
uint nextIndex = _currentIndex + 1;
require (
(nextIndex > _currentIndex || _pointerID != 0),
"Slots Full"
);
// Assign current order to next pointer
_orderMapping[_currentIndex].next = nextIndex;
_orderMapping[_currentIndex].active = true;
// Special case of root of sort order
if (_currentIndex == 0) {
_orderMapping[0].next = nextIndex;
}
// Assign initial group prev order
_orderMapping[0].prev = nextIndex;
// Whether This is assigned or calculated
uint pointerID;
if (_pointerID == 0) {
pointerID = nextIndex;
}
else {
pointerID = _pointerID;
}
// Assign next group order pointer and prev pointer
_orderMapping[nextIndex] = SortOrder(
0, // next index
_currentIndex, // prev index
pointerID, // pointerID
true // mark as active
);
return nextIndex;
}
/**
* @dev Private Function to facilitate stiching of double linked list used to preserve order with delete
* @param _orderMapping is the relevant sort order of Files, Groups, Transfer, etc
* @param _remappedIndex is the index which is swapped to from the latest index
* @param _maxIndex is the index which will always be maximum
* @param _pointerID is the ID to which it should point to, pass 0 to calculate on existing logic flow
*/
function _stichSortOrder(mapping(uint => SortOrder) storage _orderMapping, uint _remappedIndex, uint _maxIndex, uint _pointerID)
internal
returns (uint){
// Stich Order
uint prevGroupIndex = _orderMapping[_remappedIndex].prev;
uint nextGroupIndex = _orderMapping[_remappedIndex].next;
_orderMapping[prevGroupIndex].next = nextGroupIndex;
_orderMapping[nextGroupIndex].prev = prevGroupIndex;
// Check if this is not the top order number
if (_remappedIndex != _maxIndex) {
// Change order mapping and remap
_orderMapping[_remappedIndex] = _orderMapping[_maxIndex];
if (_pointerID == 0) {
_orderMapping[_remappedIndex].pointerID = _remappedIndex;
}
else {
_orderMapping[_remappedIndex].pointerID = _pointerID;
}
_orderMapping[_orderMapping[_remappedIndex].next].prev = _remappedIndex;
_orderMapping[_orderMapping[_remappedIndex].prev].next = _remappedIndex;
}
// Turn off the non-stich group
_orderMapping[_maxIndex].active = false;
// Decrement count index if it's non-zero
require (
(_maxIndex > 0),
"Item Not Found"
);
// return new index
return _maxIndex - 1;
}
// *. GENERAL CONTRACT HELPERS
/** @dev Private Function to append two strings together
* @param a the first string
* @param b the second string
*/
function _append(string memory a, string memory b)
internal pure
returns (string memory) {
return string(abi.encodePacked(a, b));
}
/* ***************
* DEFINE MODIFIERS AS INTERNAL VIEW FUNTIONS
*************** */
/**
* @dev Private Function to check that only owner can have access
* @param _ein The EIN of the file Owner
*/
function _isOwner(uint _ein)
internal view {
require (
(identityRegistry.getEIN(msg.sender) == _ein),
"Only Owner"
);
}
/**
* @dev Private Function to check that only non-owner can have access
* @param _ein The EIN of the file Owner
*/
function _isNonOwner(uint _ein)
internal view {
require (
(identityRegistry.getEIN(msg.sender) != _ein),
"Only Non-Owner"
);
}
/**
* @dev Private Function to check that only owner of EIN can access this
* @param _ownerEIN The EIN of the file Owner
* @param _fileIndex The index of the file
*/
function _isFileOwner(uint _ownerEIN, uint _fileIndex)
internal view {
require (
(identityRegistry.getEIN(msg.sender) == files[_ownerEIN][_fileIndex].fileOwner),
"Only File Owner"
);
}
/**
* @dev Private Function to check that only non-owner of EIN can access this
* @param _ownerEIN The EIN of the file Owner
* @param _fileIndex The index of the file
*/
function _isFileNonOwner(uint _ownerEIN, uint _fileIndex)
internal view {
require (
(identityRegistry.getEIN(msg.sender) != files[_ownerEIN][_fileIndex].fileOwner),
"Only File Non-Owner"
);
}
/**
* @dev Private Function to check that only valid EINs can have access
* @param _ein The EIN of the Passer
*/
function _isValidEIN(uint _ein)
internal view {
require (
(identityRegistry.identityExists(_ein) == true),
"EIN not Found"
);
}
/**
* @dev Private Function to check that only unique EINs can have access
* @param _ein1 The First EIN
* @param _ein2 The Second EIN
*/
function _isUnqEIN(uint _ein1, uint _ein2)
internal pure {
require (
(_ein1 != _ein2),
"Same EINs"
);
}
/**
* @dev Private Function to check that a file exists for the current EIN
* @param _fileIndex The index of the file
*/
function _doesFileExists(uint _fileIndex)
internal view {
require (
(_fileIndex <= fileCount[identityRegistry.getEIN(msg.sender)]),
"File not Found"
);
}
/**
* @dev Private Function to check that a file has been marked for transferee EIN
* @param _fileIndex The index of the file
*/
function _isMarkedForTransferee(uint _fileOwnerEIN, uint _fileIndex, uint _transfereeEIN)
internal view {
// Check if the group file exists or not
require (
(files[_fileOwnerEIN][_fileIndex].transferEIN == _transfereeEIN),
"File not marked for Transfers"
);
}
/**
* @dev Private Function to check that a file hasn't been marked for stamping
* @param _rec is struct record containing global association
*/
function _isUnstampedItem(GlobalRecord memory _rec)
internal view {
// Check if the group file exists or not
require (
(globalItems[_rec.i1][_rec.i2].isStamped == false),
"Item Stamped"
);
}
/**
* @dev Private Function to check that Rooot ID = 0 is not modified as this is root
* @param _index The index to check
*/
function _isNonReservedItem(uint _index)
internal pure {
require (
(_index > 0),
"Reserved Item"
);
}
/**
* @dev Private Function to check that Group Order is valid
* @param _ein is the EIN of the target user
* @param _groupIndex The index of the group order
*/
function _isGroupFileFree(uint _ein, uint _groupIndex)
internal view {
require (
(groups[_ein][_groupIndex].groupFilesCount == 0),
"Group has Files"
);
}
/**
* @dev Private Function to check if an item exists
* @param _itemIndex the index of the item
* @param _itemCount is the count of that mapping
*/
function _isValidItem(uint _itemIndex, uint _itemCount)
internal pure {
require (
(_itemIndex <= _itemCount),
"Item Not Found"
);
}
/**
* @dev Private Function to check that Group Order is valid
* @param _ein is the EIN of the target user
* @param _groupOrderIndex The index of the group order
*/
function _isValidGrpOrder(uint _ein, uint _groupOrderIndex)
internal view {
require (
(_groupOrderIndex == 0 || groupOrder[_ein][_groupOrderIndex].active == true),
"Group Order not Found"
);
}
/**
* @dev Private Function to check that operation of Files is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isFilesOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockFiles == false),
"Files Locked"
);
}
/**
* @dev Private Function to check that operation of Groups is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isGrpsOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockGroups == false),
"Groups Locked"
);
}
/**
* @dev Private Function to check that operation of Sharings is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isSharingsOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockSharings == false),
"Sharing Locked"
);
}
/**
* @dev Private Function to check that operation of Transfers is currently locked or not
* @param _ein is the EIN of the target user
*/
function _isTransfersOpLocked(uint _ein)
internal view {
require (
(atomicity[_ein].lockTransfers == false),
"Transfers Locked"
);
}
/**
* @dev Private Function to check if the user is not blacklisted by the current user
* @param _ein is the EIN of the self
* @param _otherEIN is the EIN of the target user
*/
function _isNotBlacklist(uint _ein, uint _otherEIN)
internal view {
require (
(blacklist[_ein][_otherEIN] == false),
"EIN Blacklisted"
);
}
/**
* @dev Private Function to check if the user is not whitelisted by the current user
* @param _ein is the EIN of the self
* @param _otherEIN is the EIN of the target user
*/
function _isNotWhitelist(uint _ein, uint _otherEIN)
internal view {
require (
(whitelist[_ein][_otherEIN] == false),
"EIN Whitelisted"
);
}
// *. FOR DEBUGGING CONTRACT
// To Build Groups & File System for users
function debugBuildFS()
public {
// Create Groups
createGroup("A.Images");
createGroup("B.Movies");
createGroup("C.Crypto");
createGroup("D.Others");
createGroup("E.AdobeContract");
// Create Files
// addFile(protocol, protocolMeta, name, _hash, ext, encrypted, encryptedHash, groupIndex)
addFile(1, "0x00", "index", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "family", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "myportrait", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "cutepic", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
addFile(1, "0x00", "awesome", "QmTecWfmvvsPdZXuYrLgCTqRj9YgBiAUL4ZCr9iwDnp9q7", "0x123", false, "", 0);
}
// Get Indexes with Names for EIN
// _for = 1 is Files, 2 is GroupFiles, 3 is Groups
function debugIndexesWithNames(uint _ein, uint _groupIndex, uint _seedPointer, uint16 _limit, bool _asc, uint8 _for)
external view
returns (uint[20] memory _indexes, string memory _names) {
if (_for == 1) {
_indexes = _getIndexes(fileOrder[_ein], _seedPointer, _limit, _asc);
}
else if (_for == 2) {
_indexes = _getIndexes(groups[_ein][_groupIndex].groupFilesOrder, _seedPointer, _limit, _asc);
}
else if (_for == 3) {
_indexes = _getIndexes(groupOrder[_ein], _seedPointer, _limit, _asc);
}
uint16 i = 0;
bool completed = false;
while (completed == false) {
string memory name;
// Get Name
if (_for == 1 || _for == 2) {
name = files[_ein][_indexes[i]].name;
}
else if (_for == 3) {
name = groups[_ein][_indexes[i]].name;
}
// Add To Return Vars
name = _append(name, "|");
_names = _append(_names, name);
i++;
// check status
if (i == _limit || (_indexes[i-1] == _indexes[i])) {
completed = true;
}
}
}
}
| Private Function to check that Rooot ID = 0 is not modified as this is root _index The index to check/ | function _isNonReservedItem(uint _index)
internal pure {
require (
(_index > 0),
"Reserved Item"
);
}
| 2,542,377 |
// https://nhentai.net/g/212556/
//⠄⠄⠄⢰⣧⣼⣯⠄⣸⣠⣶⣶⣦⣾⠄⠄⠄⠄⡀⠄⢀⣿⣿⠄⠄⠄⢸⡇⠄⠄
//⠄⠄⠄⣾⣿⠿⠿⠶⠿⢿⣿⣿⣿⣿⣦⣤⣄⢀⡅⢠⣾⣛⡉⠄⠄⠄⠸⢀⣿⠄
//⠄⠄⢀⡋⣡⣴⣶⣶⡀⠄⠄⠙⢿⣿⣿⣿⣿⣿⣴⣿⣿⣿⢃⣤⣄⣀⣥⣿⣿⠄
//⠄⠄⢸⣇⠻⣿⣿⣿⣧⣀⢀⣠⡌⢻⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠿⠿⣿⣿⣿⠄
//⠄⢀⢸⣿⣷⣤⣤⣤⣬⣙⣛⢿⣿⣿⣿⣿⣿⣿⡿⣿⣿⡍⠄⠄⢀⣤⣄⠉⠋⣰
//⠄⣼⣖⣿⣿⣿⣿⣿⣿⣿⣿⣿⢿⣿⣿⣿⣿⣿⢇⣿⣿⡷⠶⠶⢿⣿⣿⠇⢀⣤
//⠘⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣽⣿⣿⣿⡇⣿⣿⣿⣿⣿⣿⣷⣶⣥⣴⣿⡗
//⢀⠈⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡟⠄
//⢸⣿⣦⣌⣛⣻⣿⣿⣧⠙⠛⠛⡭⠅⠒⠦⠭⣭⡻⣿⣿⣿⣿⣿⣿⣿⣿⡿⠃⠄
//⠘⣿⣿⣿⣿⣿⣿⣿⣿⡆⠄⠄⠄⠄⠄⠄⠄⠄⠹⠈⢋⣽⣿⣿⣿⣿⣵⣾⠃⠄
//⠄⠘⣿⣿⣿⣿⣿⣿⣿⣿⠄⣴⣿⣶⣄⠄⣴⣶⠄⢀⣾⣿⣿⣿⣿⣿⣿⠃⠄⠄
//⠄⠄⠈⠻⣿⣿⣿⣿⣿⣿⡄⢻⣿⣿⣿⠄⣿⣿⡀⣾⣿⣿⣿⣿⣛⠛⠁⠄⠄⠄
//⠄⠄⠄⠄⠈⠛⢿⣿⣿⣿⠁⠞⢿⣿⣿⡄⢿⣿⡇⣸⣿⣿⠿⠛⠁⠄⠄⠄⠄⠄
//⠄⠄⠄⠄⠄⠄⠄⠉⠻⣿⣿⣾⣦⡙⠻⣷⣾⣿⠃⠿⠋⠁⠄⠄⠄⠄⠄⢀⣠⣴
//⣿⣿⣿⣶⣶⣮⣥⣒⠲⢮⣝⡿⣿⣿⡆⣿⡿⠃⠄⠄⠄⠄⠄⠄⠄⣠⣴⣿⣿⣿
// File: contracts/core/interfaces/ISwapXV1Pair.sol
pragma solidity >=0.5.0;
interface ISwapXV1Pair {
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;
}
// File: contracts/core/interfaces/ISwapXV1ERC20.sol
pragma solidity >=0.5.0;
interface ISwapXV1ERC20 {
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;
}
// File: contracts/core/libraries/SafeMath.sol
pragma solidity >=0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
// File: contracts/core/SwapXV1ERC20.sol
pragma solidity =0.5.16;
contract SwapXV1ERC20 is ISwapXV1ERC20 {
using SafeMath for uint;
string public constant name = 'S-Token';
string public symbol = 'S-Token';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
bytes32 public DOMAIN_SEPARATOR;
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
mapping(address => uint) public nonces;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
DOMAIN_SEPARATOR = keccak256(
abi.encode(
keccak256('EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)'),
keccak256(bytes(name)),
keccak256(bytes('1')),
chainId,
address(this)
)
);
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external {
require(deadline >= block.timestamp, 'SwapXV1: EXPIRED');
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, 'SwapXV1: INVALID_SIGNATURE');
_approve(owner, spender, value);
}
}
// File: contracts/core/libraries/Math.sol
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
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;
}
}
}
// File: contracts/core/libraries/UQ112x112.sol
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
// File: contracts/core/interfaces/IERC20.sol
pragma solidity >=0.5.0;
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
// File: contracts/core/interfaces/ISwapXV1Factory.sol
pragma solidity >=0.5.0;
interface ISwapXV1Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, address pToken, uint);
function feeTo() external view returns (address);
function setter() external view returns (address);
function miner() external view returns (address);
function token2Pair(address token) external view returns (address pair);
function pair2Token(address pair) external view returns (address pToken);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function pairTokens(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair, address pToken);
function setFeeTo(address) external;
function setSetter(address) external;
function setMiner(address) external;
}
// File: contracts/core/interfaces/ISwapXV1Callee.sol
pragma solidity >=0.5.0;
interface ISwapXV1Callee {
function swapXV1Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
// File: contracts/core/libraries/AddressStringUtil.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
library AddressStringUtil {
// converts an address to the uppercase hex string, extracting only len bytes (up to 20, multiple of 2)
function toAsciiString(address addr, uint len) pure internal returns (string memory) {
require(len % 2 == 0 && len > 0 && len <= 40, "AddressStringUtil: INVALID_LEN");
bytes memory s = new bytes(len);
uint addrNum = uint(addr);
for (uint i = 0; i < len / 2; i++) {
// shift right and truncate all but the least significant byte to extract the byte at position 19-i
uint8 b = uint8(addrNum >> (8 * (19 - i)));
// first hex character is the most significant 4 bits
uint8 hi = b >> 4;
// second hex character is the least significant 4 bits
uint8 lo = b - (hi << 4);
s[2 * i] = char(hi);
s[2 * i + 1] = char(lo);
}
return string(s);
}
// hi and lo are only 4 bits and between 0 and 16
// this method converts those values to the unicode/ascii code point for the hex representation
// uses upper case for the characters
function char(uint8 b) pure private returns (byte c) {
if (b < 10) {
return byte(b + 0x30);
} else {
return byte(b + 0x37);
}
}
}
// File: contracts/core/libraries/SafeERC20Namer.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity >=0.5.0;
// produces token descriptors from inconsistent or absent ERC20 symbol implementations that can return string or bytes32
// this library will always produce a string symbol to represent the token
library SafeERC20Namer {
function bytes32ToString(bytes32 x) pure private returns (string memory) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = x[j];
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
// assumes the data is in position 2
function parseStringData(bytes memory b) pure private returns (string memory) {
uint charCount = 0;
// first parse the charCount out of the data
for (uint i = 32; i < 64; i++) {
charCount <<= 8;
charCount += uint8(b[i]);
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (uint i = 0; i < charCount; i++) {
bytesStringTrimmed[i] = b[i + 64];
}
return string(bytesStringTrimmed);
}
// uses a heuristic to produce a token name from the address
// the heuristic returns the full hex of the address string in upper case
function addressToName(address token) pure private returns (string memory) {
return AddressStringUtil.toAsciiString(token, 40);
}
// uses a heuristic to produce a token symbol from the address
// the heuristic returns the first 6 hex of the address string in upper case
function addressToSymbol(address token) pure private returns (string memory) {
return AddressStringUtil.toAsciiString(token, 6);
}
// calls an external view token contract method that returns a symbol or name, and parses the output into a string
function callAndParseStringReturn(address token, bytes4 selector) view private returns (string memory) {
(bool success, bytes memory data) = token.staticcall(abi.encodeWithSelector(selector));
// if not implemented, or returns empty data, return empty string
if (!success || data.length == 0) {
return "";
}
// bytes32 data always has length 32
if (data.length == 32) {
bytes32 decoded = abi.decode(data, (bytes32));
return bytes32ToString(decoded);
} else if (data.length > 64) {
return abi.decode(data, (string));
}
return "";
}
// attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address
function tokenSymbol(address token) internal view returns (string memory) {
// 0x95d89b41 = bytes4(keccak256("symbol()"))
string memory symbol = callAndParseStringReturn(token, 0x95d89b41);
if (bytes(symbol).length == 0) {
// fallback to 6 uppercase hex of address
return addressToSymbol(token);
}
return symbol;
}
// attempts to extract the token name. if it does not implement name, returns a name derived from the address
function tokenName(address token) internal view returns (string memory) {
// 0x06fdde03 = bytes4(keccak256("name()"))
string memory name = callAndParseStringReturn(token, 0x06fdde03);
if (bytes(name).length == 0) {
// fallback to full hex of address
return addressToName(token);
}
return name;
}
}
// File: contracts/core/libraries/PairNamer.sol
pragma solidity >=0.5.0;
// produces names for pairs of tokens
library PairNamer {
string private constant TOKEN_SYMBOL_PREFIX = '🔀';
string private constant TOKEN_SEPARATOR = ':';
// produces a pair descriptor in the format of `${prefix}${name0}:${name1}${suffix}`
function pairName(address token0, address token1, string memory prefix, string memory suffix) internal view returns (string memory) {
return string(
abi.encodePacked(
prefix,
SafeERC20Namer.tokenName(token0),
TOKEN_SEPARATOR,
SafeERC20Namer.tokenName(token1),
suffix
)
);
}
// produces a pair symbol in the format of `🔀${symbol0}:${symbol1}${suffix}`
function pairSymbol(address token0, address token1, string memory suffix) internal view returns (string memory) {
return string(
abi.encodePacked(
TOKEN_SYMBOL_PREFIX,
SafeERC20Namer.tokenSymbol(token0),
TOKEN_SEPARATOR,
SafeERC20Namer.tokenSymbol(token1),
suffix
)
);
}
// produces a pair symbol in the format of `🔀${symbol0}:${symbol1}${suffix}`
function pairPtSymbol(address token0, address token1, string memory suffix) internal view returns (string memory) {
return string(
abi.encodePacked(
SafeERC20Namer.tokenSymbol(token0),
SafeERC20Namer.tokenSymbol(token1),
suffix
)
);
}
}
// File: contracts/core/SwapXV1Pair.sol
pragma solidity =0.5.16;
contract SwapXV1Pair is ISwapXV1Pair, SwapXV1ERC20 {
using SafeMath for uint;
using UQ112x112 for uint224;
uint public constant MINIMUM_LIQUIDITY = 10**3;
bytes4 private constant SELECTOR = bytes4(keccak256(bytes('transfer(address,uint256)')));
address public factory;
address public token0;
address public token1;
uint112 private reserve0; // uses single storage slot, accessible via getReserves
uint112 private reserve1; // uses single storage slot, accessible via getReserves
uint32 private blockTimestampLast; // uses single storage slot, accessible via getReserves
uint public price0CumulativeLast;
uint public price1CumulativeLast;
uint public kLast; // reserve0 * reserve1, as of immediately after the most recent liquidity event
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'SwapXV1: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
function getReserves() public view returns (uint112 _reserve0, uint112 _reserve1, uint32 _blockTimestampLast) {
_reserve0 = reserve0;
_reserve1 = reserve1;
_blockTimestampLast = blockTimestampLast;
}
function _safeTransfer(address token, address to, uint value) private {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SELECTOR, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'SwapXV1: TRANSFER_FAILED');
}
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);
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'SwapXV1: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
symbol = string(
abi.encodePacked(
IERC20(token0).symbol(),
IERC20(token1).symbol(),
"S"
)
);
}
// update reserves and, on the first call per block, price accumulators
function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'SwapXV1: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
// * never overflows, and + overflow is desired
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
// if fee is on, mint liquidity equivalent to 1/6th of the growth in sqrt(k)
function _mintFee(uint112 _reserve0, uint112 _reserve1) private returns (bool feeOn) {
address feeTo = ISwapXV1Factory(factory).feeTo();
feeOn = feeTo != address(0);
uint _kLast = kLast; // gas savings
if (feeOn) {
if (_kLast != 0) {
uint rootK = Math.sqrt(uint(_reserve0).mul(_reserve1));
uint rootKLast = Math.sqrt(_kLast);
if (rootK > rootKLast) {
uint numerator = totalSupply.mul(rootK.sub(rootKLast));
uint denominator = rootK.mul(5).add(rootKLast);
uint liquidity = numerator / denominator;
if (liquidity > 0) _mint(feeTo, liquidity);
}
}
} else if (_kLast != 0) {
kLast = 0;
}
}
// this low-level function should be called from a contract which performs important safety checks
function mint(address to) external lock returns (uint liquidity) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
uint balance0 = IERC20(token0).balanceOf(address(this));
uint balance1 = IERC20(token1).balanceOf(address(this));
uint amount0 = balance0.sub(_reserve0);
uint amount1 = balance1.sub(_reserve1);
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
if (_totalSupply == 0) {
liquidity = Math.sqrt(amount0.mul(amount1)).sub(MINIMUM_LIQUIDITY);
_mint(address(0), MINIMUM_LIQUIDITY); // permanently lock the first MINIMUM_LIQUIDITY tokens
} else {
liquidity = Math.min(amount0.mul(_totalSupply) / _reserve0, amount1.mul(_totalSupply) / _reserve1);
}
require(liquidity > 0, 'SwapXV1: INSUFFICIENT_LIQUIDITY_MINTED');
_mint(to, liquidity);
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Mint(msg.sender, amount0, amount1);
}
// this low-level function should be called from a contract which performs important safety checks
function burn(address to) external lock returns (uint amount0, uint amount1) {
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
uint balance0 = IERC20(_token0).balanceOf(address(this));
uint balance1 = IERC20(_token1).balanceOf(address(this));
uint liquidity = balanceOf[address(this)];
bool feeOn = _mintFee(_reserve0, _reserve1);
uint _totalSupply = totalSupply; // gas savings, must be defined here since totalSupply can update in _mintFee
amount0 = liquidity.mul(balance0) / _totalSupply; // using balances ensures pro-rata distribution
amount1 = liquidity.mul(balance1) / _totalSupply; // using balances ensures pro-rata distribution
require(amount0 > 0 && amount1 > 0, 'SwapV1: INSUFFICIENT_LIQUIDITY_BURNED');
_burn(address(this), liquidity);
_safeTransfer(_token0, to, amount0);
_safeTransfer(_token1, to, amount1);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
_update(balance0, balance1, _reserve0, _reserve1);
if (feeOn) kLast = uint(reserve0).mul(reserve1); // reserve0 and reserve1 are up-to-date
emit Burn(msg.sender, amount0, amount1, to);
}
// this low-level function should be called from a contract which performs important safety checks
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external lock {
require(amount0Out > 0 || amount1Out > 0, 'SwapXV1: INSUFFICIENT_OUTPUT_AMOUNT');
(uint112 _reserve0, uint112 _reserve1,) = getReserves(); // gas savings
require(amount0Out < _reserve0 && amount1Out < _reserve1, 'SwapXV1: INSUFFICIENT_LIQUIDITY');
uint balance0;
uint balance1;
{ // scope for _token{0,1}, avoids stack too deep errors
address _token0 = token0;
address _token1 = token1;
require(to != _token0 && to != _token1, 'SwapXV1: INVALID_TO');
if (amount0Out > 0) _safeTransfer(_token0, to, amount0Out); // optimistically transfer tokens
if (amount1Out > 0) _safeTransfer(_token1, to, amount1Out); // optimistically transfer tokens
if (data.length > 0) ISwapXV1Callee(to).swapXV1Call(msg.sender, amount0Out, amount1Out, data);
balance0 = IERC20(_token0).balanceOf(address(this));
balance1 = IERC20(_token1).balanceOf(address(this));
}
uint amount0In = balance0 > _reserve0 - amount0Out ? balance0 - (_reserve0 - amount0Out) : 0;
uint amount1In = balance1 > _reserve1 - amount1Out ? balance1 - (_reserve1 - amount1Out) : 0;
require(amount0In > 0 || amount1In > 0, 'SwapXV1: INSUFFICIENT_INPUT_AMOUNT');
{ // scope for reserve{0,1}Adjusted, avoids stack too deep errors
uint balance0Adjusted = balance0.mul(1000).sub(amount0In.mul(3));
uint balance1Adjusted = balance1.mul(1000).sub(amount1In.mul(3));
require(balance0Adjusted.mul(balance1Adjusted) >= uint(_reserve0).mul(_reserve1).mul(1000**2), 'SwapXV1: K');
}
_update(balance0, balance1, _reserve0, _reserve1);
emit Swap(msg.sender, amount0In, amount1In, amount0Out, amount1Out, to);
}
// force balances to match reserves
function skim(address to) external lock {
address _token0 = token0; // gas savings
address _token1 = token1; // gas savings
_safeTransfer(_token0, to, IERC20(_token0).balanceOf(address(this)).sub(reserve0));
_safeTransfer(_token1, to, IERC20(_token1).balanceOf(address(this)).sub(reserve1));
}
// force reserves to match balances
function sync() external lock {
_update(IERC20(token0).balanceOf(address(this)), IERC20(token1).balanceOf(address(this)), reserve0, reserve1);
}
} | attempts to extract the token symbol. if it does not implement symbol, returns a symbol derived from the address 0x95d89b41 = bytes4(keccak256("symbol()")) fallback to 6 uppercase hex of address | function tokenSymbol(address token) internal view returns (string memory) {
string memory symbol = callAndParseStringReturn(token, 0x95d89b41);
if (bytes(symbol).length == 0) {
return addressToSymbol(token);
}
return symbol;
}
| 363,416 |
./partial_match/1/0xfDEd04Ad91903c20a17eB4A1409C5eBF6EFE4E8A/sources/src/MerkleOrderSettler.sol | basic ERC20 interface | interface ERC20 {
function balanceOf(address owner) external view returns (uint256);
function transfer(address to, uint256 value) external;
function transferFrom(address from, address to, uint256 value) external;
function approve(address spender, uint256 value) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
}
| 4,361,798 |
/**
*Submitted for verification at Etherscan.io on 2021-11-17
*/
/*
*
* ______ _____ _____ _ _ ______ _______
* | ____|_ _| __ \ | \ | | ____|__ __|
* | |__ | | | |__) | | \| | |__ | |
* | __| | | | ___/ | . ` | __| | |
* | |____ _| |_| | | |\ | | | |
* |______|_____|_| |_| \_|_| |_|
* created by @aka_labs_, 2021
*
*/
// File contracts/Strings.sol
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.3.2 (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 with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File contracts/ECDSA.sol
pragma solidity ^0.8.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
enum RecoverError {
NoError,
InvalidSignature,
InvalidSignatureLength,
InvalidSignatureS,
InvalidSignatureV
}
function _throwError(RecoverError error) private pure {
if (error == RecoverError.NoError) {
return; // no error: do nothing
} else if (error == RecoverError.InvalidSignature) {
revert("ECDSA: invalid signature");
} else if (error == RecoverError.InvalidSignatureLength) {
revert("ECDSA: invalid signature length");
} else if (error == RecoverError.InvalidSignatureS) {
revert("ECDSA: invalid signature 's' value");
} else if (error == RecoverError.InvalidSignatureV) {
revert("ECDSA: invalid signature 'v' value");
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature` or error string. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*
* Documentation for signature generation:
* - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js]
* - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers]
*
* _Available since v4.3._
*/
function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) {
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
return tryRecover(hash, v, r, s);
} else if (signature.length == 64) {
bytes32 r;
bytes32 vs;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
assembly {
r := mload(add(signature, 0x20))
vs := mload(add(signature, 0x40))
}
return tryRecover(hash, r, vs);
} else {
return (address(0), RecoverError.InvalidSignatureLength);
}
}
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, signature);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately.
*
* See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures]
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address, RecoverError) {
bytes32 s;
uint8 v;
assembly {
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
return tryRecover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately.
*
* _Available since v4.2._
*/
function recover(
bytes32 hash,
bytes32 r,
bytes32 vs
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, r, vs);
_throwError(error);
return recovered;
}
/**
* @dev Overload of {ECDSA-tryRecover} that receives the `v`,
* `r` and `s` signature fields separately.
*
* _Available since v4.3._
*/
function tryRecover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address, RecoverError) {
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return (address(0), RecoverError.InvalidSignatureS);
}
if (v != 27 && v != 28) {
return (address(0), RecoverError.InvalidSignatureV);
}
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
if (signer == address(0)) {
return (address(0), RecoverError.InvalidSignature);
}
return (signer, RecoverError.NoError);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
(address recovered, RecoverError error) = tryRecover(hash, v, r, s);
_throwError(error);
return recovered;
}
/**
* @dev Returns an Ethereum Signed Message, created from `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));
}
}
// File @openzeppelin/contracts/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface 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/token/ERC721/[email protected]
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/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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/token/ERC721/extensions/[email protected]
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File @openzeppelin/contracts/utils/[email protected]
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/utils/introspection/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File contracts/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 ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Default baseURI for already finalized EIPs
string private _defaultBaseURI;
// 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_,
string memory defaultBaseURI_
) {
_name = name_;
_symbol = symbol_;
_defaultBaseURI = defaultBaseURI_;
}
/**
* @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), "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), "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) public view virtual override returns (string memory) {
return "";
}
/**
* @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 _defaultBaseURI;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "approval to current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"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), "approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != msg.sender, "approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, 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(msg.sender, tokenId), "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(msg.sender, tokenId), "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), "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), "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), "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), "mint to the zero address");
require(!_exists(tokenId), "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, "transfer of token that is not own");
require(to != address(0), "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(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File contracts/Base64.sol
pragma solidity ^0.8.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
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;
}
}
// File contracts/EIPRender.sol
pragma solidity ^0.8.0;
/*
*
* ______ _____ _____ _ _ ______ _______
* | ____|_ _| __ \ | \ | | ____|__ __|
* | |__ | | | |__) | | \| | |__ | |
* | __| | | | ___/ | . ` | __| | |
* | |____ _| |_| | | |\ | | | |
* |______|_____|_| |_| \_|_| |_|
* created by @aka_labs_, 2021
*
*/
library EIPRender {
using Strings for uint160;
function generateMetadata(
string memory name,
string memory collectionInfo,
address currentOwner,
string memory dateCreated,
string memory eipDescription
) public pure returns (string memory) {
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description": "',
eipDescription,
'", "image": "',
"data:image/svg+xml;base64,",
generateImage(name, collectionInfo, currentOwner, dateCreated),
'"}'
)
)
)
)
);
}
function _getBorderFade(address currentOwner) internal pure returns (string memory) {
string memory bottomRight = "#81A7F8";
string memory topLeft = "#CBAEFD";
string memory xTop = "88";
string memory xBottom = "202";
if (uint160(currentOwner) % 2 == 0) {
(bottomRight, topLeft) = (topLeft, bottomRight);
(xTop, xBottom) = (xBottom, xTop);
}
return
Base64.encode(
bytes(
abi.encodePacked(
'<svg width="290" height="500" viewBox="0 0 290 500" xmlns="http://www.w3.org/2000/svg"><circle cx="',
xBottom,
'" cy="434" r="150px" fill="',
bottomRight,
'"/><circle cx="',
xTop,
'" cy="66" r="150px" fill="',
topLeft,
'"/></svg>'
)
)
);
}
function _getPolygon(address currentOwner) internal pure returns (string memory) {
string memory fourthAndSixth = "#81A7F8";
string memory thirdAndFifth = "#CBAEFD";
string memory second = "#CEC0F9";
string memory first = "#A6FBF7";
if (uint160(currentOwner) % 2 == 0) {
(first, second) = (second, first);
(thirdAndFifth, fourthAndSixth) = (fourthAndSixth, thirdAndFifth);
}
return
string(
abi.encodePacked(
'<polygon points="392.07,0 383.5,29.11 383.5,873.74 392.07,882.29 784.13,650.54" fill="',
first,
'" stroke="rgb(0,0,0)" stroke-width="6"/><polygon points="392.07,0 0,650.54 392.07,882.29 392.07,472.33" fill="',
second,
'" stroke="rgb(0,0,0)" stroke-width="6"/><polygon points="392.07,956.52 387.24,962.41 387.24,1263.3 392.07,1277.4 784.37,724.89" fill="',
thirdAndFifth,
'" stroke="rgb(0,0,0)" stroke-width="6"/><polygon points="392.07,1277.4 392.07,956.52 0,724.89" fill="',
fourthAndSixth,
'" stroke="rgb(0,0,0)" stroke-width="6"/><polygon points="392.07,882.29 784.13,650.54 392.07,472.33" fill="',
thirdAndFifth,
'" stroke="rgb(0,0,0)" stroke-width="6"/><polygon points="0,650.54 392.07,882.29 392.07,472.33" fill="',
fourthAndSixth,
'" stroke="rgb(0,0,0)" stroke-width="6"/>'
)
);
}
function generateImage(
string memory name,
string memory collectionInfo,
address currentOwner,
string memory dateCreated
) public pure returns (string memory) {
string
memory description = "Ethereum Improvement Proposals (EIPs) describe standards for the Ethereum platform, including core protocol specifications, client APIs, and contract standards.";
return
Base64.encode(
bytes(
string(
abi.encodePacked(
'<svg width="290" height="500" viewBox="0 0 290 500" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">',
'<defs><filter id="f1"><feImage result="p3" xlink:href="data:image/svg+xml;base64,',
_getBorderFade(currentOwner),
'"/>'
'<feGaussianBlur stdDeviation="42"/></filter><clipPath id="corners"><rect width="290" height="500" rx="42" ry="42"/></clipPath><path id="dpath" d="M40 12 H250 A28 28 0 0 1 278 40 V460 A28 28 0 0 1 250 488 H40 A28 28 0 0 1 12 460 V40 A28 28 0 0 1 40 12 z"/></defs>'
'<g clip-path="url(#corners)"><rect style="filter: url(#f1)" x="0px" y="0px" width="290px" height="500px"/></g>'
'<text text-rendering="optimizeSpeed"><textPath startOffset="-100%" font-family="Courier New" font-size="10px" xlink:href="#dpath">',
description,
'<animate additive="sum" attributeName="startOffset" from="0%" to="100%" begin="0s" dur="30s" repeatCount="indefinite"/></textPath><textPath startOffset="0%" fill="#000" font-family="Courier New" font-size="10px" xlink:href="#dpath">',
description,
'<animate additive="sum" attributeName="startOffset" from="0%" to="100%" begin="0s" dur="30s" repeatCount="indefinite"/></textPath></text>'
'<rect x="20" y="25" width="250" height="450" rx="26" ry="26" fill="#f2f2f9" stroke="#000"/>',
'<text y="65px" x="50%" font-family="Courier New" font-weight="200" font-size="36px" dominant-baseline="middle" text-anchor="middle">',
name,
"</text>"
'<g transform="matrix(0.13 0 0 0.13 94.015951 143)">',
_getPolygon(currentOwner),
"</g>",
'<g style="transform:translate(65px, 95px)">',
'<rect width="160px" height="26px" rx="8px" ry="8px" fill="#fff" stroke="#000"/>',
'<text x="12px" y="17px" font-family="Courier New" font-size="12px">Created: ',
dateCreated,
"</text></g>",
'<g style="transform:translate(65px, 335px)">',
'<rect width="160px" height="50px" rx="8px" ry="8px" fill="#fff" stroke="#000"/><text x="30px" y="18px" font-family="Courier New" font-size="12px">Edition: ',
collectionInfo,
"</text>",
'<text x="30px" y="38px" font-family="Courier New" font-size="12px">Status: FINAL</text></g><g style="transform:translate(29px, 395px)"><rect width="232px" height="55px" rx="8px" ry="8px" fill="#fff" stroke="#000"/>',
'<text x="90px" y="22px" font-family="Courier New" font-size="12px">Minted:</text><text x="12px" y="36px" font-family="Courier New" font-size="8.3px">',
uint160(currentOwner).toHexString(20),
"</text></g></svg>"
)
)
)
);
}
}
// File @openzeppelin/contracts/interfaces/[email protected]
pragma solidity ^0.8.0;
// File @openzeppelin/contracts/interfaces/[email protected]
pragma solidity ^0.8.0;
/**
* @dev Interface for the NFT Royalty Standard
*/
interface IERC2981 is IERC165 {
/**
* @dev Called with the sale price to determine how much royalty is owed and to whom.
* @param tokenId - the NFT asset queried for royalty information
* @param salePrice - the sale price of the NFT asset specified by `tokenId`
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for `salePrice`
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// File contracts/EIPNFT.sol
pragma solidity ^0.8.0;
/*
*
* ______ _____ _____ _ _ ______ _______
* | ____|_ _| __ \ | \ | | ____|__ __|
* | |__ | | | |__) | | \| | |__ | |
* | __| | | | ___/ | . ` | __| | |
* | |____ _| |_| | | |\ | | | |
* |______|_____|_| |_| \_|_| |_|
* created by @aka_labs_, 2021
*
*/
contract EIPNFT is IERC2981, ERC721 {
using ECDSA for bytes32;
using Strings for uint256;
using Strings for uint16;
uint24 internal defaultBips;
address public owner;
uint256 internal immutable top;
uint256 internal immutable middle;
mapping(uint256 => address) internal _receiverAddresses;
struct MintInfo {
uint16 mintCount;
bool mintingComplete;
string dateCreated;
string eipDescription;
}
// Minting Information for a given EIP
mapping(uint256 => MintInfo) internal _mintInfo;
constructor(address _owner, uint24 _defaultBips) ERC721("Ethereum Improvement Proposal - NFTs", "EIP", "") {
owner = _owner;
middle = 100000;
top = 100000000000;
defaultBips = _defaultBips;
}
function _encodeTokenId(uint256 eipNumber, uint256 tokenNumber) internal view returns (uint256) {
return (top + (eipNumber * middle) + tokenNumber);
}
function _getEIPNumber(uint256 tokenId) internal view returns (uint256) {
return (tokenId - top) / middle;
}
function _getTokenNumber(uint256 tokenId) internal view returns (uint256) {
return (tokenId - top - (middle * _getEIPNumber(tokenId)));
}
function authenticatedMint(
uint96 _eipNumber,
uint8 _maxMints,
address _authorAddress,
string memory _dateCreated,
string memory _eipDescription,
bytes memory _authSignature
) public {
require(
verifyMint(_eipNumber, _maxMints, _authorAddress, _dateCreated, _eipDescription, _authSignature),
"Not authorized"
);
MintInfo storage currentMintInfo = _mintInfo[_eipNumber];
uint256 tokenNumber = currentMintInfo.mintCount + 1;
if (bytes(_dateCreated).length > 0) {
currentMintInfo.dateCreated = _dateCreated;
}
if (bytes(_eipDescription).length > 0) {
currentMintInfo.eipDescription = _eipDescription;
}
require(!currentMintInfo.mintingComplete, "Too many mints");
// Set mintingComplete flag to true when on the last mint for an EIP.
// Contract owner can't issue new NFTs for thie EIP after this point.
if (tokenNumber == _maxMints) {
currentMintInfo.mintingComplete = true;
}
if (super.balanceOf(_authorAddress) != 0) {
for (uint256 i = 1; i <= _maxMints; i++) {
uint256 currentTokenId = _encodeTokenId(_eipNumber, i);
if (_exists(currentTokenId)) {
require(super.ownerOf(currentTokenId) != _authorAddress, "Already minted");
}
}
}
uint256 tokenId = _encodeTokenId(_eipNumber, tokenNumber);
safeMint(tokenId, _authorAddress);
_receiverAddresses[tokenId] = _authorAddress;
currentMintInfo.mintCount += 1;
}
function verifyMint(
uint96 _eipNumber,
uint8 _maxMints,
address _authorAddress,
string memory _dateCreated,
string memory _eipDescription,
bytes memory _authSignature
) public view returns (bool) {
require(msg.sender == _authorAddress, "Wrong sender");
return
ECDSA.recover(
ECDSA.toEthSignedMessageHash(
abi.encodePacked(
abi.encodePacked(_eipNumber),
abi.encodePacked(_maxMints),
abi.encodePacked(_authorAddress),
abi.encodePacked(_dateCreated),
abi.encodePacked(_eipDescription)
)
),
_authSignature
) == owner;
}
function safeMint(uint256 tokenId, address _authorAddress) internal virtual {
super._safeMint(_authorAddress, tokenId, "");
}
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "Nonexistent token");
uint256 eipNumber = _getEIPNumber(tokenId);
string memory name = string(abi.encodePacked("EIP-", eipNumber.toString()));
address currentOwner = super.ownerOf(tokenId);
return
EIPRender.generateMetadata(
name,
string(
abi.encodePacked(
"(",
_getTokenNumber(tokenId).toString(),
"/",
_mintInfo[eipNumber].mintCount.toString(),
")"
)
),
currentOwner,
_mintInfo[eipNumber].dateCreated,
_mintInfo[eipNumber].eipDescription
);
}
/// @inheritdoc IERC2981
function royaltyInfo(uint256 tokenId, uint256 value)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = _receiverAddresses[tokenId];
royaltyAmount = (value * defaultBips) / 10000;
}
function transferOwnership(address newOwner) public {
require(owner == msg.sender, "Unauthorized");
require(newOwner != address(0));
owner = newOwner;
}
} | See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256) public view virtual override returns (string memory) {
return "";
}
| 2,161,150 |
./full_match/1/0xB51B89140D168734d656B2C8959A4E3F7205b8b4/sources/contracts/modules/common/Utils.sol | Helper method to recover the signer at a given position from a list of concatenated signatures. _signedHash The signed hash _signatures The concatenated signatures. _index The index of the signature to recover. return the signer public address./ 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 solhint-disable-next-line no-inline-assembly | function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) {
uint8 v;
bytes32 r;
bytes32 s;
assembly {
r := mload(add(_signatures, add(0x20,mul(0x41,_index))))
s := mload(add(_signatures, add(0x40,mul(0x41,_index))))
v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff)
}
require(v == 27 || v == 28, "U: bad v value in signature");
address recoveredAddress = ecrecover(_signedHash, v, r, s);
require(recoveredAddress != address(0), "U: ecrecover returned 0");
return recoveredAddress;
}
| 16,575,539 |
./full_match/1/0xA3abb32c657adA8803bF6AEEF6Eb42B29c74bf28/sources/contracts/SmartYield.sol | change the controller, only callable by old controller or dao | function setController(address newController_)
external override
onlyControllerOrDao
{
controller = newController_;
}
| 2,993,944 |
pragma solidity ^0.5.2;
import "../installed_contracts/zeppelin/contracts/math/SafeMath.sol";
import "./BehaviourToken.sol"
contract BikeSharing {
using SafeMath for uint256;
// CONSTANTS
uint constant public MAX_BIKE_COUNT = 1000;
uint constant public DAMAGE_PAYMENT = 1 ether;
uint constant public INSURANCE_RETENTION = 100 finney;
/*
================================================================
State variables
================================================================
*/
// Hyperparameters
address admin;
uint256 requiredDeposit;
uint256 hourlyFee;
uint256 premiumRate;
// Bike sharing
mapping(address => Client) public clientMapping;
mapping(uint256 => Bike) public bikeMapping;
mapping(uint256 => bool) public isBikeActive;
mapping(address => bool) public isBikeClient;
address[] public clientList;
uint256 public toRepair;
// Insurance
mapping(address => bool) public isClientInsured;
mapping(address => InsuranceClient) public insuranceMapping;
//////////// Tokens
BehaviourToken public behaviourToken;
address public tokenAddress;
uint256 public tokenRewardAmount;
/*
================================================================
Data structures
================================================================
*/
enum BikeState {DEACTIVATED, AVAILABLE, IN_USE}
enum ClientState {BANNED, GOOD_TO_GO, IN_RIDE}
struct Bike {
address lastRenter;
bool condition;
bool currentlyInUse;
uint usageTime;
BikeState state;
}
struct Client {
uint received;
uint returned;
uint clientListPointer;
ClientState state;
}
struct InsuranceClient {
uint accidentCount;
uint receivedPremiums;
uint claimPayouts;
uint tokenCount;
}
/*
================================================================
Modifiers
================================================================
*/
/*
modifier adminOnly() {
if(msg.sender == _admin) _;
}
*/
// Modifier not disallow the admin to rent bike
modifier adminOnly() {
require(msg.sender == admin);
_;
}
modifier adminExcluded() {
require(msg.sender != admin);
_;
}
modifier bikeClientOnly(address clientAddress) {
require(isBikeClient[clientAddress] == true);
_;
}
modifier validParametersBike(uint bikeId) {
require(bikeId >= 0 && bikeId < MAX_BIKE_COUNT);
_;
}
modifier notNullAddress (address _address) {
require(_address != 0);
_;
}
modifier positiveReward (uint256 _rewardValue) {
require(_rewardValue > 0);
_;
}
// TODO : a customer cannot rent another bike while he's riding one
/*
================================================================
Events
================================================================
*/
event LogBikeRent(uint bikeId, address renter, bool status);
event LogReceivedFunds(address sender, uint amount);
event LogReturnedFunds(address recipient, uint amount);
// Fallback event
event Deposit(address indexed sender, uint256 value);
// Token events
event TokenRewardSet(uint256 tokenReward);
event TokenPaid(address riderAddress, uint256 amount);
// Client creation
event ClientCreated(address clientAddress);
// Change of state events
event BikeAvailable(uint bikeId);
event ClientGoodToGo(address clientAddress)
event BikeInRide(uint bikeId);
event ClientInRide(address clientAddress);
event BikeDeactivated(uint bikeId);
/*
================================================================
Constructor
================================================================
*/
constructor(uint256 _hourlyFee, uint256 _premiumRate) public {
admin = msg.sender;
requiredDeposit = DAMAGE_PAYMENT;
hourlyFee = _hourlyFee;
premiumRate = _premiumRate;
// Initialize a BehaviourToken
setBehaviourToken(new BehaviourToken());
uint256 rideReward = 1;
setBehaviourTokenReward(rideReward);
}
/*
================================================================
Token distribution
================================================================
*/
function setBehaviourTokenReward(uint256 _tokenReward)
public
// Modifier on being onlyOwner
positiveReward(_tokenReward)
{
tokenRewardAmount = _tokenReward;
emit TokenRewardSet(tokenRewardAmount);
}
function setBehaviourToken(address _newBehaviourToken)
internal
notNullAddress(_newBehaviourToken)
{
behaviourToken = BehaviourToken(_newBehaviourToken);
tokenAddress = address(behaviourToken);
}
function rewardRider(address _riderAddress)
private
notNullAddress(_riderAddress)
{
require(tokenRewardAmount > 0);
behaviourToken.transfer(_riderAddress, tokenRewardAmount);
emit TokenPaid(_riderAddress, tokenRewardAmount);
}
/*
================================================================
Insurance
================================================================
*/
function calculatePremium(address insuranceTaker)
view
public
returns (uint256 premium)
{
InsuranceClient memory customer = insuranceMapping[msg.sender];
return (customer.accidentCount + 1) * premiumRate;
}
function underwriteInsurance()
public
payable
returns (bool success)
{
// The client must not be a client already
require(isClientInsured[msg.sender]==false);
require(msg.value == calculatePremium(msg.sender));
InsuranceClient storage customer = insuranceMapping[msg.sender];
customer.receivedPremiums += msg.value;
// Initialize the other
customer.claimPayouts = 0;
customer.tokenCount = 0;
//
isClientInsured[msg.sender] = true;
return isClientInsured[msg.sender];
}
function tokensAgainstCount()
/*
================================================================
Bike housekeeping
================================================================
*/
// Check if a bike has been used, if not
function isBikeFirstUse(uint256 bikeId)
public
view
returns(bool isFirstTime)
{
return isBikeActive[bikeId] == false;
}
function getClientCount() public view returns(uint clientCount){
return clientList.length;
}
function isClient(address client)
public
view
returns (bool isIndeed)
{
return isBikeClient[client] == true;
}
function getBalance() public view returns(uint){
return address(this).balance;
}
function calculateFee(uint duration) public view returns (uint) {
uint num_hours = div(duration, 3600);
if(num_hours > 24){
return requiredDeposit;
}
uint toPay = num_hours * hourlyFee;
return toPay;
}
/*
================================================================
Rent and surrender bikes
================================================================
*/
function rentBike(uint bikeId)
public
payable
validParametersBike(bikeId)
adminExcluded
returns (bool)
{
// Require that the bikeId remains in the desired interval
// require(bikeId >= 0 && bikeId < MAX_BIKE_COUNT);
// Check if the bike is activated
if(isBikeFirstUse(bikeId)) {
bikeMapping[bikeId] = Bike(
{
lastRenter: address(0),
condition: true,
currentlyInUse: false,
usageTime: 0,
state: BikeState.DEACTIVATED
}
);
isBikeActive[bikeId] = true;
bikeMapping[bikeId].state = BikeState.AVAILABLE;
emit BikeAvailable(bikeId);
} else {
// The bike must be unused, in good condition, activated, and not in ride already
require(bikeMapping[bikeId].currentlyInUse == false);
require(bikeMapping[bikeId].condition == true);
require(bikeMapping[bikeId].state == BikeState.AVAILABLE);
}
// Check if the address is a client, if not create a struct
if(!isClient(msg.sender)){
clientMapping[msg.sender] = Client(
{
received: 0,
returned: 0,
clientListPointer: 0,
state: ClientState.GOOD_TO_GO
}
);
clientMapping[msg.sender].clientListPointer = clientList.push(msg.sender) - 1;
// Finally, the guy is made a client
isBikeClient[msg.sender] = true;
emit ClientCreated(msg.sender);
} else {
// The client must not be already using a scooter
// TO TEST
require(clientMapping[msg.sender].state == ClientState.GOOD_TO_GO);
}
// Check if the client is insured
if(isClientInsured[msg.sender]==true) {
uint256 premium = calculatePremium(msg.sender);
require(msg.value == requiredDeposit + premium);
InsuranceClient memory policyholder = insuranceMapping[msg.sender];
// TODO : the premium has to be transferred to the insurance company !!
policyholder.receivedPremiums += premium;
} else {
// Require that the requiredDeposit is paid in full
require(msg.value == requiredDeposit);
}
clientMapping[msg.sender].received += requiredDeposit;
emit LogReceivedFunds(msg.sender, msg.value);
// Change bike situation and state
bikeMapping[bikeId].lastRenter = msg.sender;
bikeMapping[bikeId].currentlyInUse = true;
bikeMapping[bikeId].usageTime = now;
bikeMapping[bikeId].state = BikeState.IN_USE;
emit BikeInRide(bikeId);
// Change client state
clientMapping[msg.sender].state = ClientState.IN_RIDE;
emit ClientInRide(msg.sender);
// Obsolete
emit LogBikeRent(bikeId, msg.sender, bikeMapping[bikeId].currentlyInUse);
return bikeMapping[bikeId].currentlyInUse;
}
modifier bikeInRide (uint bikeId) {
require(bikeMapping[bikeId].state == BikeState.IN_USE);
_;
}
modifier bikeUser (uint bikeId, address clientAdr) {
require(bikeMapping[bikeId].lastRenter == clientAdr);
_;
}
modifier clientInRide (address clientAdr) {
require(clientMapping[clientAdr].state == ClientState.IN_RIDE);
_;
}
function surrenderBike(uint bikeId, bool newCondition)
public
bikeClientOnly(msg.sender)
validParametersBike(bikeId)
bikeInRide(bikeId)
clientInRide(msg.sender)
bikeUser(bikeId, msg.sender)
adminExcluded
returns (bool success) {
/* ============== Bike ============== */
// Compute the amount charged for the bike
uint feeCharged = calculateFee(now - bikeMapping[bikeId].usageTime);
uint owedToClient = clientMapping[msg.sender].received - feeCharged;
/* ============== Insurance ============== */
if (isClientInsured[msg.sender] == true) {
InsuranceClient storage policyholder = insuranceMapping[msg.sender];
if (newCondition == false) {
// The dude will not be charged (or a little extra)
// TODO : How is the insurer going to pay the charge ??
owedToClient = 0;
// His count of accident changes
policyholder.accidentCount += 1;
// His payout also. THIS IS A NET VALUE, NORMALLY THE CLIENT IS OWED NOTHING
policyholder.claimPayouts += DAMAGE_PAYMENT;
// The insurance will pay for the deposit.
// Eventually, the guy will be paid back by the insurer.
owedToClient += DAMAGE_PAYMENT - INSURANCE_RETENTION;
// TODO : MAKE THE SCOOTER UNRENTABLE
bikeMapping[bikeId].state = BikeState.DEACTIVATED;
emit BikeDeactivated(bikeId);
} else {
// Good shape : will gain a token
policyholder.tokenCount += tokenRewardAmount;
rewardRider(msg.sender);
bikeMapping[bikeId].state = BikeState.AVAILABLE;
emit BikeAvailable(bikeId);
}
} else {
// If bad condition, then the guy is owed nothing
if (newCondition == false) {
owedToClient = 0;
bikeMapping[bikeId].state = BikeState.DEACTIVATED;
emit BikeDeactivated(bikeId);
} else {
bikeMapping[bikeId].state = BikeState.AVAILABLE;
emit BikeAvailable(bikeId);
}
}
/* ============== Accounting / Housekeeping ============== */
// Update the transaction
clientMapping[msg.sender].returned += owedToClient;
// Pay back the remainder
if(clientMapping[msg.sender].returned != 0) {
msg.sender.call.value(owedToClient));
}
emit LogReturnedFunds(msg.sender, clientMapping[msg.sender].returned);
// Reset the accounting for the client
clientMapping[msg.sender].received = 0;
clientMapping[msg.sender].returned = 0;
// Make the client good to go
clientMapping[msg.sender].state = ClientState.GOOD_TO_GO;
emit ClientGoodToGo(msg.sender);
return true;
}
/*
================================================================
Fallback function
================================================================
*/
function ()
public
payable
{
if (msg.value > 0) {
emit Deposit(msg.sender, msg.value);
}
}
} | / Check if a bike has been used, if not | function tokensAgainstCount()
================================================================
Bike housekeeping
================================================================
function isBikeFirstUse(uint256 bikeId)
public
view
returns(bool isFirstTime)
{
return isBikeActive[bikeId] == false;
}
| 13,126,283 |
//Address: 0x996ccd50d1e3aee157dac4ee79942ab63ad86ebc
//Contract name: SharderToken
//Balance: 0 Ether
//Verification Date: 3/12/2018
//Transacion Count: 5
// CODE STARTS HERE
/*
Copyright 2017 Sharder Foundation.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
################ Sharder-Token-v2.0 ###############
a) Adding the emergency transfer functionality for owner.
b) Removing the logic of crowdsale according to standard MintToken in order to improve the neatness and
legibility of the Sharder smart contract coding.
c) Adding the broadcast event 'Frozen'.
d) Changing the parameters of name, symbol, decimal, etc. to lower-case according to convention. Adjust format of input paramters.
e) The global parameter is added to our smart contact in order to avoid that the exchanges trade Sharder tokens
before officials partnering with Sharder.
f) Add holder array to facilitate the exchange of the current ERC-20 token to the Sharder Chain token later this year
when Sharder Chain is online.
g) Lockup and lock-up query functions.
The deplyed online contract you can found at: https://etherscan.io/address/XXXXXX
Sharder-Token-v1.0 is expired. You can check the code and get the details on branch 'sharder-token-v1.0'.
*/
pragma solidity ^0.4.18;
/**
* Math operations with safety checks
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(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 min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title Sharder Token v2.0. SS(Sharder) is upgrade from SS(Sharder Storage).
* @author Ben - <[email protected]>.
* @dev ERC-20: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
*/
contract SharderToken {
using SafeMath for uint;
string public name = "Sharder";
string public symbol = "SS";
uint8 public decimals = 18;
/// +--------------------------------------------------------------+
/// | SS(Sharder) Token Issue Plan |
/// +--------------------------------------------------------------+
/// | First Round(Crowdsale) |
/// +--------------------------------------------------------------+
/// | Total Sale | Airdrop | Community Reserve |
/// +--------------------------------------------------------------+
/// | 250,000,000 | 50,000,000 | 50,000,000 |
/// +--------------------------------------------------------------+
/// | Team Reserve(50,000,000 SS): Issue in 3 years period |
/// +--------------------------------------------------------------+
/// | System Reward(100,000,000 SS): Reward by Sharder Chain Auto |
/// +--------------------------------------------------------------+
uint256 public totalSupply = 350000000000000000000000000;
mapping (address => mapping (address => uint256)) public allowance;
mapping (address => uint256) public balanceOf;
/// The owner of contract
address public owner;
/// The admin account of contract
address public admin;
mapping (address => bool) internal accountLockup;
mapping (address => uint) public accountLockupTime;
mapping (address => bool) public frozenAccounts;
mapping (address => uint) internal holderIndex;
address[] internal holders;
///First round tokens whether isssued.
bool internal firstRoundTokenIssued = false;
/// Contract pause state
bool public paused = true;
/// Issue event index starting from 0.
uint256 internal issueIndex = 0;
// Emitted when a function is invocated without the specified preconditions.
event InvalidState(bytes msg);
// This notifies clients about the token issued.
event Issue(uint issueIndex, address addr, uint ethAmount, uint tokenAmount);
// This notifies clients about the amount to transfer
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount to approve
event Approval(address indexed owner, address indexed spender, uint value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
// This notifies clients about the account frozen
event FrozenFunds(address target, bool frozen);
// This notifies clients about the pause
event Pause();
// This notifies clients about the unpause
event Unpause();
/*
* MODIFIERS
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
modifier onlyAdmin {
require(msg.sender == owner || msg.sender == admin);
_;
}
/**
* @dev Modifier to make a function callable only when account not frozen.
*/
modifier isNotFrozen {
require(frozenAccounts[msg.sender] != true && now > accountLockupTime[msg.sender]);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier isNotPaused() {
require((msg.sender == owner && paused) || (msg.sender == admin && paused) || !paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier isPaused() {
require(paused);
_;
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal isNotFrozen isNotPaused {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(balanceOf[_to] + _value > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = balanceOf[_from] + balanceOf[_to];
// Subtract from the sender
balanceOf[_from] -= _value;
// Add the same to the recipient
balanceOf[_to] += _value;
// Update holders
addOrUpdateHolder(_from);
addOrUpdateHolder(_to);
Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(balanceOf[_from] + balanceOf[_to] == previousBalances);
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _transferTokensWithDecimal The amount to be transferred.
*/
function transfer(address _to, uint _transferTokensWithDecimal) public {
_transfer(msg.sender, _to, _transferTokensWithDecimal);
}
/**
* @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 _transferTokensWithDecimal uint the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint _transferTokensWithDecimal) public isNotFrozen isNotPaused returns (bool success) {
require(_transferTokensWithDecimal <= allowance[_from][msg.sender]);
// Check allowance
allowance[_from][msg.sender] -= _transferTokensWithDecimal;
_transfer(_from, _to, _transferTokensWithDecimal);
return true;
}
/**
* Set allowance for other address
* Allows `_spender` to spend no more than `_approveTokensWithDecimal` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _approveTokensWithDecimal the max amount they can spend
*/
function approve(address _spender, uint256 _approveTokensWithDecimal) public isNotFrozen isNotPaused returns (bool success) {
allowance[msg.sender][_spender] = _approveTokensWithDecimal;
Approval(msg.sender, _spender, _approveTokensWithDecimal);
return true;
}
/**
* Destroy tokens
* Remove `_value` tokens from the system irreversibly
* @param _burnedTokensWithDecimal the amount of reserve tokens. !!IMPORTANT is 18 DECIMALS
*/
function burn(uint256 _burnedTokensWithDecimal) public isNotFrozen isNotPaused returns (bool success) {
require(balanceOf[msg.sender] >= _burnedTokensWithDecimal);
/// Check if the sender has enough
balanceOf[msg.sender] -= _burnedTokensWithDecimal;
/// Subtract from the sender
totalSupply -= _burnedTokensWithDecimal;
Burn(msg.sender, _burnedTokensWithDecimal);
return true;
}
/**
* Destroy tokens from other account
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
* @param _from the address of the sender
* @param _burnedTokensWithDecimal the amount of reserve tokens. !!! IMPORTANT is 18 DECIMALS
*/
function burnFrom(address _from, uint256 _burnedTokensWithDecimal) public isNotFrozen isNotPaused returns (bool success) {
require(balanceOf[_from] >= _burnedTokensWithDecimal);
/// Check if the targeted balance is enough
require(_burnedTokensWithDecimal <= allowance[_from][msg.sender]);
/// Check allowance
balanceOf[_from] -= _burnedTokensWithDecimal;
/// Subtract from the targeted balance
allowance[_from][msg.sender] -= _burnedTokensWithDecimal;
/// Subtract from the sender's allowance
totalSupply -= _burnedTokensWithDecimal;
Burn(_from, _burnedTokensWithDecimal);
return true;
}
/**
* Add holder addr into arrays.
* @param _holderAddr the address of the holder
*/
function addOrUpdateHolder(address _holderAddr) internal {
// Check and add holder to array
if (holderIndex[_holderAddr] == 0) {
holderIndex[_holderAddr] = holders.length++;
}
holders[holderIndex[_holderAddr]] = _holderAddr;
}
/**
* CONSTRUCTOR
* @dev Initialize the Sharder Token v2.0
*/
function SharderToken() public {
owner = msg.sender;
admin = 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));
owner = _newOwner;
}
/**
* @dev Set admin account to manage contract.
*/
function setAdmin(address _address) public onlyOwner {
admin = _address;
}
/**
* @dev Issue first round tokens to `owner` address.
*/
function issueFirstRoundToken() public onlyOwner {
require(!firstRoundTokenIssued);
balanceOf[owner] = balanceOf[owner].add(totalSupply);
Issue(issueIndex++, owner, 0, totalSupply);
addOrUpdateHolder(owner);
firstRoundTokenIssued = true;
}
/**
* @dev Issue tokens for reserve.
* @param _issueTokensWithDecimal the amount of reserve tokens. !!IMPORTANT is 18 DECIMALS
*/
function issueReserveToken(uint256 _issueTokensWithDecimal) onlyOwner public {
balanceOf[owner] = balanceOf[owner].add(_issueTokensWithDecimal);
totalSupply = totalSupply.add(_issueTokensWithDecimal);
Issue(issueIndex++, owner, 0, _issueTokensWithDecimal);
}
/**
* @dev Frozen or unfrozen account.
*/
function changeFrozenStatus(address _address, bool _frozenStatus) public onlyAdmin {
frozenAccounts[_address] = _frozenStatus;
}
/**
* @dev Lockup account till the date. Can't lock-up again when this account locked already.
* 1 year = 31536000 seconds, 0.5 year = 15768000 seconds
*/
function lockupAccount(address _address, uint _lockupSeconds) public onlyAdmin {
require((accountLockup[_address] && now > accountLockupTime[_address]) || !accountLockup[_address]);
// lock-up account
accountLockupTime[_address] = now + _lockupSeconds;
accountLockup[_address] = true;
}
/**
* @dev Get the cuurent ss holder count.
*/
function getHolderCount() public constant returns (uint _holdersCount){
return holders.length - 1;
}
/*
* @dev Get the current ss holder addresses.
*/
function getHolders() public onlyAdmin constant returns (address[] _holders){
return holders;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyAdmin isNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyAdmin isPaused public {
paused = false;
Unpause();
}
function setSymbol(string _symbol) public onlyOwner {
symbol = _symbol;
}
function setName(string _name) public onlyOwner {
name = _name;
}
/// @dev This default function reject anyone to purchase the SS(Sharder) token after crowdsale finished.
function() public payable {
revert();
}
}
| transfer token for a specified address _to The address to transfer to. _transferTokensWithDecimal The amount to be transferred./ | function transfer(address _to, uint _transferTokensWithDecimal) public {
_transfer(msg.sender, _to, _transferTokensWithDecimal);
}
| 2,574,441 |
./full_match/80001/0x7976d3d810953a343dac576b42F58382922cbA54/sources/contracts/GotMintedERC1155.sol | Function sets Pause to "True" | function pause() internal onlyRole(ADMIN_ROLE) whenNotPaused {
_pause();
}
| 5,589,966 |
pragma solidity ^0.4.24;
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/controller/Reputation.sol
/**
* @title Reputation system
* @dev A DAO has Reputation System which allows peers to rate other peers in order to build trust .
* A reputation is use to assign influence measure to a DAO'S peers.
* Reputation is similar to regular tokens but with one crucial difference: It is non-transferable.
* The Reputation contract maintain a map of address to reputation value.
* It provides an onlyOwner functions to mint and burn reputation _to (or _from) a specific address.
*/
contract Reputation is Ownable {
using SafeMath for uint;
mapping (address => uint256) public balances;
uint256 public totalSupply;
uint public decimals = 18;
// Event indicating minting of reputation to an address.
event Mint(address indexed _to, uint256 _amount);
// Event indicating burning of reputation for an address.
event Burn(address indexed _from, uint256 _amount);
/**
* @dev return the reputation amount of a given owner
* @param _owner an address of the owner which we want to get his reputation
*/
function reputationOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Generates `_amount` of reputation that are assigned to `_to`
* @param _to The address that will be assigned the new reputation
* @param _amount The quantity of reputation to be generated
* @return True if the reputation are generated correctly
*/
function mint(address _to, uint _amount)
public
onlyOwner
returns (bool)
{
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
return true;
}
/**
* @dev Burns `_amount` of reputation from `_from`
* if _amount tokens to burn > balances[_from] the balance of _from will turn to zero.
* @param _from The address that will lose the reputation
* @param _amount The quantity of reputation to burn
* @return True if the reputation are burned correctly
*/
function burn(address _from, uint _amount)
public
onlyOwner
returns (bool)
{
uint amountMinted = _amount;
if (balances[_from] < _amount) {
amountMinted = balances[_from];
}
totalSupply = totalSupply.sub(amountMinted);
balances[_from] = balances[_from].sub(amountMinted);
emit Burn(_from, amountMinted);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/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]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
// File: openzeppelin-solidity/contracts/token/ERC20/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);
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;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-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);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/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 {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// 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[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts/token/ERC827/ERC827.sol
/**
* @title ERC827 interface, an extension of ERC20 token standard
*
* @dev Interface of a ERC827 token, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals.
*/
contract ERC827 is ERC20 {
function approveAndCall(address _spender,uint256 _value,bytes _data) public payable returns(bool);
function transferAndCall(address _to,uint256 _value,bytes _data) public payable returns(bool);
function transferFromAndCall(address _from,address _to,uint256 _value,bytes _data) public payable returns(bool);
}
// File: contracts/token/ERC827/ERC827Token.sol
/* solium-disable security/no-low-level-calls */
pragma solidity ^0.4.24;
/**
* @title ERC827, an extension of ERC20 token standard
*
* @dev Implementation the ERC827, following the ERC20 standard with extra
* methods to transfer value and data and execute calls in transfers and
* approvals. Uses OpenZeppelin StandardToken.
*/
contract ERC827Token is ERC827, StandardToken {
/**
* @dev Addition to ERC20 token methods. It allows to
* approve the transfer of value and execute a call with the sent data.
* 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 that will spend the funds.
* @param _value The amount of tokens to be spent.
* @param _data ABI-encoded contract call to call `_spender` address.
* @return true if the call function was executed successfully
*/
function approveAndCall(
address _spender,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.approve(_spender, _value);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens to a specified
* address and execute a call with the sent data on the same transaction
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferAndCall(
address _to,
uint256 _value,
bytes _data
)
public
payable
returns (bool)
{
require(_to != address(this));
super.transfer(_to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to ERC20 token methods. Transfer tokens from one address to
* another and make a contract call on the same transaction
* @param _from The address which you want to send tokens from
* @param _to The address which you want to transfer to
* @param _value The amout of tokens to be transferred
* @param _data ABI-encoded contract call to call `_to` address.
* @return true if the call function was executed successfully
*/
function transferFromAndCall(
address _from,
address _to,
uint256 _value,
bytes _data
)
public payable returns (bool)
{
require(_to != address(this));
super.transferFrom(_from, _to, _value);
// solium-disable-next-line security/no-call-value
require(_to.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Increase the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function increaseApprovalAndCall(
address _spender,
uint _addedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.increaseApproval(_spender, _addedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
/**
* @dev Addition to StandardToken methods. Decrease the amount of tokens that
* an owner allowed to a spender and execute a call with the sent data.
* 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.
* @param _data ABI-encoded contract call to call `_spender` address.
*/
function decreaseApprovalAndCall(
address _spender,
uint _subtractedValue,
bytes _data
)
public
payable
returns (bool)
{
require(_spender != address(this));
super.decreaseApproval(_spender, _subtractedValue);
// solium-disable-next-line security/no-call-value
require(_spender.call.value(msg.value)(_data));
return true;
}
}
// File: contracts/controller/DAOToken.sol
/**
* @title DAOToken, base on zeppelin contract.
* @dev ERC20 compatible token. It is a mintable, destructible, burnable token.
*/
contract DAOToken is ERC827Token,MintableToken,BurnableToken {
string public name;
string public symbol;
// solium-disable-next-line uppercase
uint8 public constant decimals = 18;
uint public cap;
/**
* @dev Constructor
* @param _name - token name
* @param _symbol - token symbol
* @param _cap - token cap - 0 value means no cap
*/
constructor(string _name, string _symbol,uint _cap) public {
name = _name;
symbol = _symbol;
cap = _cap;
}
/**
* @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 onlyOwner canMint returns (bool) {
if (cap > 0)
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: contracts/controller/Avatar.sol
/**
* @title An Avatar holds tokens, reputation and ether for a controller
*/
contract Avatar is Ownable {
bytes32 public orgName;
DAOToken public nativeToken;
Reputation public nativeReputation;
event GenericAction(address indexed _action, bytes32[] _params);
event SendEther(uint _amountInWei, address indexed _to);
event ExternalTokenTransfer(address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom(address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval(StandardToken indexed _externalToken, address _spender, uint _addedValue);
event ExternalTokenDecreaseApproval(StandardToken indexed _externalToken, address _spender, uint _subtractedValue);
event ReceiveEther(address indexed _sender, uint _value);
/**
* @dev the constructor takes organization name, native token and reputation system
and creates an avatar for a controller
*/
constructor(bytes32 _orgName, DAOToken _nativeToken, Reputation _nativeReputation) public {
orgName = _orgName;
nativeToken = _nativeToken;
nativeReputation = _nativeReputation;
}
/**
* @dev enables an avatar to receive ethers
*/
function() public payable {
emit ReceiveEther(msg.sender, msg.value);
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @return the return bytes of the called contract's function.
*/
function genericCall(address _contract,bytes _data) public onlyOwner {
// solium-disable-next-line security/no-low-level-calls
bool result = _contract.call(_data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
switch result
// call returns 0 on error.
case 0 { revert(0, returndatasize) }
default { return(0, returndatasize) }
}
}
/**
* @dev send ethers from the avatar's wallet
* @param _amountInWei amount to send in Wei units
* @param _to send the ethers to this address
* @return bool which represents success
*/
function sendEther(uint _amountInWei, address _to) public onlyOwner returns(bool) {
_to.transfer(_amountInWei);
emit SendEther(_amountInWei, _to);
return true;
}
/**
* @dev external token transfer
* @param _externalToken the token contract
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value)
public onlyOwner returns(bool)
{
_externalToken.transfer(_to, _value);
emit ExternalTokenTransfer(_externalToken, _to, _value);
return true;
}
/**
* @dev external token transfer from a specific account
* @param _externalToken the token contract
* @param _from the account to spend token from
* @param _to the destination address
* @param _value the amount of tokens to transfer
* @return bool which represents success
*/
function externalTokenTransferFrom(
StandardToken _externalToken,
address _from,
address _to,
uint _value
)
public onlyOwner returns(bool)
{
_externalToken.transferFrom(_from, _to, _value);
emit ExternalTokenTransferFrom(_externalToken, _from, _to, _value);
return true;
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue)
public onlyOwner returns(bool)
{
_externalToken.increaseApproval(_spender, _addedValue);
emit ExternalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
return true;
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue )
public onlyOwner returns(bool)
{
_externalToken.decreaseApproval(_spender, _subtractedValue);
emit ExternalTokenDecreaseApproval(_externalToken,_spender, _subtractedValue);
return true;
}
}
// File: contracts/globalConstraints/GlobalConstraintInterface.sol
contract GlobalConstraintInterface {
enum CallPhase { Pre, Post,PreAndPost }
function pre( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
function post( address _scheme, bytes32 _params, bytes32 _method ) public returns(bool);
/**
* @dev when return if this globalConstraints is pre, post or both.
* @return CallPhase enum indication Pre, Post or PreAndPost.
*/
function when() public returns(CallPhase);
}
// File: contracts/controller/ControllerInterface.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens ,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
interface ControllerInterface {
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
returns(bool);
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
returns(bool);
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @param _avatar address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
returns(bool);
/**
* @dev register or update a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @param _avatar address
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
returns(bool);
/**
* @dev unregister a scheme
* @param _avatar address
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme(address _scheme,address _avatar)
external
returns(bool);
/**
* @dev unregister the caller's scheme
* @param _avatar address
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external returns(bool);
function isSchemeRegistered( address _scheme,address _avatar) external view returns(bool);
function getSchemeParameters(address _scheme,address _avatar) external view returns(bytes32);
function getGlobalConstraintParameters(address _globalConstraint,address _avatar) external view returns(bytes32);
function getSchemePermissions(address _scheme,address _avatar) external view returns(bytes4);
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar) external view returns(uint,uint);
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar) external view returns(bool);
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @param _avatar the avatar of the organization
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external returns(bool);
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @param _avatar the organization avatar.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external returns(bool);
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @param _avatar address
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external returns(bool);
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
returns(bytes32);
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @param _avatar address
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external returns(bool);
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
returns(bool);
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
returns(bool);
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @param _avatar address
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
returns(bool);
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar)
external
view
returns(address);
}
// File: contracts/controller/Controller.sol
/**
* @title Controller contract
* @dev A controller controls the organizations tokens,reputation and avatar.
* It is subject to a set of schemes and constraints that determine its behavior.
* Each scheme has it own parameters and operation permissions.
*/
contract Controller is ControllerInterface {
struct Scheme {
bytes32 paramsHash; // a hash "configuration" of the scheme
bytes4 permissions; // A bitwise flags of permissions,
// All 0: Not registered,
// 1st bit: Flag if the scheme is registered,
// 2nd bit: Scheme can register other schemes
// 3rd bit: Scheme can add/remove global constraints
// 4th bit: Scheme can upgrade the controller
// 5th bit: Scheme can call genericCall on behalf of
// the organization avatar
}
struct GlobalConstraint {
address gcAddress;
bytes32 params;
}
struct GlobalConstraintRegister {
bool isRegistered; //is registered
uint index; //index at globalConstraints
}
mapping(address=>Scheme) public schemes;
Avatar public avatar;
DAOToken public nativeToken;
Reputation public nativeReputation;
// newController will point to the new controller after the present controller is upgraded
address public newController;
// globalConstraintsPre that determine pre conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPre;
// globalConstraintsPost that determine post conditions for all actions on the controller
GlobalConstraint[] public globalConstraintsPost;
// globalConstraintsRegisterPre indicate if a globalConstraints is registered as a pre global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPre;
// globalConstraintsRegisterPost indicate if a globalConstraints is registered as a post global constraint
mapping(address=>GlobalConstraintRegister) public globalConstraintsRegisterPost;
event MintReputation (address indexed _sender, address indexed _to, uint256 _amount);
event BurnReputation (address indexed _sender, address indexed _from, uint256 _amount);
event MintTokens (address indexed _sender, address indexed _beneficiary, uint256 _amount);
event RegisterScheme (address indexed _sender, address indexed _scheme);
event UnregisterScheme (address indexed _sender, address indexed _scheme);
event GenericAction (address indexed _sender, bytes32[] _params);
event SendEther (address indexed _sender, uint _amountInWei, address indexed _to);
event ExternalTokenTransfer (address indexed _sender, address indexed _externalToken, address indexed _to, uint _value);
event ExternalTokenTransferFrom (address indexed _sender, address indexed _externalToken, address _from, address _to, uint _value);
event ExternalTokenIncreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event ExternalTokenDecreaseApproval (address indexed _sender, StandardToken indexed _externalToken, address _spender, uint _value);
event UpgradeController(address indexed _oldController,address _newController);
event AddGlobalConstraint(address indexed _globalConstraint, bytes32 _params,GlobalConstraintInterface.CallPhase _when);
event RemoveGlobalConstraint(address indexed _globalConstraint ,uint256 _index,bool _isPre);
event GenericCall(address indexed _contract,bytes _data);
constructor( Avatar _avatar) public
{
avatar = _avatar;
nativeToken = avatar.nativeToken();
nativeReputation = avatar.nativeReputation();
schemes[msg.sender] = Scheme({paramsHash: bytes32(0),permissions: bytes4(0x1F)});
}
// Do not allow mistaken calls:
function() external {
revert();
}
// Modifiers:
modifier onlyRegisteredScheme() {
require(schemes[msg.sender].permissions&bytes4(1) == bytes4(1));
_;
}
modifier onlyRegisteringSchemes() {
require(schemes[msg.sender].permissions&bytes4(2) == bytes4(2));
_;
}
modifier onlyGlobalConstraintsScheme() {
require(schemes[msg.sender].permissions&bytes4(4) == bytes4(4));
_;
}
modifier onlyUpgradingScheme() {
require(schemes[msg.sender].permissions&bytes4(8) == bytes4(8));
_;
}
modifier onlyGenericCallScheme() {
require(schemes[msg.sender].permissions&bytes4(16) == bytes4(16));
_;
}
modifier onlySubjectToConstraint(bytes32 func) {
uint idx;
for (idx = 0;idx<globalConstraintsPre.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPre[idx].gcAddress)).pre(msg.sender,globalConstraintsPre[idx].params,func));
}
_;
for (idx = 0;idx<globalConstraintsPost.length;idx++) {
require((GlobalConstraintInterface(globalConstraintsPost[idx].gcAddress)).post(msg.sender,globalConstraintsPost[idx].params,func));
}
}
modifier isAvatarValid(address _avatar) {
require(_avatar == address(avatar));
_;
}
/**
* @dev Mint `_amount` of reputation that are assigned to `_to` .
* @param _amount amount of reputation to mint
* @param _to beneficiary address
* @return bool which represents a success
*/
function mintReputation(uint256 _amount, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit MintReputation(msg.sender, _to, _amount);
return nativeReputation.mint(_to, _amount);
}
/**
* @dev Burns `_amount` of reputation from `_from`
* @param _amount amount of reputation to burn
* @param _from The address that will lose the reputation
* @return bool which represents a success
*/
function burnReputation(uint256 _amount, address _from,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("burnReputation")
isAvatarValid(_avatar)
returns(bool)
{
emit BurnReputation(msg.sender, _from, _amount);
return nativeReputation.burn(_from, _amount);
}
/**
* @dev mint tokens .
* @param _amount amount of token to mint
* @param _beneficiary beneficiary address
* @return bool which represents a success
*/
function mintTokens(uint256 _amount, address _beneficiary,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("mintTokens")
isAvatarValid(_avatar)
returns(bool)
{
emit MintTokens(msg.sender, _beneficiary, _amount);
return nativeToken.mint(_beneficiary, _amount);
}
/**
* @dev register a scheme
* @param _scheme the address of the scheme
* @param _paramsHash a hashed configuration of the usage of the scheme
* @param _permissions the permissions the new scheme will have
* @return bool which represents a success
*/
function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("registerScheme")
isAvatarValid(_avatar)
returns(bool)
{
Scheme memory scheme = schemes[_scheme];
// Check scheme has at least the permissions it is changing, and at least the current permissions:
// Implementation is a bit messy. One must recall logic-circuits ^^
// produces non-zero if sender does not have all of the perms that are changing between old and new
require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0));
// produces non-zero if sender does not have all of the perms in the old scheme
require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Add or change the scheme:
schemes[_scheme].paramsHash = _paramsHash;
schemes[_scheme].permissions = _permissions|bytes4(1);
emit RegisterScheme(msg.sender, _scheme);
return true;
}
/**
* @dev unregister a scheme
* @param _scheme the address of the scheme
* @return bool which represents a success
*/
function unregisterScheme( address _scheme,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("unregisterScheme")
isAvatarValid(_avatar)
returns(bool)
{
//check if the scheme is registered
if (schemes[_scheme].permissions&bytes4(1) == bytes4(0)) {
return false;
}
// Check the unregistering scheme has enough permissions:
require(bytes4(0x1F)&(schemes[_scheme].permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
// Unregister:
emit UnregisterScheme(msg.sender, _scheme);
delete schemes[_scheme];
return true;
}
/**
* @dev unregister the caller's scheme
* @return bool which represents a success
*/
function unregisterSelf(address _avatar) external isAvatarValid(_avatar) returns(bool) {
if (_isSchemeRegistered(msg.sender,_avatar) == false) {
return false;
}
delete schemes[msg.sender];
emit UnregisterScheme(msg.sender, msg.sender);
return true;
}
function isSchemeRegistered(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bool) {
return _isSchemeRegistered(_scheme,_avatar);
}
function getSchemeParameters(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes32) {
return schemes[_scheme].paramsHash;
}
function getSchemePermissions(address _scheme,address _avatar) external isAvatarValid(_avatar) view returns(bytes4) {
return schemes[_scheme].permissions;
}
function getGlobalConstraintParameters(address _globalConstraint,address) external view returns(bytes32) {
GlobalConstraintRegister memory register = globalConstraintsRegisterPre[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPre[register.index].params;
}
register = globalConstraintsRegisterPost[_globalConstraint];
if (register.isRegistered) {
return globalConstraintsPost[register.index].params;
}
}
/**
* @dev globalConstraintsCount return the global constraint pre and post count
* @return uint globalConstraintsPre count.
* @return uint globalConstraintsPost count.
*/
function globalConstraintsCount(address _avatar)
external
isAvatarValid(_avatar)
view
returns(uint,uint)
{
return (globalConstraintsPre.length,globalConstraintsPost.length);
}
function isGlobalConstraintRegistered(address _globalConstraint,address _avatar)
external
isAvatarValid(_avatar)
view
returns(bool)
{
return (globalConstraintsRegisterPre[_globalConstraint].isRegistered || globalConstraintsRegisterPost[_globalConstraint].isRegistered);
}
/**
* @dev add or update Global Constraint
* @param _globalConstraint the address of the global constraint to be added.
* @param _params the constraint parameters hash.
* @return bool which represents a success
*/
function addGlobalConstraint(address _globalConstraint, bytes32 _params,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPre[_globalConstraint].isRegistered) {
globalConstraintsPre.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPre[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPre.length-1);
}else {
globalConstraintsPre[globalConstraintsRegisterPre[_globalConstraint].index].params = _params;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
if (!globalConstraintsRegisterPost[_globalConstraint].isRegistered) {
globalConstraintsPost.push(GlobalConstraint(_globalConstraint,_params));
globalConstraintsRegisterPost[_globalConstraint] = GlobalConstraintRegister(true,globalConstraintsPost.length-1);
}else {
globalConstraintsPost[globalConstraintsRegisterPost[_globalConstraint].index].params = _params;
}
}
emit AddGlobalConstraint(_globalConstraint, _params,when);
return true;
}
/**
* @dev remove Global Constraint
* @param _globalConstraint the address of the global constraint to be remove.
* @return bool which represents a success
*/
function removeGlobalConstraint (address _globalConstraint,address _avatar)
external
onlyGlobalConstraintsScheme
isAvatarValid(_avatar)
returns(bool)
{
GlobalConstraintRegister memory globalConstraintRegister;
GlobalConstraint memory globalConstraint;
GlobalConstraintInterface.CallPhase when = GlobalConstraintInterface(_globalConstraint).when();
bool retVal = false;
if ((when == GlobalConstraintInterface.CallPhase.Pre)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPre[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPre.length-1) {
globalConstraint = globalConstraintsPre[globalConstraintsPre.length-1];
globalConstraintsPre[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPre[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPre.length--;
delete globalConstraintsRegisterPre[_globalConstraint];
retVal = true;
}
}
if ((when == GlobalConstraintInterface.CallPhase.Post)||(when == GlobalConstraintInterface.CallPhase.PreAndPost)) {
globalConstraintRegister = globalConstraintsRegisterPost[_globalConstraint];
if (globalConstraintRegister.isRegistered) {
if (globalConstraintRegister.index < globalConstraintsPost.length-1) {
globalConstraint = globalConstraintsPost[globalConstraintsPost.length-1];
globalConstraintsPost[globalConstraintRegister.index] = globalConstraint;
globalConstraintsRegisterPost[globalConstraint.gcAddress].index = globalConstraintRegister.index;
}
globalConstraintsPost.length--;
delete globalConstraintsRegisterPost[_globalConstraint];
retVal = true;
}
}
if (retVal) {
emit RemoveGlobalConstraint(_globalConstraint,globalConstraintRegister.index,when == GlobalConstraintInterface.CallPhase.Pre);
}
return retVal;
}
/**
* @dev upgrade the Controller
* The function will trigger an event 'UpgradeController'.
* @param _newController the address of the new controller.
* @return bool which represents a success
*/
function upgradeController(address _newController,address _avatar)
external
onlyUpgradingScheme
isAvatarValid(_avatar)
returns(bool)
{
require(newController == address(0)); // so the upgrade could be done once for a contract.
require(_newController != address(0));
newController = _newController;
avatar.transferOwnership(_newController);
require(avatar.owner()==_newController);
if (nativeToken.owner() == address(this)) {
nativeToken.transferOwnership(_newController);
require(nativeToken.owner()==_newController);
}
if (nativeReputation.owner() == address(this)) {
nativeReputation.transferOwnership(_newController);
require(nativeReputation.owner()==_newController);
}
emit UpgradeController(this,newController);
return true;
}
/**
* @dev perform a generic call to an arbitrary contract
* @param _contract the contract's address to call
* @param _data ABI-encoded contract call to call `_contract` address.
* @param _avatar the controller's avatar address
* @return bytes32 - the return value of the called _contract's function.
*/
function genericCall(address _contract,bytes _data,address _avatar)
external
onlyGenericCallScheme
onlySubjectToConstraint("genericCall")
isAvatarValid(_avatar)
returns (bytes32)
{
emit GenericCall(_contract, _data);
avatar.genericCall(_contract, _data);
// solium-disable-next-line security/no-inline-assembly
assembly {
// Copy the returned data.
returndatacopy(0, 0, returndatasize)
return(0, returndatasize)
}
}
/**
* @dev send some ether
* @param _amountInWei the amount of ether (in Wei) to send
* @param _to address of the beneficiary
* @return bool which represents a success
*/
function sendEther(uint _amountInWei, address _to,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("sendEther")
isAvatarValid(_avatar)
returns(bool)
{
emit SendEther(msg.sender, _amountInWei, _to);
return avatar.sendEther(_amountInWei, _to);
}
/**
* @dev send some amount of arbitrary ERC20 Tokens
* @param _externalToken the address of the Token Contract
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransfer(StandardToken _externalToken, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransfer")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransfer(msg.sender, _externalToken, _to, _value);
return avatar.externalTokenTransfer(_externalToken, _to, _value);
}
/**
* @dev transfer token "from" address "to" address
* One must to approve the amount of tokens which can be spend from the
* "from" account.This can be done using externalTokenApprove.
* @param _externalToken the address of the Token Contract
* @param _from address of the account to send from
* @param _to address of the beneficiary
* @param _value the amount of ether (in Wei) to send
* @return bool which represents a success
*/
function externalTokenTransferFrom(StandardToken _externalToken, address _from, address _to, uint _value,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenTransferFrom")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenTransferFrom(msg.sender, _externalToken, _from, _to, _value);
return avatar.externalTokenTransferFrom(_externalToken, _from, _to, _value);
}
/**
* @dev increase approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _addedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenIncreaseApproval(StandardToken _externalToken, address _spender, uint _addedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenIncreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenIncreaseApproval(msg.sender,_externalToken,_spender,_addedValue);
return avatar.externalTokenIncreaseApproval(_externalToken, _spender, _addedValue);
}
/**
* @dev decrease approval for the spender address to spend a specified amount of tokens
* on behalf of msg.sender.
* @param _externalToken the address of the Token Contract
* @param _spender address
* @param _subtractedValue the amount of ether (in Wei) which the approval is referring to.
* @return bool which represents a success
*/
function externalTokenDecreaseApproval(StandardToken _externalToken, address _spender, uint _subtractedValue,address _avatar)
external
onlyRegisteredScheme
onlySubjectToConstraint("externalTokenDecreaseApproval")
isAvatarValid(_avatar)
returns(bool)
{
emit ExternalTokenDecreaseApproval(msg.sender,_externalToken,_spender,_subtractedValue);
return avatar.externalTokenDecreaseApproval(_externalToken, _spender, _subtractedValue);
}
/**
* @dev getNativeReputation
* @param _avatar the organization avatar.
* @return organization native reputation
*/
function getNativeReputation(address _avatar) external isAvatarValid(_avatar) view returns(address) {
return address(nativeReputation);
}
function _isSchemeRegistered(address _scheme,address _avatar) private isAvatarValid(_avatar) view returns(bool) {
return (schemes[_scheme].permissions&bytes4(1) != bytes4(0));
}
}
// File: contracts/universalSchemes/ExecutableInterface.sol
contract ExecutableInterface {
function execute(bytes32 _proposalId, address _avatar, int _param) public returns(bool);
}
// File: contracts/VotingMachines/IntVoteInterface.sol
interface IntVoteInterface {
//When implementing this interface please do not only override function and modifier,
//but also to keep the modifiers on the overridden functions.
modifier onlyProposalOwner(bytes32 _proposalId) {revert(); _;}
modifier votable(bytes32 _proposalId) {revert(); _;}
event NewProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _numOfChoices, address _proposer, bytes32 _paramsHash);
event ExecuteProposal(bytes32 indexed _proposalId, address indexed _avatar, uint _decision, uint _totalReputation);
event VoteProposal(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter, uint _vote, uint _reputation);
event CancelProposal(bytes32 indexed _proposalId, address indexed _avatar );
event CancelVoting(bytes32 indexed _proposalId, address indexed _avatar, address indexed _voter);
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _proposalParameters defines the parameters of the voting machine used for this proposal
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(
uint _numOfChoices,
bytes32 _proposalParameters,
address _avatar,
ExecutableInterface _executable,
address _proposer
) external returns(bytes32);
// Only owned proposals and only the owner:
function cancelProposal(bytes32 _proposalId) external returns(bool);
// Only owned proposals and only the owner:
function ownerVote(bytes32 _proposalId, uint _vote, address _voter) external returns(bool);
function vote(bytes32 _proposalId, uint _vote) external returns(bool);
function voteWithSpecifiedAmounts(
bytes32 _proposalId,
uint _vote,
uint _rep,
uint _token) external returns(bool);
function cancelVote(bytes32 _proposalId) external;
//@dev execute check if the proposal has been decided, and if so, execute the proposal
//@param _proposalId the id of the proposal
//@return bool true - the proposal has been executed
// false - otherwise.
function execute(bytes32 _proposalId) external returns(bool);
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint);
function isVotable(bytes32 _proposalId) external view returns(bool);
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint);
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool);
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max);
}
// File: contracts/universalSchemes/UniversalSchemeInterface.sol
contract UniversalSchemeInterface {
function updateParameters(bytes32 _hashedParameters) public;
function getParametersFromController(Avatar _avatar) internal view returns(bytes32);
}
// File: contracts/universalSchemes/UniversalScheme.sol
contract UniversalScheme is Ownable, UniversalSchemeInterface {
bytes32 public hashedParameters; // For other parameters.
function updateParameters(
bytes32 _hashedParameters
)
public
onlyOwner
{
hashedParameters = _hashedParameters;
}
/**
* @dev get the parameters for the current scheme from the controller
*/
function getParametersFromController(Avatar _avatar) internal view returns(bytes32) {
return ControllerInterface(_avatar.owner()).getSchemeParameters(this,address(_avatar));
}
}
// File: contracts/libs/RealMath.sol
/**
* RealMath: fixed-point math library, based on fractional and integer parts.
* Using int256 as real216x40, which isn't in Solidity yet.
* 40 fractional bits gets us down to 1E-12 precision, while still letting us
* go up to galaxy scale counting in meters.
* Internally uses the wider int256 for some math.
*
* Note that for addition, subtraction, and mod (%), you should just use the
* built-in Solidity operators. Functions for these operations are not provided.
*
* Note that the fancy functions like sqrt, atan2, etc. aren't as accurate as
* they should be. They are (hopefully) Good Enough for doing orbital mechanics
* on block timescales in a game context, but they may not be good enough for
* other applications.
*/
library RealMath {
/**
* How many total bits are there?
*/
int256 constant REAL_BITS = 256;
/**
* How many fractional bits are there?
*/
int256 constant REAL_FBITS = 40;
/**
* How many integer bits are there?
*/
int256 constant REAL_IBITS = REAL_BITS - REAL_FBITS;
/**
* What's the first non-fractional bit
*/
int256 constant REAL_ONE = int256(1) << REAL_FBITS;
/**
* What's the last fractional bit?
*/
int256 constant REAL_HALF = REAL_ONE >> 1;
/**
* What's two? Two is pretty useful.
*/
int256 constant REAL_TWO = REAL_ONE << 1;
/**
* And our logarithms are based on ln(2).
*/
int256 constant REAL_LN_TWO = 762123384786;
/**
* It is also useful to have Pi around.
*/
int256 constant REAL_PI = 3454217652358;
/**
* And half Pi, to save on divides.
* TODO: That might not be how the compiler handles constants.
*/
int256 constant REAL_HALF_PI = 1727108826179;
/**
* And two pi, which happens to be odd in its most accurate representation.
*/
int256 constant REAL_TWO_PI = 6908435304715;
/**
* What's the sign bit?
*/
int256 constant SIGN_MASK = int256(1) << 255;
/**
* Convert an integer to a real. Preserves sign.
*/
function toReal(int216 ipart) internal pure returns (int256) {
return int256(ipart) * REAL_ONE;
}
/**
* Convert a real to an integer. Preserves sign.
*/
function fromReal(int256 realValue) internal pure returns (int216) {
return int216(realValue / REAL_ONE);
}
/**
* Round a real to the nearest integral real value.
*/
function round(int256 realValue) internal pure returns (int256) {
// First, truncate.
int216 ipart = fromReal(realValue);
if ((fractionalBits(realValue) & (uint40(1) << (REAL_FBITS - 1))) > 0) {
// High fractional bit is set. Round up.
if (realValue < int256(0)) {
// Rounding up for a negative number is rounding down.
ipart -= 1;
} else {
ipart += 1;
}
}
return toReal(ipart);
}
/**
* Get the absolute value of a real. Just the same as abs on a normal int256.
*/
function abs(int256 realValue) internal pure returns (int256) {
if (realValue > 0) {
return realValue;
} else {
return -realValue;
}
}
/**
* Returns the fractional bits of a real. Ignores the sign of the real.
*/
function fractionalBits(int256 realValue) internal pure returns (uint40) {
return uint40(abs(realValue) % REAL_ONE);
}
/**
* Get the fractional part of a real, as a real. Ignores sign (so fpart(-0.5) is 0.5).
*/
function fpart(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
return abs(realValue) % REAL_ONE;
}
/**
* Get the fractional part of a real, as a real. Respects sign (so fpartSigned(-0.5) is -0.5).
*/
function fpartSigned(int256 realValue) internal pure returns (int256) {
// This gets the fractional part but strips the sign
int256 fractional = fpart(realValue);
if (realValue < 0) {
// Add the negative sign back in.
return -fractional;
} else {
return fractional;
}
}
/**
* Get the integer part of a fixed point value.
*/
function ipart(int256 realValue) internal pure returns (int256) {
// Subtract out the fractional part to get the real part.
return realValue - fpartSigned(realValue);
}
/**
* Multiply one real by another. Truncates overflows.
*/
function mul(int256 realA, int256 realB) internal pure returns (int256) {
// When multiplying fixed point in x.y and z.w formats we get (x+z).(y+w) format.
// So we just have to clip off the extra REAL_FBITS fractional bits.
return int256((int256(realA) * int256(realB)) >> REAL_FBITS);
}
/**
* Divide one real by another real. Truncates overflows.
*/
function div(int256 realNumerator, int256 realDenominator) internal pure returns (int256) {
// We use the reverse of the multiplication trick: convert numerator from
// x.y to (x+z).(y+w) fixed point, then divide by denom in z.w fixed point.
return int256((int256(realNumerator) * REAL_ONE) / int256(realDenominator));
}
/**
* Create a real from a rational fraction.
*/
function fraction(int216 numerator, int216 denominator) internal pure returns (int256) {
return div(toReal(numerator), toReal(denominator));
}
// Now we have some fancy math things (like pow and trig stuff). This isn't
// in the RealMath that was deployed with the original Macroverse
// deployment, so it needs to be linked into your contract statically.
/**
* Raise a number to a positive integer power in O(log power) time.
* See <https://stackoverflow.com/a/101613>
*/
function ipow(int256 realBase, int216 exponent) internal pure returns (int256) {
if (exponent < 0) {
// Negative powers are not allowed here.
revert();
}
int256 tempRealBase = realBase;
int256 tempExponent = exponent;
// Start with the 0th power
int256 realResult = REAL_ONE;
while (tempExponent != 0) {
// While there are still bits set
if ((tempExponent & 0x1) == 0x1) {
// If the low bit is set, multiply in the (many-times-squared) base
realResult = mul(realResult, tempRealBase);
}
// Shift off the low bit
tempExponent = tempExponent >> 1;
// Do the squaring
tempRealBase = mul(tempRealBase, tempRealBase);
}
// Return the final result.
return realResult;
}
/**
* Zero all but the highest set bit of a number.
* See <https://stackoverflow.com/a/53184>
*/
function hibit(uint256 _val) internal pure returns (uint256) {
// Set all the bits below the highest set bit
uint256 val = _val;
val |= (val >> 1);
val |= (val >> 2);
val |= (val >> 4);
val |= (val >> 8);
val |= (val >> 16);
val |= (val >> 32);
val |= (val >> 64);
val |= (val >> 128);
return val ^ (val >> 1);
}
/**
* Given a number with one bit set, finds the index of that bit.
*/
function findbit(uint256 val) internal pure returns (uint8 index) {
index = 0;
// We and the value with alternating bit patters of various pitches to find it.
if (val & 0xAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA != 0) {
// Picth 1
index |= 1;
}
if (val & 0xCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC != 0) {
// Pitch 2
index |= 2;
}
if (val & 0xF0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0F0 != 0) {
// Pitch 4
index |= 4;
}
if (val & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00 != 0) {
// Pitch 8
index |= 8;
}
if (val & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000 != 0) {
// Pitch 16
index |= 16;
}
if (val & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000 != 0) {
// Pitch 32
index |= 32;
}
if (val & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000 != 0) {
// Pitch 64
index |= 64;
}
if (val & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000000000000000000000000000 != 0) {
// Pitch 128
index |= 128;
}
}
/**
* Shift realArg left or right until it is between 1 and 2. Return the
* rescaled value, and the number of bits of right shift applied. Shift may be negative.
*
* Expresses realArg as realScaled * 2^shift, setting shift to put realArg between [1 and 2).
*
* Rejects 0 or negative arguments.
*/
function rescale(int256 realArg) internal pure returns (int256 realScaled, int216 shift) {
if (realArg <= 0) {
// Not in domain!
revert();
}
// Find the high bit
int216 highBit = findbit(hibit(uint256(realArg)));
// We'll shift so the high bit is the lowest non-fractional bit.
shift = highBit - int216(REAL_FBITS);
if (shift < 0) {
// Shift left
realScaled = realArg << -shift;
} else if (shift >= 0) {
// Shift right
realScaled = realArg >> shift;
}
}
/**
* Calculate the natural log of a number. Rescales the input value and uses
* the algorithm outlined at <https://math.stackexchange.com/a/977836> and
* the ipow implementation.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function lnLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
if (realArg <= 0) {
// Outside of acceptable domain
revert();
}
if (realArg == REAL_ONE) {
// Handle this case specially because people will want exactly 0 and
// not ~2^-39 ish.
return 0;
}
// We know it's positive, so rescale it to be between [1 and 2)
int256 realRescaled;
int216 shift;
(realRescaled, shift) = rescale(realArg);
// Compute the argument to iterate on
int256 realSeriesArg = div(realRescaled - REAL_ONE, realRescaled + REAL_ONE);
// We will accumulate the result here
int256 realSeriesResult = 0;
for (int216 n = 0; n < maxIterations; n++) {
// Compute term n of the series
int256 realTerm = div(ipow(realSeriesArg, 2 * n + 1), toReal(2 * n + 1));
// And add it in
realSeriesResult += realTerm;
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Double it to account for the factor of 2 outside the sum
realSeriesResult = mul(realSeriesResult, REAL_TWO);
// Now compute and return the overall result
return mul(toReal(shift), REAL_LN_TWO) + realSeriesResult;
}
/**
* Calculate a natural logarithm with a sensible maximum iteration count to
* wait until convergence. Note that it is potentially possible to get an
* un-converged value; lack of convergence does not throw.
*/
function ln(int256 realArg) internal pure returns (int256) {
return lnLimited(realArg, 100);
}
/**
* Calculate e^x. Uses the series given at
* <http://pages.mtu.edu/~shene/COURSES/cs201/NOTES/chap04/exp.html>.
*
* Lets you artificially limit the number of iterations.
*
* Note that it is potentially possible to get an un-converged value; lack
* of convergence does not throw.
*/
function expLimited(int256 realArg, int maxIterations) internal pure returns (int256) {
// We will accumulate the result here
int256 realResult = 0;
// We use this to save work computing terms
int256 realTerm = REAL_ONE;
for (int216 n = 0; n < maxIterations; n++) {
// Add in the term
realResult += realTerm;
// Compute the next term
realTerm = mul(realTerm, div(realArg, toReal(n + 1)));
if (realTerm == 0) {
// We must have converged. Next term is too small to represent.
break;
}
// If we somehow never converge I guess we will run out of gas
}
// Return the result
return realResult;
}
/**
* Calculate e^x with a sensible maximum iteration count to wait until
* convergence. Note that it is potentially possible to get an un-converged
* value; lack of convergence does not throw.
*/
function exp(int256 realArg) internal pure returns (int256) {
return expLimited(realArg, 100);
}
/**
* Raise any number to any power, except for negative bases to fractional powers.
*/
function pow(int256 realBase, int256 realExponent) internal pure returns (int256) {
if (realExponent == 0) {
// Anything to the 0 is 1
return REAL_ONE;
}
if (realBase == 0) {
if (realExponent < 0) {
// Outside of domain!
revert();
}
// Otherwise it's 0
return 0;
}
if (fpart(realExponent) == 0) {
// Anything (even a negative base) is super easy to do to an integer power.
if (realExponent > 0) {
// Positive integer power is easy
return ipow(realBase, fromReal(realExponent));
} else {
// Negative integer power is harder
return div(REAL_ONE, ipow(realBase, fromReal(-realExponent)));
}
}
if (realBase < 0) {
// It's a negative base to a non-integer power.
// In general pow(-x^y) is undefined, unless y is an int or some
// weird rational-number-based relationship holds.
revert();
}
// If it's not a special case, actually do it.
return exp(mul(realExponent, ln(realBase)));
}
/**
* Compute the square root of a number.
*/
function sqrt(int256 realArg) internal pure returns (int256) {
return pow(realArg, REAL_HALF);
}
/**
* Compute the sin of a number to a certain number of Taylor series terms.
*/
function sinLimited(int256 _realArg, int216 maxIterations) internal pure returns (int256) {
// First bring the number into 0 to 2 pi
// TODO: This will introduce an error for very large numbers, because the error in our Pi will compound.
// But for actual reasonable angle values we should be fine.
int256 realArg = _realArg;
realArg = realArg % REAL_TWO_PI;
int256 accumulator = REAL_ONE;
// We sum from large to small iteration so that we can have higher powers in later terms
for (int216 iteration = maxIterations - 1; iteration >= 0; iteration--) {
accumulator = REAL_ONE - mul(div(mul(realArg, realArg), toReal((2 * iteration + 2) * (2 * iteration + 3))), accumulator);
// We can't stop early; we need to make it to the first term.
}
return mul(realArg, accumulator);
}
/**
* Calculate sin(x) with a sensible maximum iteration count to wait until
* convergence.
*/
function sin(int256 realArg) internal pure returns (int256) {
return sinLimited(realArg, 15);
}
/**
* Calculate cos(x).
*/
function cos(int256 realArg) internal pure returns (int256) {
return sin(realArg + REAL_HALF_PI);
}
/**
* Calculate tan(x). May overflow for large results. May throw if tan(x)
* would be infinite, or return an approximation, or overflow.
*/
function tan(int256 realArg) internal pure returns (int256) {
return div(sin(realArg), cos(realArg));
}
}
// File: openzeppelin-solidity/contracts/ECRecovery.sol
/**
* @title Eliptic curve signature operations
*
* @dev Based on https://gist.github.com/axic/5b33912c6f61ae6fd96d6c4a47afde6d
*
* TODO Remove this library once solidity supports passing a signature to ecrecover.
* See https://github.com/ethereum/solidity/issues/864
*
*/
library ECRecovery {
/**
* @dev Recover signer address from a message by using their signature
* @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address.
* @param sig bytes signature, the signature is generated using web3.eth.sign()
*/
function recover(bytes32 hash, bytes sig)
internal
pure
returns (address)
{
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
if (sig.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solium-disable-next-line security/no-inline-assembly
assembly {
r := mload(add(sig, 32))
s := mload(add(sig, 64))
v := byte(0, mload(add(sig, 96)))
}
// Version of signature should be 27 or 28, but 0 and 1 are also possible versions
if (v < 27) {
v += 27;
}
// If the version is correct return the signer address
if (v != 27 && v != 28) {
return (address(0));
} else {
// solium-disable-next-line arg-overflow
return ecrecover(hash, v, r, s);
}
}
/**
* toEthSignedMessageHash
* @dev prefix a bytes32 value with "\x19Ethereum Signed Message:"
* @dev and hash the result
*/
function toEthSignedMessageHash(bytes32 hash)
internal
pure
returns (bytes32)
{
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(
"\x19Ethereum Signed Message:\n32",
hash
);
}
}
// File: contracts/libs/OrderStatisticTree.sol
library OrderStatisticTree {
struct Node {
mapping (bool => uint) children; // a mapping of left(false) child and right(true) child nodes
uint parent; // parent node
bool side; // side of the node on the tree (left or right)
uint height; //Height of this node
uint count; //Number of tree nodes below this node (including this one)
uint dupes; //Number of duplicates values for this node
}
struct Tree {
// a mapping between node value(uint) to Node
// the tree's root is always at node 0 ,which points to the "real" tree
// as its right child.this is done to eliminate the need to update the tree
// root in the case of rotation.(saving gas).
mapping(uint => Node) nodes;
}
/**
* @dev rank - find the rank of a value in the tree,
* i.e. its index in the sorted list of elements of the tree
* @param _tree the tree
* @param _value the input value to find its rank.
* @return smaller - the number of elements in the tree which their value is
* less than the input value.
*/
function rank(Tree storage _tree,uint _value) internal view returns (uint smaller) {
if (_value != 0) {
smaller = _tree.nodes[0].dupes;
uint cur = _tree.nodes[0].children[true];
Node storage currentNode = _tree.nodes[cur];
while (true) {
if (cur <= _value) {
if (cur<_value) {
smaller = smaller + 1+currentNode.dupes;
}
uint leftChild = currentNode.children[false];
if (leftChild!=0) {
smaller = smaller + _tree.nodes[leftChild].count;
}
}
if (cur == _value) {
break;
}
cur = currentNode.children[cur<_value];
if (cur == 0) {
break;
}
currentNode = _tree.nodes[cur];
}
}
}
function count(Tree storage _tree) internal view returns (uint) {
Node storage root = _tree.nodes[0];
Node memory child = _tree.nodes[root.children[true]];
return root.dupes+child.count;
}
function updateCount(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.count = 1+_tree.nodes[n.children[false]].count+_tree.nodes[n.children[true]].count+n.dupes;
}
function updateCounts(Tree storage _tree,uint _value) private {
uint parent = _tree.nodes[_value].parent;
while (parent!=0) {
updateCount(_tree,parent);
parent = _tree.nodes[parent].parent;
}
}
function updateHeight(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint heightLeft = _tree.nodes[n.children[false]].height;
uint heightRight = _tree.nodes[n.children[true]].height;
if (heightLeft > heightRight)
n.height = heightLeft+1;
else
n.height = heightRight+1;
}
function balanceFactor(Tree storage _tree,uint _value) private view returns (int bf) {
Node storage n = _tree.nodes[_value];
return int(_tree.nodes[n.children[false]].height)-int(_tree.nodes[n.children[true]].height);
}
function rotate(Tree storage _tree,uint _value,bool dir) private {
bool otherDir = !dir;
Node storage n = _tree.nodes[_value];
bool side = n.side;
uint parent = n.parent;
uint valueNew = n.children[otherDir];
Node storage nNew = _tree.nodes[valueNew];
uint orphan = nNew.children[dir];
Node storage p = _tree.nodes[parent];
Node storage o = _tree.nodes[orphan];
p.children[side] = valueNew;
nNew.side = side;
nNew.parent = parent;
nNew.children[dir] = _value;
n.parent = valueNew;
n.side = dir;
n.children[otherDir] = orphan;
o.parent = _value;
o.side = otherDir;
updateHeight(_tree,_value);
updateHeight(_tree,valueNew);
updateCount(_tree,_value);
updateCount(_tree,valueNew);
}
function rebalanceInsert(Tree storage _tree,uint _nValue) private {
updateHeight(_tree,_nValue);
Node storage n = _tree.nodes[_nValue];
uint pValue = n.parent;
if (pValue!=0) {
int pBf = balanceFactor(_tree,pValue);
bool side = n.side;
int sign;
if (side)
sign = -1;
else
sign = 1;
if (pBf == sign*2) {
if (balanceFactor(_tree,_nValue) == (-1 * sign)) {
rotate(_tree,_nValue,side);
}
rotate(_tree,pValue,!side);
} else if (pBf != 0) {
rebalanceInsert(_tree,pValue);
}
}
}
function rebalanceDelete(Tree storage _tree,uint _pValue,bool side) private {
if (_pValue!=0) {
updateHeight(_tree,_pValue);
int pBf = balanceFactor(_tree,_pValue);
int sign;
if (side)
sign = 1;
else
sign = -1;
int bf = balanceFactor(_tree,_pValue);
if (bf==(2*sign)) {
Node storage p = _tree.nodes[_pValue];
uint sValue = p.children[!side];
int sBf = balanceFactor(_tree,sValue);
if (sBf == (-1 * sign)) {
rotate(_tree,sValue,!side);
}
rotate(_tree,_pValue,side);
if (sBf!=0) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
} else if (pBf != sign) {
p = _tree.nodes[_pValue];
rebalanceDelete(_tree,p.parent,p.side);
}
}
}
function fixParents(Tree storage _tree,uint parent,bool side) private {
if (parent!=0) {
updateCount(_tree,parent);
updateCounts(_tree,parent);
rebalanceDelete(_tree,parent,side);
}
}
function insertHelper(Tree storage _tree,uint _pValue,bool _side,uint _value) private {
Node storage root = _tree.nodes[_pValue];
uint cValue = root.children[_side];
if (cValue==0) {
root.children[_side] = _value;
Node storage child = _tree.nodes[_value];
child.parent = _pValue;
child.side = _side;
child.height = 1;
child.count = 1;
updateCounts(_tree,_value);
rebalanceInsert(_tree,_value);
} else if (cValue==_value) {
_tree.nodes[cValue].dupes++;
updateCount(_tree,_value);
updateCounts(_tree,_value);
} else {
insertHelper(_tree,cValue,(_value >= cValue),_value);
}
}
function insert(Tree storage _tree,uint _value) internal {
if (_value==0) {
_tree.nodes[_value].dupes++;
} else {
insertHelper(_tree,0,true,_value);
}
}
function rightmostLeaf(Tree storage _tree,uint _value) private view returns (uint leaf) {
uint child = _tree.nodes[_value].children[true];
if (child!=0) {
return rightmostLeaf(_tree,child);
} else {
return _value;
}
}
function zeroOut(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
n.parent = 0;
n.side = false;
n.children[false] = 0;
n.children[true] = 0;
n.count = 0;
n.height = 0;
n.dupes = 0;
}
function removeBranch(Tree storage _tree,uint _value,uint _left) private {
uint ipn = rightmostLeaf(_tree,_left);
Node storage i = _tree.nodes[ipn];
uint dupes = i.dupes;
removeHelper(_tree,ipn);
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
Node storage p = _tree.nodes[parent];
uint height = n.height;
bool side = n.side;
uint ncount = n.count;
uint right = n.children[true];
uint left = n.children[false];
p.children[side] = ipn;
i.parent = parent;
i.side = side;
i.count = ncount+dupes-n.dupes;
i.height = height;
i.dupes = dupes;
if (left!=0) {
i.children[false] = left;
_tree.nodes[left].parent = ipn;
}
if (right!=0) {
i.children[true] = right;
_tree.nodes[right].parent = ipn;
}
zeroOut(_tree,_value);
updateCounts(_tree,ipn);
}
function removeHelper(Tree storage _tree,uint _value) private {
Node storage n = _tree.nodes[_value];
uint parent = n.parent;
bool side = n.side;
Node storage p = _tree.nodes[parent];
uint left = n.children[false];
uint right = n.children[true];
if ((left == 0) && (right == 0)) {
p.children[side] = 0;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
} else if ((left != 0) && (right != 0)) {
removeBranch(_tree,_value,left);
} else {
uint child = left+right;
Node storage c = _tree.nodes[child];
p.children[side] = child;
c.parent = parent;
c.side = side;
zeroOut(_tree,_value);
fixParents(_tree,parent,side);
}
}
function remove(Tree storage _tree,uint _value) internal {
Node storage n = _tree.nodes[_value];
if (_value==0) {
if (n.dupes==0) {
return;
}
} else {
if (n.count==0) {
return;
}
}
if (n.dupes>0) {
n.dupes--;
if (_value!=0) {
n.count--;
}
fixParents(_tree,n.parent,n.side);
} else {
removeHelper(_tree,_value);
}
}
}
// File: contracts/VotingMachines/GenesisProtocol.sol
/**
* @title GenesisProtocol implementation -an organization's voting machine scheme.
*/
contract GenesisProtocol is IntVoteInterface,UniversalScheme {
using SafeMath for uint;
using RealMath for int216;
using RealMath for int256;
using ECRecovery for bytes32;
using OrderStatisticTree for OrderStatisticTree.Tree;
enum ProposalState { None ,Closed, Executed, PreBoosted,Boosted,QuietEndingPeriod }
enum ExecutionState { None, PreBoostedTimeOut, PreBoostedBarCrossed, BoostedTimeOut,BoostedBarCrossed }
//Organization's parameters
struct Parameters {
uint preBoostedVoteRequiredPercentage; // the absolute vote percentages bar.
uint preBoostedVotePeriodLimit; //the time limit for a proposal to be in an absolute voting mode.
uint boostedVotePeriodLimit; //the time limit for a proposal to be in an relative voting mode.
uint thresholdConstA;//constant A for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint thresholdConstB;//constant B for threshold calculation . threshold =A * (e ** (numberOfBoostedProposals/B))
uint minimumStakingFee; //minimum staking fee allowed.
uint quietEndingPeriod; //quite ending period
uint proposingRepRewardConstA;//constant A for calculate proposer reward. proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint proposingRepRewardConstB;//constant B for calculate proposing reward.proposerReward =(A*(RTotal) +B*(R+ - R-))/1000
uint stakerFeeRatioForVoters; // The “ratio of stake” to be paid to voters.
// All stakers pay a portion of their stake to all voters, stakerFeeRatioForVoters * (s+ + s-).
//All voters (pre and during boosting period) divide this portion in proportion to their reputation.
uint votersReputationLossRatio;//Unsuccessful pre booster voters lose votersReputationLossRatio% of their reputation.
uint votersGainRepRatioFromLostRep; //the percentages of the lost reputation which is divided by the successful pre boosted voters,
//in proportion to their reputation.
//The rest (100-votersGainRepRatioFromLostRep)% of lost reputation is divided between the successful wagers,
//in proportion to their stake.
uint daoBountyConst;//The DAO adds up a bounty for successful staker.
//The bounty formula is: s * daoBountyConst, where s+ is the wager staked for the proposal,
//and daoBountyConst is a constant factor that is configurable and changeable by the DAO given.
// daoBountyConst should be greater than stakerFeeRatioForVoters and less than 2 * stakerFeeRatioForVoters.
uint daoBountyLimit;//The daoBounty cannot be greater than daoBountyLimit.
}
struct Voter {
uint vote; // YES(1) ,NO(2)
uint reputation; // amount of voter's reputation
bool preBoosted;
}
struct Staker {
uint vote; // YES(1) ,NO(2)
uint amount; // amount of staker's stake
uint amountForBounty; // amount of staker's stake which will be use for bounty calculation
}
struct Proposal {
address avatar; // the organization's avatar the proposal is target to.
uint numOfChoices;
ExecutableInterface executable; // will be executed if the proposal will pass
uint votersStakes;
uint submittedTime;
uint boostedPhaseTime; //the time the proposal shift to relative mode.
ProposalState state;
uint winningVote; //the winning vote.
address proposer;
uint currentBoostedVotePeriodLimit;
bytes32 paramsHash;
uint daoBountyRemain;
uint[2] totalStakes;// totalStakes[0] - (amount staked minus fee) - Total number of tokens staked which can be redeemable by stakers.
// totalStakes[1] - (amount staked) - Total number of redeemable tokens.
// vote reputation
mapping(uint => uint ) votes;
// vote reputation
mapping(uint => uint ) preBoostedVotes;
// address voter
mapping(address => Voter ) voters;
// vote stakes
mapping(uint => uint ) stakes;
// address staker
mapping(address => Staker ) stakers;
}
event GPExecuteProposal(bytes32 indexed _proposalId, ExecutionState _executionState);
event Stake(bytes32 indexed _proposalId, address indexed _avatar, address indexed _staker,uint _vote,uint _amount);
event Redeem(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemDaoBounty(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
event RedeemReputation(bytes32 indexed _proposalId, address indexed _avatar, address indexed _beneficiary,uint _amount);
mapping(bytes32=>Parameters) public parameters; // A mapping from hashes to parameters
mapping(bytes32=>Proposal) public proposals; // Mapping from the ID of the proposal to the proposal itself.
mapping(bytes=>bool) stakeSignatures; //stake signatures
uint constant public NUM_OF_CHOICES = 2;
uint constant public NO = 2;
uint constant public YES = 1;
uint public proposalsCnt; // Total number of proposals
mapping(address=>uint) orgBoostedProposalsCnt;
StandardToken public stakingToken;
mapping(address=>OrderStatisticTree.Tree) proposalsExpiredTimes; //proposals expired times
/**
* @dev Constructor
*/
constructor(StandardToken _stakingToken) public
{
stakingToken = _stakingToken;
}
/**
* @dev Check that the proposal is votable (open and not executed yet)
*/
modifier votable(bytes32 _proposalId) {
require(_isVotable(_proposalId));
_;
}
/**
* @dev register a new proposal with the given parameters. Every proposal has a unique ID which is being
* generated by calculating keccak256 of a incremented counter.
* @param _numOfChoices number of voting choices
* @param _avatar an address to be sent as the payload to the _executable contract.
* @param _executable This contract will be executed when vote is over.
* @param _proposer address
* @return proposal's id.
*/
function propose(uint _numOfChoices, bytes32 , address _avatar, ExecutableInterface _executable,address _proposer)
external
returns(bytes32)
{
// Check valid params and number of choices:
require(_numOfChoices == NUM_OF_CHOICES);
require(ExecutableInterface(_executable) != address(0));
//Check parameters existence.
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
require(parameters[paramsHash].preBoostedVoteRequiredPercentage > 0);
// Generate a unique ID:
bytes32 proposalId = keccak256(abi.encodePacked(this, proposalsCnt));
proposalsCnt++;
// Open proposal:
Proposal memory proposal;
proposal.numOfChoices = _numOfChoices;
proposal.avatar = _avatar;
proposal.executable = _executable;
proposal.state = ProposalState.PreBoosted;
// solium-disable-next-line security/no-block-members
proposal.submittedTime = now;
proposal.currentBoostedVotePeriodLimit = parameters[paramsHash].boostedVotePeriodLimit;
proposal.proposer = _proposer;
proposal.winningVote = NO;
proposal.paramsHash = paramsHash;
proposals[proposalId] = proposal;
emit NewProposal(proposalId, _avatar, _numOfChoices, _proposer, paramsHash);
return proposalId;
}
/**
* @dev Cancel a proposal, only the owner can call this function and only if allowOwner flag is true.
*/
function cancelProposal(bytes32 ) external returns(bool) {
//This is not allowed.
return false;
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stake(bytes32 _proposalId, uint _vote, uint _amount) external returns(bool) {
return _stake(_proposalId,_vote,_amount,msg.sender);
}
// Digest describing the data the user signs according EIP 712.
// Needs to match what is passed to Metamask.
bytes32 public constant DELEGATION_HASH_EIP712 =
keccak256(abi.encodePacked("address GenesisProtocolAddress","bytes32 ProposalId", "uint Vote","uint AmountToStake","uint Nonce"));
// web3.eth.sign prefix
string public constant ETH_SIGN_PREFIX= "\x19Ethereum Signed Message:\n32";
/**
* @dev stakeWithSignature function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _nonce nonce value ,it is part of the signature to ensure that
a signature can be received only once.
* @param _signatureType signature type
1 - for web3.eth.sign
2 - for eth_signTypedData according to EIP #712.
* @param _signature - signed data by the staker
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function stakeWithSignature(
bytes32 _proposalId,
uint _vote,
uint _amount,
uint _nonce,
uint _signatureType,
bytes _signature
)
external
returns(bool)
{
require(stakeSignatures[_signature] == false);
// Recreate the digest the user signed
bytes32 delegationDigest;
if (_signatureType == 2) {
delegationDigest = keccak256(
abi.encodePacked(
DELEGATION_HASH_EIP712, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
} else {
delegationDigest = keccak256(
abi.encodePacked(
ETH_SIGN_PREFIX, keccak256(
abi.encodePacked(
address(this),
_proposalId,
_vote,
_amount,
_nonce)))
);
}
address staker = delegationDigest.recover(_signature);
//a garbage staker address due to wrong signature will revert due to lack of approval and funds.
require(staker!=address(0));
stakeSignatures[_signature] = true;
return _stake(_proposalId,_vote,_amount,staker);
}
/**
* @dev voting function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function vote(bytes32 _proposalId, uint _vote) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId, msg.sender, _vote, 0);
}
/**
* @dev voting function with owner functionality (can vote on behalf of someone else)
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function ownerVote(bytes32 , uint , address ) external returns(bool) {
//This is not allowed.
return false;
}
function voteWithSpecifiedAmounts(bytes32 _proposalId,uint _vote,uint _rep,uint) external votable(_proposalId) returns(bool) {
return internalVote(_proposalId,msg.sender,_vote,_rep);
}
/**
* @dev Cancel the vote of the msg.sender.
* cancel vote is not allow in genesisProtocol so this function doing nothing.
* This function is here in order to comply to the IntVoteInterface .
*/
function cancelVote(bytes32 _proposalId) external votable(_proposalId) {
//this is not allowed
return;
}
/**
* @dev getNumberOfChoices returns the number of choices possible in this proposal
* @param _proposalId the ID of the proposals
* @return uint that contains number of choices
*/
function getNumberOfChoices(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].numOfChoices;
}
/**
* @dev voteInfo returns the vote and the amount of reputation of the user committed to this proposal
* @param _proposalId the ID of the proposal
* @param _voter the address of the voter
* @return uint vote - the voters vote
* uint reputation - amount of reputation committed by _voter to _proposalId
*/
function voteInfo(bytes32 _proposalId, address _voter) external view returns(uint, uint) {
Voter memory voter = proposals[_proposalId].voters[_voter];
return (voter.vote, voter.reputation);
}
/**
* @dev voteStatus returns the reputation voted for a proposal for a specific voting choice.
* @param _proposalId the ID of the proposal
* @param _choice the index in the
* @return voted reputation for the given choice
*/
function voteStatus(bytes32 _proposalId,uint _choice) external view returns(uint) {
return proposals[_proposalId].votes[_choice];
}
/**
* @dev isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function isVotable(bytes32 _proposalId) external view returns(bool) {
return _isVotable(_proposalId);
}
/**
* @dev proposalStatus return the total votes and stakes for a given proposal
* @param _proposalId the ID of the proposal
* @return uint preBoostedVotes YES
* @return uint preBoostedVotes NO
* @return uint stakersStakes
* @return uint totalRedeemableStakes
* @return uint total stakes YES
* @return uint total stakes NO
*/
function proposalStatus(bytes32 _proposalId) external view returns(uint, uint, uint ,uint, uint ,uint) {
return (
proposals[_proposalId].preBoostedVotes[YES],
proposals[_proposalId].preBoostedVotes[NO],
proposals[_proposalId].totalStakes[0],
proposals[_proposalId].totalStakes[1],
proposals[_proposalId].stakes[YES],
proposals[_proposalId].stakes[NO]
);
}
/**
* @dev proposalAvatar return the avatar for a given proposal
* @param _proposalId the ID of the proposal
* @return uint total reputation supply
*/
function proposalAvatar(bytes32 _proposalId) external view returns(address) {
return (proposals[_proposalId].avatar);
}
/**
* @dev scoreThresholdParams return the score threshold params for a given
* organization.
* @param _avatar the organization's avatar
* @return uint thresholdConstA
* @return uint thresholdConstB
*/
function scoreThresholdParams(address _avatar) external view returns(uint,uint) {
bytes32 paramsHash = getParametersFromController(Avatar(_avatar));
Parameters memory params = parameters[paramsHash];
return (params.thresholdConstA,params.thresholdConstB);
}
/**
* @dev getStaker return the vote and stake amount for a given proposal and staker
* @param _proposalId the ID of the proposal
* @param _staker staker address
* @return uint vote
* @return uint amount
*/
function getStaker(bytes32 _proposalId,address _staker) external view returns(uint,uint) {
return (proposals[_proposalId].stakers[_staker].vote,proposals[_proposalId].stakers[_staker].amount);
}
/**
* @dev state return the state for a given proposal
* @param _proposalId the ID of the proposal
* @return ProposalState proposal state
*/
function state(bytes32 _proposalId) external view returns(ProposalState) {
return proposals[_proposalId].state;
}
/**
* @dev winningVote return the winningVote for a given proposal
* @param _proposalId the ID of the proposal
* @return uint winningVote
*/
function winningVote(bytes32 _proposalId) external view returns(uint) {
return proposals[_proposalId].winningVote;
}
/**
* @dev isAbstainAllow returns if the voting machine allow abstain (0)
* @return bool true or false
*/
function isAbstainAllow() external pure returns(bool) {
return false;
}
/**
* @dev getAllowedRangeOfChoices returns the allowed range of choices for a voting machine.
* @return min - minimum number of choices
max - maximum number of choices
*/
function getAllowedRangeOfChoices() external pure returns(uint min,uint max) {
return (NUM_OF_CHOICES,NUM_OF_CHOICES);
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function execute(bytes32 _proposalId) external votable(_proposalId) returns(bool) {
return _execute(_proposalId);
}
/**
* @dev redeem a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return rewards -
* rewards[0] - stakerTokenAmount
* rewards[1] - stakerReputationAmount
* rewards[2] - voterTokenAmount
* rewards[3] - voterReputationAmount
* rewards[4] - proposerReputationAmount
* @return reputation - redeem reputation
*/
function redeem(bytes32 _proposalId,address _beneficiary) public returns (uint[5] rewards) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed),"wrong proposal state");
Parameters memory params = parameters[proposal.paramsHash];
uint amount;
uint reputation;
uint lostReputation;
if (proposal.winningVote == YES) {
lostReputation = proposal.preBoostedVotes[NO];
} else {
lostReputation = proposal.preBoostedVotes[YES];
}
lostReputation = (lostReputation * params.votersReputationLossRatio)/100;
//as staker
Staker storage staker = proposal.stakers[_beneficiary];
if ((staker.amount>0) &&
(staker.vote == proposal.winningVote)) {
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (totalWinningStakes != 0) {
rewards[0] = (staker.amount * proposal.totalStakes[0]) / totalWinningStakes;
}
if (proposal.state != ProposalState.Closed) {
rewards[1] = (staker.amount * ( lostReputation - ((lostReputation * params.votersGainRepRatioFromLostRep)/100)))/proposal.stakes[proposal.winningVote];
}
staker.amount = 0;
}
//as voter
Voter storage voter = proposal.voters[_beneficiary];
if ((voter.reputation != 0 ) && (voter.preBoosted)) {
uint preBoostedVotes = proposal.preBoostedVotes[YES] + proposal.preBoostedVotes[NO];
if (preBoostedVotes>0) {
rewards[2] = ((proposal.votersStakes * voter.reputation) / preBoostedVotes);
}
if (proposal.state == ProposalState.Closed) {
//give back reputation for the voter
rewards[3] = ((voter.reputation * params.votersReputationLossRatio)/100);
} else if (proposal.winningVote == voter.vote ) {
rewards[3] = (((voter.reputation * params.votersReputationLossRatio)/100) +
(((voter.reputation * lostReputation * params.votersGainRepRatioFromLostRep)/100)/preBoostedVotes));
}
voter.reputation = 0;
}
//as proposer
if ((proposal.proposer == _beneficiary)&&(proposal.winningVote == YES)&&(proposal.proposer != address(0))) {
rewards[4] = (params.proposingRepRewardConstA.mul(proposal.votes[YES]+proposal.votes[NO]) + params.proposingRepRewardConstB.mul(proposal.votes[YES]-proposal.votes[NO]))/1000;
proposal.proposer = 0;
}
amount = rewards[0] + rewards[2];
reputation = rewards[1] + rewards[3] + rewards[4];
if (amount != 0) {
proposal.totalStakes[1] = proposal.totalStakes[1].sub(amount);
require(stakingToken.transfer(_beneficiary, amount));
emit Redeem(_proposalId,proposal.avatar,_beneficiary,amount);
}
if (reputation != 0 ) {
ControllerInterface(Avatar(proposal.avatar).owner()).mintReputation(reputation,_beneficiary,proposal.avatar);
emit RedeemReputation(_proposalId,proposal.avatar,_beneficiary,reputation);
}
}
/**
* @dev redeemDaoBounty a reward for a successful stake, vote or proposing.
* The function use a beneficiary address as a parameter (and not msg.sender) to enable
* users to redeem on behalf of someone else.
* @param _proposalId the ID of the proposal
* @param _beneficiary - the beneficiary address
* @return redeemedAmount - redeem token amount
* @return potentialAmount - potential redeem token amount(if there is enough tokens bounty at the avatar )
*/
function redeemDaoBounty(bytes32 _proposalId,address _beneficiary) public returns(uint redeemedAmount,uint potentialAmount) {
Proposal storage proposal = proposals[_proposalId];
require((proposal.state == ProposalState.Executed) || (proposal.state == ProposalState.Closed));
uint totalWinningStakes = proposal.stakes[proposal.winningVote];
if (
// solium-disable-next-line operator-whitespace
(proposal.stakers[_beneficiary].amountForBounty>0)&&
(proposal.stakers[_beneficiary].vote == proposal.winningVote)&&
(proposal.winningVote == YES)&&
(totalWinningStakes != 0))
{
//as staker
Parameters memory params = parameters[proposal.paramsHash];
uint beneficiaryLimit = (proposal.stakers[_beneficiary].amountForBounty.mul(params.daoBountyLimit)) / totalWinningStakes;
potentialAmount = (params.daoBountyConst.mul(proposal.stakers[_beneficiary].amountForBounty))/100;
if (potentialAmount > beneficiaryLimit) {
potentialAmount = beneficiaryLimit;
}
}
if ((potentialAmount != 0)&&(stakingToken.balanceOf(proposal.avatar) >= potentialAmount)) {
proposal.daoBountyRemain = proposal.daoBountyRemain.sub(potentialAmount);
require(ControllerInterface(Avatar(proposal.avatar).owner()).externalTokenTransfer(stakingToken,_beneficiary,potentialAmount,proposal.avatar));
proposal.stakers[_beneficiary].amountForBounty = 0;
redeemedAmount = potentialAmount;
emit RedeemDaoBounty(_proposalId,proposal.avatar,_beneficiary,redeemedAmount);
}
}
/**
* @dev shouldBoost check if a proposal should be shifted to boosted phase.
* @param _proposalId the ID of the proposal
* @return bool true or false.
*/
function shouldBoost(bytes32 _proposalId) public view returns(bool) {
Proposal memory proposal = proposals[_proposalId];
return (_score(_proposalId) >= threshold(proposal.paramsHash,proposal.avatar));
}
/**
* @dev score return the proposal score
* @param _proposalId the ID of the proposal
* @return uint proposal score.
*/
function score(bytes32 _proposalId) public view returns(int) {
return _score(_proposalId);
}
/**
* @dev getBoostedProposalsCount return the number of boosted proposal for an organization
* @param _avatar the organization avatar
* @return uint number of boosted proposals
*/
function getBoostedProposalsCount(address _avatar) public view returns(uint) {
uint expiredProposals;
if (proposalsExpiredTimes[_avatar].count() != 0) {
// solium-disable-next-line security/no-block-members
expiredProposals = proposalsExpiredTimes[_avatar].rank(now);
}
return orgBoostedProposalsCnt[_avatar].sub(expiredProposals);
}
/**
* @dev threshold return the organization's score threshold which required by
* a proposal to shift to boosted state.
* This threshold is dynamically set and it depend on the number of boosted proposal.
* @param _avatar the organization avatar
* @param _paramsHash the organization parameters hash
* @return int organization's score threshold.
*/
function threshold(bytes32 _paramsHash,address _avatar) public view returns(int) {
uint boostedProposals = getBoostedProposalsCount(_avatar);
int216 e = 2;
Parameters memory params = parameters[_paramsHash];
require(params.thresholdConstB > 0,"should be a valid parameter hash");
int256 power = int216(boostedProposals).toReal().div(int216(params.thresholdConstB).toReal());
if (power.fromReal() > 100 ) {
power = int216(100).toReal();
}
int256 res = int216(params.thresholdConstA).toReal().mul(e.toReal().pow(power));
return res.fromReal();
}
/**
* @dev hash the parameters, save them if necessary, and return the hash value
* @param _params a parameters array
* _params[0] - _preBoostedVoteRequiredPercentage,
* _params[1] - _preBoostedVotePeriodLimit, //the time limit for a proposal to be in an absolute voting mode.
* _params[2] -_boostedVotePeriodLimit, //the time limit for a proposal to be in an relative voting mode.
* _params[3] -_thresholdConstA
* _params[4] -_thresholdConstB
* _params[5] -_minimumStakingFee
* _params[6] -_quietEndingPeriod
* _params[7] -_proposingRepRewardConstA
* _params[8] -_proposingRepRewardConstB
* _params[9] -_stakerFeeRatioForVoters
* _params[10] -_votersReputationLossRatio
* _params[11] -_votersGainRepRatioFromLostRep
* _params[12] - _daoBountyConst
* _params[13] - _daoBountyLimit
*/
function setParameters(
uint[14] _params //use array here due to stack too deep issue.
)
public
returns(bytes32)
{
require(_params[0] <= 100 && _params[0] > 0,"0 < preBoostedVoteRequiredPercentage <= 100");
require(_params[4] > 0 && _params[4] <= 100000000,"0 < thresholdConstB < 100000000 ");
require(_params[3] <= 100000000 ether,"thresholdConstA <= 100000000 wei");
require(_params[9] <= 100,"stakerFeeRatioForVoters <= 100");
require(_params[10] <= 100,"votersReputationLossRatio <= 100");
require(_params[11] <= 100,"votersGainRepRatioFromLostRep <= 100");
require(_params[2] >= _params[6],"boostedVotePeriodLimit >= quietEndingPeriod");
require(_params[7] <= 100000000,"proposingRepRewardConstA <= 100000000");
require(_params[8] <= 100000000,"proposingRepRewardConstB <= 100000000");
require(_params[12] <= (2 * _params[9]),"daoBountyConst <= 2 * stakerFeeRatioForVoters");
require(_params[12] >= _params[9],"daoBountyConst >= stakerFeeRatioForVoters");
bytes32 paramsHash = getParametersHash(_params);
parameters[paramsHash] = Parameters({
preBoostedVoteRequiredPercentage: _params[0],
preBoostedVotePeriodLimit: _params[1],
boostedVotePeriodLimit: _params[2],
thresholdConstA:_params[3],
thresholdConstB:_params[4],
minimumStakingFee: _params[5],
quietEndingPeriod: _params[6],
proposingRepRewardConstA: _params[7],
proposingRepRewardConstB:_params[8],
stakerFeeRatioForVoters:_params[9],
votersReputationLossRatio:_params[10],
votersGainRepRatioFromLostRep:_params[11],
daoBountyConst:_params[12],
daoBountyLimit:_params[13]
});
return paramsHash;
}
/**
* @dev hashParameters returns a hash of the given parameters
*/
function getParametersHash(
uint[14] _params) //use array here due to stack too deep issue.
public
pure
returns(bytes32)
{
return keccak256(
abi.encodePacked(
_params[0],
_params[1],
_params[2],
_params[3],
_params[4],
_params[5],
_params[6],
_params[7],
_params[8],
_params[9],
_params[10],
_params[11],
_params[12],
_params[13]));
}
/**
* @dev execute check if the proposal has been decided, and if so, execute the proposal
* @param _proposalId the id of the proposal
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _execute(bytes32 _proposalId) internal votable(_proposalId) returns(bool) {
Proposal storage proposal = proposals[_proposalId];
Parameters memory params = parameters[proposal.paramsHash];
Proposal memory tmpProposal = proposal;
uint totalReputation = Avatar(proposal.avatar).nativeReputation().totalSupply();
uint executionBar = totalReputation * params.preBoostedVoteRequiredPercentage/100;
ExecutionState executionState = ExecutionState.None;
if (proposal.state == ProposalState.PreBoosted) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.submittedTime) >= params.preBoostedVotePeriodLimit) {
proposal.state = ProposalState.Closed;
proposal.winningVote = NO;
executionState = ExecutionState.PreBoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
proposal.state = ProposalState.Executed;
executionState = ExecutionState.PreBoostedBarCrossed;
} else if ( shouldBoost(_proposalId)) {
//change proposal mode to boosted mode.
proposal.state = ProposalState.Boosted;
// solium-disable-next-line security/no-block-members
proposal.boostedPhaseTime = now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[proposal.avatar]++;
}
}
if ((proposal.state == ProposalState.Boosted) ||
(proposal.state == ProposalState.QuietEndingPeriod)) {
// solium-disable-next-line security/no-block-members
if ((now - proposal.boostedPhaseTime) >= proposal.currentBoostedVotePeriodLimit) {
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedTimeOut;
} else if (proposal.votes[proposal.winningVote] > executionBar) {
// someone crossed the absolute vote execution bar.
orgBoostedProposalsCnt[tmpProposal.avatar] = orgBoostedProposalsCnt[tmpProposal.avatar].sub(1);
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
proposal.state = ProposalState.Executed;
executionState = ExecutionState.BoostedBarCrossed;
}
}
if (executionState != ExecutionState.None) {
if (proposal.winningVote == YES) {
uint daoBountyRemain = (params.daoBountyConst.mul(proposal.stakes[proposal.winningVote]))/100;
if (daoBountyRemain > params.daoBountyLimit) {
daoBountyRemain = params.daoBountyLimit;
}
proposal.daoBountyRemain = daoBountyRemain;
}
emit ExecuteProposal(_proposalId, proposal.avatar, proposal.winningVote, totalReputation);
emit GPExecuteProposal(_proposalId, executionState);
(tmpProposal.executable).execute(_proposalId, tmpProposal.avatar, int(proposal.winningVote));
}
return (executionState != ExecutionState.None);
}
/**
* @dev staking function
* @param _proposalId id of the proposal
* @param _vote NO(2) or YES(1).
* @param _amount the betting amount
* @param _staker the staker address
* @return bool true - the proposal has been executed
* false - otherwise.
*/
function _stake(bytes32 _proposalId, uint _vote, uint _amount,address _staker) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0);
require(_amount > 0);
if (_execute(_proposalId)) {
return true;
}
Proposal storage proposal = proposals[_proposalId];
if (proposal.state != ProposalState.PreBoosted) {
return false;
}
// enable to increase stake only on the previous stake vote
Staker storage staker = proposal.stakers[_staker];
if ((staker.amount > 0) && (staker.vote != _vote)) {
return false;
}
uint amount = _amount;
Parameters memory params = parameters[proposal.paramsHash];
require(amount >= params.minimumStakingFee);
require(stakingToken.transferFrom(_staker, address(this), amount));
proposal.totalStakes[1] = proposal.totalStakes[1].add(amount); //update totalRedeemableStakes
staker.amount += amount;
staker.amountForBounty = staker.amount;
staker.vote = _vote;
proposal.votersStakes += (params.stakerFeeRatioForVoters * amount)/100;
proposal.stakes[_vote] = amount.add(proposal.stakes[_vote]);
amount = amount - ((params.stakerFeeRatioForVoters*amount)/100);
proposal.totalStakes[0] = amount.add(proposal.totalStakes[0]);
// Event:
emit Stake(_proposalId, proposal.avatar, _staker, _vote, _amount);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev Vote for a proposal, if the voter already voted, cancel the last vote and set a new one instead
* @param _proposalId id of the proposal
* @param _voter used in case the vote is cast for someone else
* @param _vote a value between 0 to and the proposal's number of choices.
* @param _rep how many reputation the voter would like to stake for this vote.
* if _rep==0 so the voter full reputation will be use.
* @return true in case of proposal execution otherwise false
* throws if proposal is not open or if it has been executed
* NB: executes the proposal if a decision has been reached
*/
function internalVote(bytes32 _proposalId, address _voter, uint _vote, uint _rep) internal returns(bool) {
// 0 is not a valid vote.
require(_vote <= NUM_OF_CHOICES && _vote > 0,"0 < _vote <= 2");
if (_execute(_proposalId)) {
return true;
}
Parameters memory params = parameters[proposals[_proposalId].paramsHash];
Proposal storage proposal = proposals[_proposalId];
// Check voter has enough reputation:
uint reputation = Avatar(proposal.avatar).nativeReputation().reputationOf(_voter);
require(reputation >= _rep);
uint rep = _rep;
if (rep == 0) {
rep = reputation;
}
// If this voter has already voted, return false.
if (proposal.voters[_voter].reputation != 0) {
return false;
}
// The voting itself:
proposal.votes[_vote] = rep.add(proposal.votes[_vote]);
//check if the current winningVote changed or there is a tie.
//for the case there is a tie the current winningVote set to NO.
if ((proposal.votes[_vote] > proposal.votes[proposal.winningVote]) ||
((proposal.votes[NO] == proposal.votes[proposal.winningVote]) &&
proposal.winningVote == YES))
{
// solium-disable-next-line security/no-block-members
uint _now = now;
if ((proposal.state == ProposalState.QuietEndingPeriod) ||
((proposal.state == ProposalState.Boosted) && ((_now - proposal.boostedPhaseTime) >= (params.boostedVotePeriodLimit - params.quietEndingPeriod)))) {
//quietEndingPeriod
proposalsExpiredTimes[proposal.avatar].remove(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
if (proposal.state != ProposalState.QuietEndingPeriod) {
proposal.currentBoostedVotePeriodLimit = params.quietEndingPeriod;
proposal.state = ProposalState.QuietEndingPeriod;
}
proposal.boostedPhaseTime = _now;
proposalsExpiredTimes[proposal.avatar].insert(proposal.boostedPhaseTime + proposal.currentBoostedVotePeriodLimit);
}
proposal.winningVote = _vote;
}
proposal.voters[_voter] = Voter({
reputation: rep,
vote: _vote,
preBoosted:(proposal.state == ProposalState.PreBoosted)
});
if (proposal.state == ProposalState.PreBoosted) {
proposal.preBoostedVotes[_vote] = rep.add(proposal.preBoostedVotes[_vote]);
uint reputationDeposit = (params.votersReputationLossRatio * rep)/100;
ControllerInterface(Avatar(proposal.avatar).owner()).burnReputation(reputationDeposit,_voter,proposal.avatar);
}
// Event:
emit VoteProposal(_proposalId, proposal.avatar, _voter, _vote, rep);
// execute the proposal if this vote was decisive:
return _execute(_proposalId);
}
/**
* @dev _score return the proposal score
* For dual choice proposal S = (S+) - (S-)
* @param _proposalId the ID of the proposal
* @return int proposal score.
*/
function _score(bytes32 _proposalId) private view returns(int) {
Proposal storage proposal = proposals[_proposalId];
return int(proposal.stakes[YES]) - int(proposal.stakes[NO]);
}
/**
* @dev _isVotable check if the proposal is votable
* @param _proposalId the ID of the proposal
* @return bool true or false
*/
function _isVotable(bytes32 _proposalId) private view returns(bool) {
ProposalState pState = proposals[_proposalId].state;
return ((pState == ProposalState.PreBoosted)||(pState == ProposalState.Boosted)||(pState == ProposalState.QuietEndingPeriod));
}
} | register a scheme _scheme the address of the scheme _paramsHash a hashed configuration of the usage of the scheme _permissions the permissions the new scheme will have return bool which represents a success/ Check scheme has at least the permissions it is changing, and at least the current permissions: Implementation is a bit messy. One must recall logic-circuits ^^ produces non-zero if sender does not have all of the perms that are changing between old and new produces non-zero if sender does not have all of the perms in the old scheme Add or change the scheme: | function registerScheme(address _scheme, bytes32 _paramsHash, bytes4 _permissions,address _avatar)
external
onlyRegisteringSchemes
onlySubjectToConstraint("registerScheme")
isAvatarValid(_avatar)
returns(bool)
{
Scheme memory scheme = schemes[_scheme];
require(bytes4(0x1F)&(_permissions^scheme.permissions)&(~schemes[msg.sender].permissions) == bytes4(0));
require(bytes4(0x1F)&(scheme.permissions&(~schemes[msg.sender].permissions)) == bytes4(0));
schemes[_scheme].paramsHash = _paramsHash;
schemes[_scheme].permissions = _permissions|bytes4(1);
emit RegisterScheme(msg.sender, _scheme);
return true;
}
| 1,299,080 |
/*
* source https://github.com/lukso-network/rICO-smart-contracts
* @name rICO
* @package rICO-smart-contracts
* @author Micky Socaci <[email protected]>, Fabian Vogelsteller <@frozeman>, Marjorie Hernandez <[email protected]>
* @license MIT
*/
pragma solidity ^0.5.0;
import "./zeppelin/math/SafeMath.sol";
import "./zeppelin/token/ERC777/IERC777.sol";
import "./zeppelin/token/ERC777/IERC777Recipient.sol";
import "./zeppelin/introspection/IERC1820Registry.sol";
contract ReversibleICO is IERC777Recipient {
/*
* Instances
*/
using SafeMath for uint256;
/// @dev The address of the introspection registry contract deployed.
IERC1820Registry private ERC1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = keccak256("ERC777TokensRecipient");
/*
* Contract States
*/
/// @dev It is set to TRUE after the deployer initializes the contract.
bool public initialized;
/// @dev Security guard. The freezer address can the freeze the contract and move its funds in case of emergency.
bool public frozen;
uint256 public frozenPeriod;
uint256 public freezeStart;
/*
* Addresses
*/
/// @dev Only the deploying address is allowed to initialize the contract.
address public deployingAddress;
/// @dev The rICO token contract address.
address public tokenAddress;
/// @dev The address of wallet of the project running the rICO.
address public projectAddress;
/// @dev Only the whitelist controller can whitelist addresses.
address public whitelistingAddress;
/// @dev Only the freezer address can call the freeze functions.
address public freezerAddress;
/// @dev Only the rescuer address can move funds if the rICO is frozen.
address public rescuerAddress;
/*
* Public Variables
*/
/// @dev Total amount tokens initially available to be bought, increases if the project adds more.
uint256 public initialTokenSupply;
/// @dev Total amount tokens currently available to be bought.
uint256 public tokenSupply;
/// @dev Total amount of ETH currently accepted as a commitment to buy tokens (excluding pendingETH).
uint256 public committedETH;
/// @dev Total amount of ETH currently pending to be whitelisted.
uint256 public pendingETH;
/// @dev Accumulated amount of all ETH returned from canceled pending ETH.
uint256 public canceledETH;
/// @dev Accumulated amount of all ETH withdrawn by participants.
uint256 public withdrawnETH;
/// @dev Count of the number the project has withdrawn from the funds raised.
uint256 public projectWithdrawCount;
/// @dev Total amount of ETH withdrawn by the project
uint256 public projectWithdrawnETH;
/// @dev Minimum amount of ETH accepted for a contribution. Everything lower than that will trigger a canceling of pending ETH.
uint256 public minContribution = 0.001 ether;
uint256 public maxContribution = 4000 ether;
mapping(uint8 => Stage) public stages;
uint8 public stageCount;
/// @dev Maps participants stats by their address.
mapping(address => Participant) public participants;
/// @dev Maps participants address to a unique participant ID (incremental IDs, based on "participantCount").
mapping(uint256 => address) public participantsById;
/// @dev Total number of rICO participants.
uint256 public participantCount;
/*
* Commit phase (Stage 0)
*/
/// @dev Initial token price in the commit phase (Stage 0).
uint256 public commitPhasePrice;
/// @dev Block number that indicates the start of the commit phase.
uint256 public commitPhaseStartBlock;
/// @dev Block number that indicates the end of the commit phase.
uint256 public commitPhaseEndBlock;
/// @dev The duration of the commit phase in blocks.
uint256 public commitPhaseBlockCount;
/*
* Buy phases (Stages 1-n)
*/
/// @dev Block number that indicates the start of the buy phase (Stages 1-n).
uint256 public buyPhaseStartBlock;
/// @dev Block number that indicates the end of the buy phase.
uint256 public buyPhaseEndBlock;
/// @dev The duration of the buy phase in blocks.
uint256 public buyPhaseBlockCount;
/*
* Internal Variables
*/
/// @dev Total amount of the current reserved ETH for the project by the participants contributions.
uint256 internal _projectCurrentlyReservedETH;
/// @dev Accumulated amount allocated to the project by participants.
uint256 internal _projectUnlockedETH;
/// @dev Last block since the project has calculated the _projectUnlockedETH.
uint256 internal _projectLastBlock;
/*
* Structs
*/
/*
* Stages
* Stage 0 = commit phase
* Stage 1-n = buy phase
*/
struct Stage {
uint256 tokenLimit; // 500k > 9.5M >
uint256 tokenPrice;
}
/*
* Participants
*/
struct Participant {
bool whitelisted;
uint32 contributions;
uint32 withdraws;
uint256 firstContributionBlock;
uint256 reservedTokens;
uint256 committedETH;
uint256 pendingETH;
uint256 _currentReservedTokens;
uint256 _unlockedTokens;
uint256 _lastBlock;
mapping(uint8 => ParticipantStageDetails) stages;
}
struct ParticipantStageDetails {
uint256 pendingETH;
}
/*
* Events
*/
event PendingContributionAdded(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId, uint8 stageId);
event PendingContributionsCanceled(address indexed participantAddress, uint256 indexed amount, uint32 indexed contributionId);
event WhitelistApproved(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event WhitelistRejected(address indexed participantAddress, uint256 indexed pendingETH, uint32 indexed contributions);
event ContributionsAccepted(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint8 stageId);
event ProjectWithdraw(address indexed projectAddress, uint256 indexed amount, uint32 indexed withdrawCount);
event ParticipantWithdraw(address indexed participantAddress, uint256 indexed ethAmount, uint256 indexed tokenAmount, uint32 withdrawCount);
event StageChanged(uint8 indexed stageId, uint256 indexed tokenLimit, uint256 indexed tokenPrice, uint256 effectiveBlockNumber);
event WhitelistingAddressChanged(address indexed whitelistingAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event FreezerAddressChanged(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityFreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityUnfreeze(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityDisableEscapeHatch(address indexed freezerAddress, uint8 indexed stageId, uint256 indexed effectiveBlockNumber);
event SecurityEscapeHatch(address indexed rescuerAddress, address indexed to, uint8 indexed stageId, uint256 effectiveBlockNumber);
event TransferEvent (
uint8 indexed typeId,
address indexed relatedAddress,
uint256 indexed value
);
enum TransferTypes {
NOT_SET, // 0
WHITELIST_REJECTED, // 1
CONTRIBUTION_CANCELED, // 2
CONTRIBUTION_ACCEPTED_OVERFLOW, // 3 not accepted ETH
PARTICIPANT_WITHDRAW, // 4
PARTICIPANT_WITHDRAW_OVERFLOW, // 5 not returnable tokens
PROJECT_WITHDRAWN, // 6
FROZEN_ESCAPEHATCH_TOKEN, // 7
FROZEN_ESCAPEHATCH_ETH // 8
}
// ------------------------------------------------------------------------------------------------
/// @notice Constructor sets the deployer and defines ERC777TokensRecipient interface support.
constructor() public {
deployingAddress = msg.sender;
ERC1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
/**
* @notice Initializes the contract. Only the deployer (set in the constructor) can call this method.
* @param _tokenAddress The address of the ERC777 rICO token contract.
* @param _whitelistingAddress The address handling whitelisting.
* @param _projectAddress The project wallet that can withdraw ETH contributions.
* @param _commitPhaseStartBlock The block at which the commit phase starts.
* @param _buyPhaseStartBlock The duration of the commit phase in blocks.
* @param _initialPrice The initial token price (in WEI per token) during the commit phase.
* @param _stageCount The number of the rICO stages, excluding the commit phase (Stage 0).
* @param _stageTokenLimitIncrease The duration of each stage in blocks.
* @param _stagePriceIncrease A factor used to increase the token price from the _initialPrice at each subsequent stage.
*/
function init(
address _tokenAddress,
address _whitelistingAddress,
address _freezerAddress,
address _rescuerAddress,
address _projectAddress,
uint256 _commitPhaseStartBlock,
uint256 _buyPhaseStartBlock,
uint256 _buyPhaseEndBlock,
uint256 _initialPrice,
uint8 _stageCount, // Its not recommended to choose more than 50 stages! (9 stages require ~650k GAS when whitelisting contributions, the whitelisting function could run out of gas with a high number of stages, preventing accepting contributions)
uint256 _stageTokenLimitIncrease,
uint256 _stagePriceIncrease
)
public
onlyDeployingAddress
isNotInitialized
{
require(_tokenAddress != address(0), "_tokenAddress cannot be 0x");
require(_whitelistingAddress != address(0), "_whitelistingAddress cannot be 0x");
require(_freezerAddress != address(0), "_freezerAddress cannot be 0x");
require(_rescuerAddress != address(0), "_rescuerAddress cannot be 0x");
require(_projectAddress != address(0), "_projectAddress cannot be 0x");
// require(_commitPhaseStartBlock > getCurrentBlockNumber(), "Start block cannot be set in the past.");
// Assign address variables
tokenAddress = _tokenAddress;
whitelistingAddress = _whitelistingAddress;
freezerAddress = _freezerAddress;
rescuerAddress = _rescuerAddress;
projectAddress = _projectAddress;
// UPDATE global STATS
commitPhaseStartBlock = _commitPhaseStartBlock;
commitPhaseEndBlock = _buyPhaseStartBlock.sub(1);
commitPhaseBlockCount = commitPhaseEndBlock.sub(commitPhaseStartBlock).add(1);
commitPhasePrice = _initialPrice;
stageCount = _stageCount;
// Setup stage 0: The commit phase.
Stage storage commitPhase = stages[0];
commitPhase.tokenLimit = _stageTokenLimitIncrease;
commitPhase.tokenPrice = _initialPrice;
// Setup stage 1 to n: The buy phase stages
uint256 previousStageTokenLimit = _stageTokenLimitIncrease;
// Update stages: start, end, price
for (uint8 i = 1; i <= _stageCount; i++) {
// Get i-th stage
Stage storage byStage = stages[i];
// set the stage limit amount
byStage.tokenLimit = previousStageTokenLimit.add(_stageTokenLimitIncrease);
// Store the current stage endBlock in order to update the next one
previousStageTokenLimit = byStage.tokenLimit;
// At each stage the token price increases by _stagePriceIncrease * stageCount
byStage.tokenPrice = _initialPrice.add(_stagePriceIncrease.mul(i));
}
// UPDATE global STATS
// The buy phase starts on the subsequent block of the commitPhase's (stage0) endBlock
buyPhaseStartBlock = _buyPhaseStartBlock;
// The buy phase ends when the lat stage ends
buyPhaseEndBlock = _buyPhaseEndBlock;
// The duration of buyPhase in blocks
buyPhaseBlockCount = buyPhaseEndBlock.sub(buyPhaseStartBlock).add(1);
// The contract is now initialized
initialized = true;
}
/*
* Public functions
* ------------------------------------------------------------------------------------------------
*/
/*
* Public functions
* The main way to interact with the rICO.
*/
/**
* @notice FALLBACK function: If the amount sent is smaller than `minContribution` it cancels all pending contributions.
* IF you are a known contributor with at least 1 contribution and you are whitelisted, you can send ETH without calling "commit()" to contribute more.
*/
function()
external
payable
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[msg.sender];
// allow to commit directly if its a known user with at least 1 contribution
if (participantStats.whitelisted == true && participantStats.contributions > 0) {
commit();
// otherwise try to cancel
} else {
require(msg.value < minContribution, 'To contribute call commit() [0x3c7a3aff] and send ETH along.');
// Participant cancels pending contributions.
cancelPendingContributions(msg.sender, msg.value);
}
}
/**
* @notice ERC777TokensRecipient implementation for receiving ERC777 tokens.
* @param _from Token sender.
* @param _amount Token amount.
*/
function tokensReceived(
address,
address _from,
address,
uint256 _amount,
bytes calldata,
bytes calldata
)
external
isInitialized
isNotFrozen
{
// rICO should only receive tokens from the rICO token contract.
// Transactions from any other token contract revert
require(msg.sender == tokenAddress, "Unknown token contract sent tokens.");
// Project wallet adds tokens to the sale
if (_from == projectAddress) {
// increase the supply
tokenSupply = tokenSupply.add(_amount);
initialTokenSupply = initialTokenSupply.add(_amount);
// rICO participant sends tokens back
} else {
withdraw(_from, _amount);
}
}
/**
* @notice Allows a participant to reserve tokens by committing ETH as contributions.
*
* Function signature: 0x3c7a3aff
*/
function commit()
public
payable
isInitialized
isNotFrozen
isRunning
{
// Reject contributions lower than the minimum amount, and max than maxContribution
require(msg.value >= minContribution, "Value sent is less than the minimum contribution.");
// Participant initial state record
uint8 currentStage = getCurrentStage();
Participant storage participantStats = participants[msg.sender];
ParticipantStageDetails storage byStage = participantStats.stages[currentStage];
require(participantStats.committedETH.add(msg.value) <= maxContribution, "Value sent is larger than the maximum contribution.");
// Check if participant already exists
if (participantStats.contributions == 0) {
// Identify the participants by their Id
participantsById[participantCount] = msg.sender;
// Increase participant count
participantCount++;
}
// UPDATE PARTICIPANT STATS
participantStats.contributions++;
participantStats.pendingETH = participantStats.pendingETH.add(msg.value);
byStage.pendingETH = byStage.pendingETH.add(msg.value);
// UPDATE GLOBAL STATS
pendingETH = pendingETH.add(msg.value);
emit PendingContributionAdded(
msg.sender,
msg.value,
uint32(participantStats.contributions),
currentStage
);
// If whitelisted, process the contribution automatically
if (participantStats.whitelisted == true) {
acceptContributions(msg.sender);
}
}
/**
* @notice Allows a participant to cancel pending contributions
*
* Function signature: 0xea8a1af0
*/
function cancel()
external
payable
isInitialized
isNotFrozen
{
cancelPendingContributions(msg.sender, msg.value);
}
/**
* @notice Approves or rejects participants.
* @param _addresses The list of participant address.
* @param _approve Indicates if the provided participants are approved (true) or rejected (false).
*/
function whitelist(address[] calldata _addresses, bool _approve)
external
onlyWhitelistingAddress
isInitialized
isNotFrozen
isRunning
{
// Revert if the provided list is empty
require(_addresses.length > 0, "No addresses given to whitelist.");
for (uint256 i = 0; i < _addresses.length; i++) {
address participantAddress = _addresses[i];
Participant storage participantStats = participants[participantAddress];
if (_approve) {
if (participantStats.whitelisted == false) {
// If participants are approved: whitelist them and accept their contributions
participantStats.whitelisted = true;
emit WhitelistApproved(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
}
// accept any pending ETH
acceptContributions(participantAddress);
} else {
participantStats.whitelisted = false;
emit WhitelistRejected(participantAddress, participantStats.pendingETH, uint32(participantStats.contributions));
// Cancel participants pending contributions.
cancelPendingContributions(participantAddress, 0);
}
}
}
/**
* @notice Allows the project to withdraw tokens.
* @param _tokenAmount The token amount.
*/
function projectTokenWithdraw(uint256 _tokenAmount)
external
onlyProjectAddress
isInitialized
{
require(_tokenAmount <= tokenSupply, "Requested amount too high, not enough tokens available.");
// decrease the supply
tokenSupply = tokenSupply.sub(_tokenAmount);
initialTokenSupply = initialTokenSupply.sub(_tokenAmount);
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(projectAddress, _tokenAmount, "");
}
/**
* @notice Allows for the project to withdraw ETH.
* @param _ethAmount The ETH amount in wei.
*/
function projectWithdraw(uint256 _ethAmount)
external
onlyProjectAddress
isInitialized
isNotFrozen
{
// UPDATE the locked/unlocked ratio for the project
calcProjectAllocation();
// Get current allocated ETH to the project
uint256 availableForWithdraw = _projectUnlockedETH.sub(projectWithdrawnETH);
require(_ethAmount <= availableForWithdraw, "Requested amount too high, not enough ETH unlocked.");
// UPDATE global STATS
projectWithdrawCount++;
projectWithdrawnETH = projectWithdrawnETH.add(_ethAmount);
// Event emission
emit ProjectWithdraw(
projectAddress,
_ethAmount,
uint32(projectWithdrawCount)
);
emit TransferEvent(
uint8(TransferTypes.PROJECT_WITHDRAWN),
projectAddress,
_ethAmount
);
// Transfer ETH to project wallet
address(uint160(projectAddress)).transfer(_ethAmount);
}
function changeStage(uint8 _stageId, uint256 _tokenLimit, uint256 _tokenPrice)
external
onlyProjectAddress
isInitialized
{
stages[_stageId].tokenLimit = _tokenLimit;
stages[_stageId].tokenPrice = _tokenPrice;
if(_stageId > stageCount) {
stageCount = _stageId;
}
emit StageChanged(_stageId, _tokenLimit, _tokenPrice, getCurrentEffectiveBlockNumber());
}
function changeWhitelistingAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
whitelistingAddress = _newAddress;
emit WhitelistingAddressChanged(whitelistingAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
function changeFreezerAddress(address _newAddress)
external
onlyProjectAddress
isInitialized
{
freezerAddress = _newAddress;
emit FreezerAddressChanged(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/*
* Security functions.
* If the rICO runs fine the freezer address can be set to 0x0, for the beginning its good to have a safe guard.
*/
/**
* @notice Freezes the rICO in case of emergency.
*
* Function signature: 0x62a5af3b
*/
function freeze()
external
onlyFreezerAddress
isNotFrozen
{
frozen = true;
freezeStart = getCurrentEffectiveBlockNumber();
// Emit event
emit SecurityFreeze(freezerAddress, getCurrentStage(), freezeStart);
}
/**
* @notice Un-freezes the rICO.
*
* Function signature: 0x6a28f000
*/
function unfreeze()
external
onlyFreezerAddress
isFrozen
{
uint256 currentBlock = getCurrentEffectiveBlockNumber();
frozen = false;
frozenPeriod = frozenPeriod.add(
currentBlock.sub(freezeStart)
);
// Emit event
emit SecurityUnfreeze(freezerAddress, getCurrentStage(), currentBlock);
}
/**
* @notice Sets the freeze address to 0x0
*
* Function signature: 0xeb10dec7
*/
function disableEscapeHatch()
external
onlyFreezerAddress
isNotFrozen
{
freezerAddress = address(0);
rescuerAddress = address(0);
// Emit event
emit SecurityDisableEscapeHatch(freezerAddress, getCurrentStage(), getCurrentEffectiveBlockNumber());
}
/**
* @notice Moves the funds to a safe place, in case of emergency. Only possible, when the the rICO is frozen.
*/
function escapeHatch(address _to)
external
onlyRescuerAddress
isFrozen
{
require(getCurrentEffectiveBlockNumber() >= freezeStart.add(18000), 'Let it cool.. Wait at least ~3 days (18000 blk) before moving anything.');
uint256 tokenBalance = IERC777(tokenAddress).balanceOf(address(this));
uint256 ethBalance = address(this).balance;
// sent all tokens from the contract to the _to address
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_to, tokenBalance, "");
// sent all ETH from the contract to the _to address
address(uint160(_to)).transfer(ethBalance);
// Emit events
emit SecurityEscapeHatch(rescuerAddress, _to, getCurrentStage(), getCurrentEffectiveBlockNumber());
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_TOKEN), _to, tokenBalance);
emit TransferEvent(uint8(TransferTypes.FROZEN_ESCAPEHATCH_ETH), _to, ethBalance);
}
/*
* Public view functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Returns project's total unlocked ETH.
* @return uint256 The amount of ETH unlocked over the whole rICO.
*/
function getUnlockedProjectETH() public view returns (uint256) {
// calc from the last known point on
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
return _projectUnlockedETH
.add(newlyUnlockedEth);
}
/**
* @notice Returns project's current available unlocked ETH reduced by what was already withdrawn.
* @return uint256 The amount of ETH available to the project for withdraw.
*/
function getAvailableProjectETH() public view returns (uint256) {
return getUnlockedProjectETH()
.sub(projectWithdrawnETH);
}
/**
* @notice Returns the participant's amount of locked tokens at the current block.
* @param _participantAddress The participant's address.
*/
function getParticipantReservedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
if(participantStats._currentReservedTokens == 0) {
return 0;
}
return participantStats._currentReservedTokens.sub(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the participant's amount of unlocked tokens at the current block.
* This function is used for internal sanity checks.
* Note: this value can differ from the actual unlocked token balance of the participant, if he received tokens from other sources than the rICO.
* @param _participantAddress The participant's address.
*/
function getParticipantUnlockedTokens(address _participantAddress) public view returns (uint256) {
Participant storage participantStats = participants[_participantAddress];
return participantStats._unlockedTokens.add(
calcUnlockedAmount(participantStats._currentReservedTokens, participantStats._lastBlock)
);
}
/**
* @notice Returns the token amount that are still available at the current stage
* @return The amount of tokens
*/
function getAvailableTokenAtCurrentStage() public view returns (uint256) {
return stages[getCurrentStage()].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current stage at current sold token amount
* @return The current stage ID
*/
function getCurrentStage() public view returns (uint8) {
return getStageByTokenLimit(
initialTokenSupply.sub(tokenSupply)
);
}
/**
* @notice Returns the current token price at the current stage.
* @return The current ETH price in wei.
*/
function getCurrentPrice() public view returns (uint256) {
return getPriceAtStage(getCurrentStage());
}
/**
* @notice Returns the token price at the specified stage ID.
* @param _stageId the stage ID at which we want to retrieve the token price.
*/
function getPriceAtStage(uint8 _stageId) public view returns (uint256) {
if (_stageId <= stageCount) {
return stages[_stageId].tokenPrice;
}
return stages[stageCount].tokenPrice;
}
/**
* @notice Returns the token price for when a specific amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the respective token price
* @return The ETH price in wei
*/
function getPriceForTokenLimit(uint256 _tokenLimit) public view returns (uint256) {
return getPriceAtStage(getStageByTokenLimit(_tokenLimit));
}
/**
* @notice Returns the stage at a point where a certain amount of tokens is sold
* @param _tokenLimit The amount of tokens for which we want to know the stage ID
*/
function getStageByTokenLimit(uint256 _tokenLimit) public view returns (uint8) {
// Go through all stages, until we find the one that matches the supply
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
if(_tokenLimit <= stages[stageId].tokenLimit) {
return stageId;
}
}
// if amount is more than available stages return last stage with the highest price
return stageCount;
}
/**
* @notice Returns the rICOs available ETH to reserve tokens at a given stage.
* @param _stageId the stage ID.
*/
function committableEthAtStage(uint8 _stageId, uint8 _currentStage) public view returns (uint256) {
uint256 supply;
// past stages
if(_stageId < _currentStage) {
return 0;
// last stage
} else if(_stageId >= stageCount) {
supply = tokenSupply;
// current stage
} else if(_stageId == _currentStage) {
supply = stages[_currentStage].tokenLimit.sub(
initialTokenSupply.sub(tokenSupply)
);
// later stages
} else if(_stageId > _currentStage) {
supply = stages[_stageId].tokenLimit.sub(stages[_stageId - 1].tokenLimit); // calc difference to last stage
}
return getEthAmountForTokensAtStage(
supply
, _stageId);
}
/**
* @notice Returns the amount of ETH (in wei) for a given token amount at a given stage.
* @param _tokenAmount The amount of token.
* @param _stageId the stage ID.
* @return The ETH amount in wei
*/
function getEthAmountForTokensAtStage(uint256 _tokenAmount, uint8 _stageId) public view returns (uint256) {
return _tokenAmount
.mul(stages[_stageId].tokenPrice)
.div(10 ** 18);
}
/**
* @notice Returns the amount of tokens that given ETH would buy at a given stage.
* @param _ethAmount The ETH amount in wei.
* @param _stageId the stage ID.
* @return The token amount in its smallest unit (token "wei")
*/
function getTokenAmountForEthAtStage(uint256 _ethAmount, uint8 _stageId) public view returns (uint256) {
return _ethAmount
.mul(10 ** 18)
.div(stages[_stageId].tokenPrice);
}
/**
* @notice Returns the current block number: required in order to override when running tests.
*/
function getCurrentBlockNumber() public view returns (uint256) {
return uint256(block.number);
}
/**
* @notice Returns the current block number - the frozen period: required in order to override when running tests.
*/
function getCurrentEffectiveBlockNumber() public view returns (uint256) {
return uint256(block.number)
.sub(frozenPeriod); // make sure we deduct any frozenPeriod from calculations
}
/**
* @notice rICO HEART: Calculates the unlocked amount tokens/ETH beginning from the buy phase start or last block to the current block.
* This function is used by the participants as well as the project, to calculate the current unlocked amount.
*
* @return the unlocked amount of tokens or ETH.
*/
function calcUnlockedAmount(uint256 _amount, uint256 _lastBlock) public view returns (uint256) {
uint256 currentBlock = getCurrentEffectiveBlockNumber();
if(_amount == 0) {
return 0;
}
// Calculate WITHIN the buy phase
if (currentBlock >= buyPhaseStartBlock && currentBlock < buyPhaseEndBlock) {
// security/no-assign-params: "calcUnlockedAmount": Avoid assigning to function parameters.
uint256 lastBlock = _lastBlock;
if(lastBlock < buyPhaseStartBlock) {
lastBlock = buyPhaseStartBlock.sub(1); // We need to reduce it by 1, as the startBlock is always already IN the period.
}
// get the number of blocks that have "elapsed" since the last block
uint256 passedBlocks = currentBlock.sub(lastBlock);
// number of blocks ( ie: start=4/end=10 => 10 - 4 => 6 )
uint256 totalBlockCount = buyPhaseEndBlock.sub(lastBlock);
return _amount.mul(
passedBlocks.mul(10 ** 20)
.div(totalBlockCount)
).div(10 ** 20);
// Return everything AFTER the buy phase
} else if (currentBlock >= buyPhaseEndBlock) {
return _amount;
}
// Return nothing BEFORE the buy phase
return 0;
}
/*
* Internal functions
* ------------------------------------------------------------------------------------------------
*/
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckProject() internal view {
// PROJECT: The sum of reserved + unlocked has to be equal the committedETH.
require(
committedETH == _projectCurrentlyReservedETH.add(_projectUnlockedETH),
'Project Sanity check failed! Reserved + Unlock must equal committedETH'
);
// PROJECT: The ETH in the rICO has to be the total of unlocked + reserved - withdraw
require(
address(this).balance == _projectUnlockedETH.add(_projectCurrentlyReservedETH).add(pendingETH).sub(projectWithdrawnETH),
'Project sanity check failed! balance = Unlock + Reserved - Withdrawn'
);
}
/**
* @notice Checks the projects core variables and ETH amounts in the contract for correctness.
*/
function sanityCheckParticipant(address _participantAddress) internal view {
Participant storage participantStats = participants[_participantAddress];
// PARTICIPANT: The sum of reserved + unlocked has to be equal the totalReserved.
require(
participantStats.reservedTokens == participantStats._currentReservedTokens.add(participantStats._unlockedTokens),
'Participant Sanity check failed! Reser. + Unlock must equal totalReser'
);
}
/**
* @notice Calculates the projects allocation since the last calculation.
*/
function calcProjectAllocation() internal {
uint256 newlyUnlockedEth = calcUnlockedAmount(_projectCurrentlyReservedETH, _projectLastBlock);
// UPDATE GLOBAL STATS
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(newlyUnlockedEth);
_projectUnlockedETH = _projectUnlockedETH.add(newlyUnlockedEth);
_projectLastBlock = getCurrentEffectiveBlockNumber();
sanityCheckProject();
}
/**
* @notice Calculates the participants allocation since the last calculation.
*/
function calcParticipantAllocation(address _participantAddress) internal {
Participant storage participantStats = participants[_participantAddress];
// UPDATE the locked/unlocked ratio for this participant
participantStats._unlockedTokens = getParticipantUnlockedTokens(_participantAddress);
participantStats._currentReservedTokens = getParticipantReservedTokens(_participantAddress);
// RESET BLOCK NUMBER: Force the unlock calculations to start from this point in time.
participantStats._lastBlock = getCurrentEffectiveBlockNumber();
// UPDATE the locked/unlocked ratio for the project as well
calcProjectAllocation();
}
/**
* @notice Cancels any participant's pending ETH contributions.
* Pending is any ETH from participants that are not whitelisted yet.
*/
function cancelPendingContributions(address _participantAddress, uint256 _sentValue)
internal
isInitialized
isNotFrozen
{
Participant storage participantStats = participants[_participantAddress];
uint256 participantPendingEth = participantStats.pendingETH;
// Fail silently if no ETH are pending
if(participantPendingEth == 0) {
// sent at least back what he contributed
if(_sentValue > 0) {
address(uint160(_participantAddress)).transfer(_sentValue);
}
return;
}
// UPDATE PARTICIPANT STAGES
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
participantStats.stages[stageId].pendingETH = 0;
}
// UPDATE PARTICIPANT STATS
participantStats.pendingETH = 0;
// UPDATE GLOBAL STATS
canceledETH = canceledETH.add(participantPendingEth);
pendingETH = pendingETH.sub(participantPendingEth);
// Emit events
emit PendingContributionsCanceled(_participantAddress, participantPendingEth, uint32(participantStats.contributions));
emit TransferEvent(
uint8(TransferTypes.CONTRIBUTION_CANCELED),
_participantAddress,
participantPendingEth
);
// transfer ETH back to participant including received value
address(uint160(_participantAddress)).transfer(participantPendingEth.add(_sentValue));
// SANITY check
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Accept a participant's contribution.
* @param _participantAddress Participant's address.
*/
function acceptContributions(address _participantAddress)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
// Fail silently if no ETH are pending
if (participantStats.pendingETH == 0) {
return;
}
uint8 currentStage = getCurrentStage();
uint256 totalRefundedETH;
uint256 totalNewReservedTokens;
calcParticipantAllocation(_participantAddress);
// set the first contribution block
if(participantStats.committedETH == 0) {
participantStats.firstContributionBlock = participantStats._lastBlock; // `_lastBlock` was set in calcParticipantAllocation()
}
// Iterate over all stages and their pending contributions
for (uint8 stageId = 0; stageId <= stageCount; stageId++) {
ParticipantStageDetails storage byStage = participantStats.stages[stageId];
// skip if not ETH is pending
if (byStage.pendingETH == 0) {
continue;
}
// skip if stage is below "currentStage" (as they have no available tokens)
if(stageId < currentStage) {
// add this stage pendingETH to the "currentStage"
participantStats.stages[currentStage].pendingETH = participantStats.stages[currentStage].pendingETH.add(byStage.pendingETH);
// and reset this stage
byStage.pendingETH = 0;
continue;
}
// --> We continue only if in "currentStage" or later stages
uint256 maxCommittableEth = committableEthAtStage(stageId, currentStage);
uint256 newlyCommittableEth = byStage.pendingETH;
uint256 returnEth = 0;
uint256 overflowEth = 0;
// If incoming value is higher than what we can accept,
// just accept the difference and return the rest
if (newlyCommittableEth > maxCommittableEth) {
overflowEth = newlyCommittableEth.sub(maxCommittableEth);
newlyCommittableEth = maxCommittableEth;
// if in the last stage, return ETH
if (stageId == stageCount) {
returnEth = overflowEth;
totalRefundedETH = totalRefundedETH.add(returnEth);
// if below the last stage, move pending ETH to the next stage
} else {
participantStats.stages[stageId + 1].pendingETH = participantStats.stages[stageId + 1].pendingETH.add(overflowEth);
byStage.pendingETH = byStage.pendingETH.sub(overflowEth);
}
}
// convert ETH to TOKENS
uint256 newTokenAmount = getTokenAmountForEthAtStage(
newlyCommittableEth, stageId
);
totalNewReservedTokens = totalNewReservedTokens.add(newTokenAmount);
// UPDATE PARTICIPANT STATS
participantStats._currentReservedTokens = participantStats._currentReservedTokens.add(newTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.add(newTokenAmount);
participantStats.committedETH = participantStats.committedETH.add(newlyCommittableEth);
participantStats.pendingETH = participantStats.pendingETH.sub(newlyCommittableEth).sub(returnEth);
byStage.pendingETH = byStage.pendingETH.sub(newlyCommittableEth).sub(returnEth);
// UPDATE GLOBAL STATS
tokenSupply = tokenSupply.sub(newTokenAmount);
pendingETH = pendingETH.sub(newlyCommittableEth).sub(returnEth);
committedETH = committedETH.add(newlyCommittableEth);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.add(newlyCommittableEth);
// Emit event
emit ContributionsAccepted(_participantAddress, newlyCommittableEth, newTokenAmount, stageId);
}
// Refund what couldn't be accepted
if (totalRefundedETH > 0) {
emit TransferEvent(uint8(TransferTypes.CONTRIBUTION_ACCEPTED_OVERFLOW), _participantAddress, totalRefundedETH);
address(uint160(_participantAddress)).transfer(totalRefundedETH);
}
// Transfer tokens to the participant
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, totalNewReservedTokens, "");
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/**
* @notice Allow a participant to withdraw by sending tokens back to rICO contract.
* @param _participantAddress participant address.
* @param _returnedTokenAmount The amount of tokens returned.
*/
function withdraw(address _participantAddress, uint256 _returnedTokenAmount)
internal
isInitialized
isNotFrozen
isRunning
{
Participant storage participantStats = participants[_participantAddress];
calcParticipantAllocation(_participantAddress);
require(_returnedTokenAmount > 0, 'You can not withdraw without sending tokens.');
require(participantStats._currentReservedTokens > 0 && participantStats.reservedTokens > 0, 'You can not withdraw, you have no locked tokens.');
uint256 returnedTokenAmount = _returnedTokenAmount;
uint256 overflowingTokenAmount;
uint256 returnEthAmount;
// Only allow reserved tokens be returned, return the overflow.
if (returnedTokenAmount > participantStats._currentReservedTokens) {
overflowingTokenAmount = returnedTokenAmount.sub(participantStats._currentReservedTokens);
returnedTokenAmount = participantStats._currentReservedTokens;
}
// Calculate the return amount
returnEthAmount = participantStats.committedETH.mul(
returnedTokenAmount.sub(1).mul(10 ** 20) // deduct 1 token-wei to minimize rounding issues
.div(participantStats.reservedTokens)
).div(10 ** 20);
// UPDATE PARTICIPANT STATS
participantStats.withdraws++;
participantStats._currentReservedTokens = participantStats._currentReservedTokens.sub(returnedTokenAmount);
participantStats.reservedTokens = participantStats.reservedTokens.sub(returnedTokenAmount);
participantStats.committedETH = participantStats.committedETH.sub(returnEthAmount);
// UPDATE global STATS
tokenSupply = tokenSupply.add(returnedTokenAmount);
withdrawnETH = withdrawnETH.add(returnEthAmount);
committedETH = committedETH.sub(returnEthAmount);
_projectCurrentlyReservedETH = _projectCurrentlyReservedETH.sub(returnEthAmount);
// Return overflowing tokens received
if (overflowingTokenAmount > 0) {
// send tokens back to participant
bytes memory data;
// Emit event
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW_OVERFLOW), _participantAddress, overflowingTokenAmount);
// solium-disable-next-line security/no-send
IERC777(tokenAddress).send(_participantAddress, overflowingTokenAmount, data);
}
// Emit events
emit ParticipantWithdraw(_participantAddress, returnEthAmount, returnedTokenAmount, uint32(participantStats.withdraws));
emit TransferEvent(uint8(TransferTypes.PARTICIPANT_WITHDRAW), _participantAddress, returnEthAmount);
// Return ETH back to participant
address(uint160(_participantAddress)).transfer(returnEthAmount);
// SANITY CHECK
sanityCheckParticipant(_participantAddress);
sanityCheckProject();
}
/*
* Modifiers
*/
/**
* @notice Checks if the sender is the project.
*/
modifier onlyProjectAddress() {
require(msg.sender == projectAddress, "Only the project can call this method.");
_;
}
/**
* @notice Checks if the sender is the deployer.
*/
modifier onlyDeployingAddress() {
require(msg.sender == deployingAddress, "Only the deployer can call this method.");
_;
}
/**
* @notice Checks if the sender is the whitelist controller.
*/
modifier onlyWhitelistingAddress() {
require(msg.sender == whitelistingAddress, "Only the whitelist controller can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyFreezerAddress() {
require(msg.sender == freezerAddress, "Only the freezer address can call this method.");
_;
}
/**
* @notice Checks if the sender is the freezer controller address.
*/
modifier onlyRescuerAddress() {
require(msg.sender == rescuerAddress, "Only the rescuer address can call this method.");
_;
}
/**
* @notice Requires the contract to have been initialized.
*/
modifier isInitialized() {
require(initialized == true, "Contract must be initialized.");
_;
}
/**
* @notice Requires the contract to NOT have been initialized,
*/
modifier isNotInitialized() {
require(initialized == false, "Contract can not be initialized.");
_;
}
/**
* @notice @dev Requires the contract to be frozen.
*/
modifier isFrozen() {
require(frozen == true, "rICO has to be frozen!");
_;
}
/**
* @notice @dev Requires the contract not to be frozen.
*/
modifier isNotFrozen() {
require(frozen == false, "rICO is frozen!");
_;
}
/**
* @notice Checks if the rICO is running.
*/
modifier isRunning() {
uint256 blockNumber = getCurrentEffectiveBlockNumber();
require(blockNumber >= commitPhaseStartBlock && blockNumber <= buyPhaseEndBlock, "Current block is outside the rICO period.");
_;
}
} | Allows the project to withdraw tokens. _tokenAmount The token amount./ decrease the supply sent all tokens from the contract to the _to address solium-disable-next-line security/no-send | function projectTokenWithdraw(uint256 _tokenAmount)
external
onlyProjectAddress
isInitialized
{
require(_tokenAmount <= tokenSupply, "Requested amount too high, not enough tokens available.");
tokenSupply = tokenSupply.sub(_tokenAmount);
initialTokenSupply = initialTokenSupply.sub(_tokenAmount);
IERC777(tokenAddress).send(projectAddress, _tokenAmount, "");
}
| 6,399,455 |
contract ShinySquirrels {
// all the things
uint private minDeposit = 10 finney;
uint private maxDeposit = 5 ether;
uint private baseFee = 5;
uint private baseMultiplier = 100;
uint private maxMultiplier = 160;
uint private currentPosition = 0;
uint private balance = 0;
uint private feeBalance = 0;
uint private totalDeposits = 0;
uint private totalPaid = 0;
uint private totalSquirrels = 0;
uint private totalShinyThings = 0;
uint private totalSprockets = 0;
uint private totalStars = 0;
uint private totalHearts = 0;
uint private totalSkips = 0;
address private owner = msg.sender;
struct PlayerEntry {
address addr;
uint deposit;
uint paid;
uint multiplier;
uint fee;
uint skip;
uint squirrels;
uint shinyThings;
uint sprockets;
uint stars;
uint hearts;
}
struct PlayerStat {
address addr;
uint entries;
uint deposits;
uint paid;
uint skips;
uint squirrels;
uint shinyThings;
uint sprockets;
uint stars;
uint hearts;
}
// player entries in the order received
PlayerEntry[] private players;
// The Line of players, keeping track as new players cut in...
uint[] theLine;
// individual player totals
mapping(address => PlayerStat) private playerStats;
// Shiny new contract, no copy & paste here!
function ShinySquirrels() {
owner = msg.sender;
}
function totals() constant returns(uint playerCount, uint currentPlaceInLine, uint playersWaiting, uint totalDepositsInFinneys, uint totalPaidOutInFinneys, uint squirrelFriends, uint shinyThingsFound, uint sprocketsCollected, uint starsWon, uint heartsEarned, uint balanceInFinneys, uint feeBalanceInFinneys) {
playerCount = players.length;
currentPlaceInLine = currentPosition;
playersWaiting = waitingForPayout();
totalDepositsInFinneys = totalDeposits / 1 finney;
totalPaidOutInFinneys = totalPaid / 1 finney;
squirrelFriends = totalSquirrels;
shinyThingsFound = totalShinyThings;
sprocketsCollected = totalSprockets;
starsWon = totalStars;
heartsEarned = totalHearts;
balanceInFinneys = balance / 1 finney;
feeBalanceInFinneys = feeBalance / 1 finney;
}
function settings() constant returns(uint minimumDepositInFinneys, uint maximumDepositInFinneys) {
minimumDepositInFinneys = minDeposit / 1 finney;
maximumDepositInFinneys = maxDeposit / 1 finney;
}
function playerByAddress(address addr) constant returns(uint entries, uint depositedInFinney, uint paidOutInFinney, uint skippedAhead, uint squirrels, uint shinyThings, uint sprockets, uint stars, uint hearts) {
entries = playerStats[addr].entries;
depositedInFinney = playerStats[addr].deposits / 1 finney;
paidOutInFinney = playerStats[addr].paid / 1 finney;
skippedAhead = playerStats[addr].skips;
squirrels = playerStats[addr].squirrels;
shinyThings = playerStats[addr].shinyThings;
sprockets = playerStats[addr].sprockets;
stars = playerStats[addr].stars;
hearts = playerStats[addr].hearts;
}
// current number of players still waiting for their payout
function waitingForPayout() constant private returns(uint waiting) {
waiting = players.length - currentPosition;
}
// the total payout this entry in line will receive
function entryPayout(uint index) constant private returns(uint payout) {
payout = players[theLine[index]].deposit * players[theLine[index]].multiplier / 100;
}
// the payout amount still due to this entry in line
function entryPayoutDue(uint index) constant private returns(uint payoutDue) {
// subtract the amount they've been paid from the total they are to receive
payoutDue = entryPayout(index) - players[theLine[index]].paid;
}
// public interface to the line of players
function lineOfPlayers(uint index) constant returns (address addr, uint orderJoined, uint depositInFinney, uint payoutInFinney, uint multiplierPercent, uint paid, uint skippedAhead, uint squirrels, uint shinyThings, uint sprockets, uint stars, uint hearts) {
PlayerEntry player = players[theLine[index]];
addr = player.addr;
orderJoined = theLine[index];
depositInFinney = player.deposit / 1 finney;
payoutInFinney = depositInFinney * player.multiplier / 100;
multiplierPercent = player.multiplier;
paid = player.paid / 1 finney;
skippedAhead = player.skip;
squirrels = player.squirrels;
shinyThings = player.shinyThings;
sprockets = player.sprockets;
stars = player.stars;
hearts = player.hearts;
}
function () {
play();
}
function play() {
uint deposit = msg.value; // in wei
// validate deposit is in range
if(deposit < minDeposit || deposit > maxDeposit) {
msg.sender.send(deposit);
return;
}
uint multiplier = baseMultiplier; // percent
uint fee = baseFee; // percent
uint skip = 0;
uint squirrels = 0;
uint shinyThings = 0;
uint sprockets = 0;
uint stars = 0;
uint hearts = 0;
if(players.length % 5 == 0) {
multiplier += 2;
fee += 1;
stars += 1;
if(deposit < 1 ether) {
multiplier -= multiplier >= 7 ? 7 : multiplier;
fee -= fee >= 1 ? 1 : 0;
shinyThings += 1;
}
if(deposit >= 1 && waitingForPayout() >= 10) {
// at least 10 players waiting
skip += 4;
fee += 3;
}
if(deposit >= 2 ether && deposit <= 3 ether) {
multiplier += 3;
fee += 2;
hearts += 1;
}
if(deposit >= 3 ether) {
stars += 1;
}
} else if (players.length % 5 == 1) {
multiplier += 4;
fee += 2;
squirrels += 1;
if(deposit < 1 ether) {
multiplier += 6;
fee += 3;
squirrels += 1;
}
if(deposit >= 2 ether) {
if(waitingForPayout() >= 20) {
// at least 20 players waiting
skip += waitingForPayout() / 2; // skip half of them
fee += 2;
shinyThings += 1;
}
multiplier += 4;
fee += 4;
hearts += 1;
}
if(deposit >= 4 ether) {
multiplier += 1;
fee -= fee >= 1 ? 1 : 0;
skip += 1;
hearts += 1;
stars += 1;
}
} else if (players.length % 5 == 2) {
multiplier += 7;
fee += 6;
sprockets += 1;
if(waitingForPayout() >= 10) {
// at least 10 players waiting
multiplier -= multiplier >= 8 ? 8 : multiplier;
fee -= fee >= 1 ? 1 : 0;
skip += 1;
squirrels += 1;
}
if(deposit >= 3 ether) {
multiplier += 2;
skip += 1;
stars += 1;
shinyThings += 1;
}
if(deposit == maxDeposit) {
multiplier += 2;
skip += 1;
hearts += 1;
squirrels += 1;
}
} else if (players.length % 5 == 3) {
multiplier -= multiplier >= 5 ? 5 : multiplier; // on noes!
fee += 0;
skip += 3; // oh yay!
shinyThings += 1;
if(deposit < 1 ether) {
multiplier -= multiplier >= 5 ? 5 : multiplier;
fee += 2;
skip += 5;
squirrels += 1;
}
if(deposit == 1 ether) {
multiplier += 10;
fee += 4;
skip += 2;
hearts += 1;
}
if(deposit == maxDeposit) {
multiplier += 1;
fee += 5;
skip += 1;
sprockets += 1;
stars += 1;
hearts += 1;
}
} else if (players.length % 5 == 4) {
multiplier += 2;
fee -= fee >= 1 ? 1 : fee;
squirrels += 1;
if(deposit < 1 ether) {
multiplier += 3;
fee += 2;
skip += 3;
}
if(deposit >= 2 ether) {
multiplier += 2;
fee += 2;
skip += 1;
stars += 1;
}
if(deposit == maxDeposit/2) {
multiplier += 2;
fee += 5;
skip += 3;
shinyThings += 1;
sprockets += 1;
}
if(deposit >= 3 ether) {
multiplier += 1;
fee += 1;
skip += 1;
sprockets += 1;
hearts += 1;
}
}
// track the accumulated bonus goodies!
playerStats[msg.sender].hearts += hearts;
playerStats[msg.sender].stars += stars;
playerStats[msg.sender].squirrels += squirrels;
playerStats[msg.sender].shinyThings += shinyThings;
playerStats[msg.sender].sprockets += sprockets;
// track cummulative awarded goodies
totalHearts += hearts;
totalStars += stars;
totalSquirrels += squirrels;
totalShinyThings += shinyThings;
totalSprockets += sprockets;
// got squirrels? skip in front of that many players!
skip += playerStats[msg.sender].squirrels;
// one squirrel ran away!
playerStats[msg.sender].squirrels -= playerStats[msg.sender].squirrels >= 1 ? 1 : 0;
// got stars? 2% multiplier bonus for every star!
multiplier += playerStats[msg.sender].stars * 2;
// got hearts? -2% fee for every heart!
fee -= playerStats[msg.sender].hearts;
// got sprockets? 1% multiplier bonus and -1% fee for every sprocket!
multiplier += playerStats[msg.sender].sprockets;
fee -= fee > playerStats[msg.sender].sprockets ? playerStats[msg.sender].sprockets : fee;
// got shiny things? skip 1 more player and -1% fee!
if(playerStats[msg.sender].shinyThings >= 1) {
skip += 1;
fee -= fee >= 1 ? 1 : 0;
}
// got a heart, star, squirrel, shiny thin, and sprocket?!? 50% bonus multiplier!!!
if(playerStats[msg.sender].hearts >= 1 && playerStats[msg.sender].stars >= 1 && playerStats[msg.sender].squirrels >= 1 && playerStats[msg.sender].shinyThings >= 1 && playerStats[msg.sender].sprockets >= 1) {
multiplier += 30;
}
// got a heart and a star? trade them for +20% multiplier!!!
if(playerStats[msg.sender].hearts >= 1 && playerStats[msg.sender].stars >= 1) {
multiplier += 15;
playerStats[msg.sender].hearts -= 1;
playerStats[msg.sender].stars -= 1;
}
// got a sprocket and a shiny thing? trade them for 5 squirrels!
if(playerStats[msg.sender].sprockets >= 1 && playerStats[msg.sender].shinyThings >= 1) {
playerStats[msg.sender].squirrels += 5;
playerStats[msg.sender].sprockets -= 1;
playerStats[msg.sender].shinyThings -= 1;
}
// stay within profitable and safe limits
if(multiplier > maxMultiplier) {
multiplier == maxMultiplier;
}
// keep power players in check so regular players can still win some too
if(waitingForPayout() > 15 && skip > waitingForPayout()/2) {
// limit skip to half of waiting players
skip = waitingForPayout() / 2;
}
// ledgers within ledgers
feeBalance += deposit * fee / 100;
balance += deposit - deposit * fee / 100;
totalDeposits += deposit;
// prepare players array for a new entry
uint playerIndex = players.length;
players.length += 1;
// make room in The Line for one more
uint lineIndex = theLine.length;
theLine.length += 1;
// skip ahead if you should be so lucky!
(skip, lineIndex) = skipInLine(skip, lineIndex);
// record the players entry
players[playerIndex].addr = msg.sender;
players[playerIndex].deposit = deposit;
players[playerIndex].multiplier = multiplier;
players[playerIndex].fee = fee;
players[playerIndex].squirrels = squirrels;
players[playerIndex].shinyThings = shinyThings;
players[playerIndex].sprockets = sprockets;
players[playerIndex].stars = stars;
players[playerIndex].hearts = hearts;
players[playerIndex].skip = skip;
// add the player to The Line at whatever position they snuck in at
theLine[lineIndex] = playerIndex;
// track players cumulative stats
playerStats[msg.sender].entries += 1;
playerStats[msg.sender].deposits += deposit;
playerStats[msg.sender].skips += skip;
// track total game skips
totalSkips += skip;
// issue payouts while the balance allows
// rolling payouts occur as long as the balance is above zero
uint nextPayout = entryPayoutDue(currentPosition);
uint payout;
while(balance > 0) {
if(nextPayout <= balance) {
// the balance is great enough to pay the entire next balance due
// pay the balance due
payout = nextPayout;
} else {
// the balance is above zero, but less than the next balance due
// send them everything available
payout = balance;
}
// issue the payment
players[theLine[currentPosition]].addr.send(payout);
// mark the amount paid
players[theLine[currentPosition]].paid += payout;
// keep a global tally
playerStats[players[theLine[currentPosition]].addr].paid += payout;
balance -= payout;
totalPaid += payout;
// move to the next position in line if the last entry got paid out completely
if(balance > 0) {
currentPosition++;
nextPayout = entryPayoutDue(currentPosition);
}
}
}
// jump in line, moving entries back towards the end one at a time
// presumes the line length has already been increased to accomodate the newcomer
// return the the number of positions skipped and the index of the vacant position in line
function skipInLine(uint skip, uint currentLineIndex) private returns (uint skipped, uint newLineIndex) {
// check for at least 1 player in line plus this new entry
if(skip > 0 && waitingForPayout() > 2) {
// -2 because we don't want to count the new empty slot at the end of the list
if(skip > waitingForPayout()-2) {
skip = waitingForPayout()-2;
}
// move entries forward one by one
uint i = 0;
while(i < skip) {
theLine[currentLineIndex-i] = theLine[currentLineIndex-1-i];
i++;
}
// don't leave a duplicate copy of the last entry processed
delete(theLine[currentLineIndex-i]);
// the newly vacant position is i slots from the end
newLineIndex = currentLineIndex-i;
} else {
// no change
newLineIndex = currentLineIndex;
skip = 0;
}
skipped = skip;
}
function DynamicPyramid() {
// Rubixi god-code, j/k :-P
playerStats[msg.sender].squirrels = 0;
playerStats[msg.sender].shinyThings = 0;
playerStats[msg.sender].sprockets = 0;
playerStats[msg.sender].stars = 0;
playerStats[msg.sender].hearts = 0;
}
function collectFees() {
if(msg.sender != owner) {
throw;
}
// game balance will always be zero due to automatic rolling payouts
if(address(this).balance > balance + feeBalance) {
// collect any funds outside of the game balance
feeBalance = address(this).balance - balance;
}
owner.send(feeBalance);
feeBalance = 0;
}
function updateSettings(uint newMultiplier, uint newMaxMultiplier, uint newFee, uint newMinDeposit, uint newMaxDeposit, bool collect) {
// adjust the base settings within a small and limited range as the game matures and ether prices change
if(msg.sender != owner) throw;
if(newMultiplier < 80 || newMultiplier > 120) throw;
if(maxMultiplier < 125 || maxMultiplier > 200) throw;
if(newFee < 0 || newFee > 15) throw;
if(minDeposit < 1 finney || minDeposit > 1 ether) throw;
if(maxDeposit < 1 finney || maxDeposit > 25 ether) throw;
if(collect) collectFees();
baseMultiplier = newMultiplier;
maxMultiplier = newMaxMultiplier;
baseFee = newFee;
minDeposit = newMinDeposit;
maxDeposit = newMaxDeposit;
}
} | game balance will always be zero due to automatic rolling payouts collect any funds outside of the game balance | function collectFees() {
if(msg.sender != owner) {
throw;
}
if(address(this).balance > balance + feeBalance) {
feeBalance = address(this).balance - balance;
}
owner.send(feeBalance);
feeBalance = 0;
}
| 12,966,860 |
./full_match/1/0x631b949c7e0fdef95e612165798E09aD46b5635c/sources/contracts/oasis-main/OasisAccessPass.sol | Returns the token ID of the user. _user User address. return tokenId_ Token ID of the user./ | function getID(address _user) public view returns (uint256 tokenId_) {
return addressToId[_user];
}
| 3,181,607 |
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/ERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/extensions/ERC20BurnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import "../interfaces/INotaryNFT.sol";
import "../interfaces/IxDraceDistributor.sol";
import "../interfaces/IDeathRoadNFT.sol";
import "../interfaces/INFTFactoryV2.sol";
import "../interfaces/INFTFactory.sol";
import "../interfaces/INFTStorage.sol";
import "../interfaces/IMint.sol";
import "../lib/SignerRecover.sol";
contract NFTFactoryV3 is
Initializable,
ContextUpgradeable,
UUPSUpgradeable,
OwnableUpgradeable,
INFTFactoryV2,
SignerRecover
{
using SafeMathUpgradeable for uint256;
address public DRACE;
address payable public feeTo;
event NewBox(address owner, uint256 boxId);
event OpenBox(address owner, uint256 boxId, uint256 tokenId);
event UpgradeToken(
address owner,
uint256[3] oldTokenId,
bool upgradeStatus,
bool useCharm,
uint256 tokenId
);
event BoxRewardUpdated(address addr, uint256 reward);
event SetMasterChef(address addr, bool val);
//commit reveal needs 2 steps, the reveal step needs to pay fee by bot, this fee is to compensate for bots
uint256 public SETTLE_FEE;
address payable public SETTLE_FEE_RECEIVER;
mapping(address => bool) public masterChefs;
uint256 public boxDiscountPercent;
mapping(address => bool) public mappingApprover;
IDeathRoadNFT public nft;
//open and settle box data structure
mapping(bytes32 => OpenBoxInfo) public _openBoxInfo;
mapping(address => bytes32[]) public allOpenBoxes;
mapping(uint256 => bool) public committedBoxes;
bytes32[] public allBoxCommitments;
event CommitOpenBox(
address owner,
bytes boxType,
bytes packType,
uint256 boxCount,
bytes32 commitment
);
//upgrade datastructure
mapping(bytes32 => UpgradeInfo) public _upgradesInfo;
mapping(bytes32 => UpgradeInfoV2) public _upgradesInfoV2;
mapping(address => bytes32[]) public allUpgrades;
bytes32[] public allUpgradeCommitments;
event CommitUpgradeFeature(address owner, bytes32 commitment);
INFTFactory public oldFactory;
IMint public xDrace;
INFTFactoryV2 public factoryV2;
INotaryNFT public notaryHook;
INFTStorage public nftStorageHook;
mapping(address => bool) public override alreadyMinted;
IxDraceDistributor public xDraceVesting;
uint256 public devFundPercent;
/// @custom:oz-upgrades-unsafe-allow constructor
constructor() initializer {}
function _authorizeUpgrade(address) internal override onlyOwner {}
function initialize(
address _nft,
address DRACE_token,
address payable _feeTo,
address _notaryHook,
address _nftStorageHook,
address _masterChef,
address _v,
address _xDrace
) external initializer {
__Ownable_init();
__Context_init();
SETTLE_FEE = 0.01 ether;
devFundPercent = 10;
nft = IDeathRoadNFT(_nft);
DRACE = DRACE_token;
feeTo = _feeTo;
notaryHook = INotaryNFT(_notaryHook);
masterChefs[_masterChef] = true;
nftStorageHook = INFTStorage(_nftStorageHook);
xDraceVesting = IxDraceDistributor(_v);
xDrace = IMint(_xDrace);
boxDiscountPercent = 70;
oldFactory = INFTFactory(0x9accf295895595D694b5D9E781082686dfa2801A);
factoryV2 = INFTFactoryV2(0x817e1F3C6987E4185E75db630591244b7B1a17d1);
}
modifier onlyBoxOwner(uint256 boxId) {
require(nft.isBoxOwner(msg.sender, boxId), "!not box owner");
_;
}
modifier boxNotOpen(uint256 boxId) {
require(!nft.isBoxOpen(boxId), "box already open");
_;
}
function setSettleFee(uint256 _fee) external onlyOwner {
SETTLE_FEE = _fee;
}
function setSettleFeeReceiver(address payable _bot) external onlyOwner {
SETTLE_FEE_RECEIVER = _bot;
}
function getBoxes() public view returns (bytes[] memory) {
return nft.getBoxes();
}
function getPacks() public view returns (bytes[] memory) {
return nft.getPacks();
}
function setFeeTo(address payable _feeTo) public onlyOwner {
feeTo = _feeTo;
}
function addBox(bytes memory _box) public onlyOwner {
nft.addBox(_box);
}
function addBoxes(bytes[] memory _boxes) public onlyOwner {
nft.addBoxes(_boxes);
}
function addPack(bytes memory _pack) public onlyOwner {
nft.addPack(_pack);
}
function addPacks(bytes[] memory _packs) public onlyOwner {
nft.addPacks(_packs);
}
function setBoxDiscountPercent(uint256 _discount) external onlyOwner {
boxDiscountPercent = _discount;
}
function _buyBox(bytes memory _box, bytes memory _pack)
internal
returns (uint256)
{
uint256 boxId = nft.buyBox(msg.sender, _box, _pack);
emit NewBox(msg.sender, boxId);
return boxId;
}
function buyCharm(
uint256 _price,
bool _useXdrace,
uint256 _expiryTime,
bytes32 r,
bytes32 s,
uint8 v
) public {
require(block.timestamp <= _expiryTime, "Expired");
bytes32 message = keccak256(
abi.encode("buyCharm", msg.sender, _price, _useXdrace, _expiryTime)
);
require(verifySignature(r, s, v, message), "Signature invalid");
transferBoxFee(_price, _useXdrace);
nft.buyCharm(msg.sender);
}
function getAllBoxCommitments() external view returns (bytes32[] memory) {
return allBoxCommitments;
}
function openBoxInfo(bytes32 _comm)
external
view
override
returns (OpenBoxInfo memory)
{
return _openBoxInfo[_comm];
}
function getLatestTokenMinted(address _addr)
external
view
returns (uint256)
{
return nft.latestTokenMinted(_addr);
}
function updateFeature(
uint256 tokenId,
bytes memory featureName,
bytes memory featureValue,
uint256 _draceFee,
uint256 _expiryTime,
bytes32 r,
bytes32 s,
uint8 v
) external {
require(
nft.ownerOf(tokenId) == msg.sender,
"updateFeature: only token owner"
);
require(block.timestamp <= _expiryTime, "buyAndCommitOpenBox:Expired");
IERC20Upgradeable erc20 = IERC20Upgradeable(DRACE);
if (_draceFee > 0) {
erc20.transferFrom(msg.sender, feeTo, _draceFee);
}
bytes32 message = keccak256(
abi.encode(
"updateFeature",
msg.sender,
tokenId,
featureName,
featureValue,
_draceFee,
_expiryTime
)
);
require(
verifySignature(r, s, v, message),
"updateFeature: Signature invalid"
);
nft.updateFeature(msg.sender, tokenId, featureName, featureValue);
}
function setNFTStorage(address _storage) external onlyOwner {
nftStorageHook = INFTStorage(_storage);
}
function buyAndCommitOpenBox(
bytes memory _box,
bytes memory _pack,
uint256 _numBox,
uint256 _price,
uint16[] memory _featureValueIndexesSet,
bool _useBoxReward,
bytes32 _commitment,
uint256 _expiryTime,
bytes32 r,
bytes32 s,
uint8 v
) external payable {
require(
msg.value == SETTLE_FEE * _numBox,
"commitOpenBox: must pay settle fee"
);
SETTLE_FEE_RECEIVER.transfer(msg.value);
//verify signature
require(block.timestamp <= _expiryTime, "buyAndCommitOpenBox:Expired");
for (uint256 i = 0; i < _featureValueIndexesSet.length; i++) {
require(
_featureValueIndexesSet[i] < nftStorageHook.getSetLength(),
"buyAndCommitOpenBox: _featureValueIndexesSet out of rage"
);
}
bytes32 message = keccak256(
abi.encode(
"buyAndCommitOpenBox",
msg.sender,
_box,
_pack,
_numBox,
_price,
_featureValueIndexesSet,
_useBoxReward,
_commitment,
_expiryTime
)
);
require(
verifySignature(r, s, v, message),
"buyAndCommitOpenBox: Signature invalid"
);
transferBoxFee(_numBox.mul(_price), _useBoxReward);
uint256 boxId;
for (uint256 i = 0; i < _numBox; i++) {
boxId = _buyBox(_box, _pack);
committedBoxes[boxId] = true;
}
//commit open box
allBoxCommitments.push(_commitment);
require(
_openBoxInfo[_commitment].user == address(0),
"buyAndCommitOpenBox:commitment overlap"
);
// require(
// _featureNameIndex.length == _featureValueIndexesSet[0].length,
// "buyAndCommitOpenBox:invalid input length"
// );
OpenBoxInfo storage info = _openBoxInfo[_commitment];
info.user = msg.sender;
info.boxIdFrom = boxId.add(1).sub(_numBox);
info.boxCount = _numBox;
info.featureValuesSet = _featureValueIndexesSet;
info.previousBlockHash = blockhash(block.number - 1);
allOpenBoxes[msg.sender].push(_commitment);
emit CommitOpenBox(msg.sender, _box, _pack, _numBox, _commitment);
}
function transferBoxFee(uint256 _price, bool _useBoxReward) internal {
IERC20Upgradeable erc20 = IERC20Upgradeable(DRACE);
if (!_useBoxReward) {
erc20.transferFrom(msg.sender, feeTo, _price);
} else {
uint256 boxRewardSpent = _price.mul(boxDiscountPercent).div(100);
ERC20BurnableUpgradeable(address(xDrace)).burnFrom(msg.sender, boxRewardSpent);
erc20.transferFrom(msg.sender, feeTo, _price.sub(boxRewardSpent));
}
}
//in case server lose secret, it basically revoke box for user to open again
function revokeBoxId(uint256 boxId) external onlyOwner {
committedBoxes[boxId] = false;
}
//client compute result index off-chain, the function will verify it
function settleOpenBox(bytes32 secret) public {
bytes32 commitment = keccak256(abi.encode(secret));
OpenBoxInfo storage info = _openBoxInfo[commitment];
require(info.user != address(0), "settleOpenBox: commitment not exist");
require(
committedBoxes[info.boxIdFrom],
"settleOpenBox: box must be committed"
);
require(!info.settled, "settleOpenBox: already settled");
info.settled = true;
info.openBoxStatus = true;
uint256[] memory resultIndexes = notaryHook.getOpenBoxResult(
secret,
address(this)
);
//mint
for (uint256 i = 0; i < info.boxCount; i++) {
(
bytes[] memory _featureNames,
bytes[] memory _featureValues
) = nftStorageHook.getFeaturesByIndex(resultIndexes[i]);
uint256 tokenId = nft.mint(
info.user,
_featureNames,
_featureValues
);
nft.setBoxOpen(info.boxIdFrom + i, true);
emit OpenBox(info.user, info.boxIdFrom + i, tokenId);
}
}
function addApprover(address _approver, bool _val) public onlyOwner {
mappingApprover[_approver] = _val;
}
function verifySignature(
bytes32 r,
bytes32 s,
uint8 v,
bytes32 signedData
) internal view returns (bool) {
address signer = recoverSigner(r, s, v, signedData);
return mappingApprover[signer];
}
function getTokenFeatures(uint256 tokenId)
public
view
override
returns (bytes[] memory _featureNames, bytes[] memory)
{
return nft.getTokenFeatures(tokenId);
}
function existTokenFeatures(uint256 tokenId)
public
view
override
returns (bool)
{
return nft.existTokenFeatures(tokenId);
}
function getAllUpgradeCommitments()
external
view
returns (bytes32[] memory)
{
return allUpgradeCommitments;
}
function upgradesInfo(bytes32 _comm)
external
view
override
returns (UpgradeInfo memory)
{
return _upgradesInfo[_comm];
}
function upgradesInfoV2(bytes32 _comm)
external
view
override
returns (UpgradeInfoV2 memory)
{
return _upgradesInfoV2[_comm];
}
//upgrade consists of 2 steps following commit-reveal scheme to ensure transparency and security
//1. commitment by sending hash of a secret value
//2. reveal the secret and the upgrades randomly
//_tokenIds: tokens used for upgrades
//_featureNames: of new NFT
//_featureValues: of new NFT
//_useCharm: burn the input tokens or not when failed
function commitUpgradeFeatures(
uint256[3] memory _tokenIds,
uint256[] memory _featureValueIndexesSet,
uint256 _failureRate,
bool _useCharm,
uint256 _upgradeFee,
bool _useXDrace,
bytes32 _commitment,
uint256 _expiryTime,
bytes32[2] memory rs,
uint8 v
) public payable {
require(
msg.value == SETTLE_FEE,
"commitUpgradeFeatures: must pay settle fee"
);
SETTLE_FEE_RECEIVER.transfer(msg.value);
require(
block.timestamp <= _expiryTime,
"commitUpgradeFeatures: commitment expired"
);
require(
_upgradesInfoV2[_commitment].user == address(0),
"commitment overlap"
);
for (uint256 i = 0; i < _featureValueIndexesSet.length; i++) {
require(
_featureValueIndexesSet[i] < nftStorageHook.getSetLength(),
"buyAndCommitOpenBox: _featureValueIndexesSet out of rage"
);
}
allUpgradeCommitments.push(_commitment);
if (_useCharm) {
require(
nft.mappingLuckyCharm(msg.sender) > 0,
"commitUpgradeFeatures: you need to buy charm"
);
}
//verify infor
bytes32 message = keccak256(
abi.encode(
"commitUpgradeFeatures",
msg.sender,
_tokenIds,
_featureValueIndexesSet,
_failureRate,
_useCharm,
_upgradeFee,
_useXDrace,
_commitment,
_expiryTime
)
);
require(
verifySignature(rs[0], rs[1], v, message),
"commitUpgradeFeatures:Signature invalid"
);
transferBoxFee(_upgradeFee, _useXDrace);
//need to lock token Ids here
transferTokensIn(_tokenIds);
pushUpgradeInfo(
_commitment,
_useCharm,
_failureRate,
_tokenIds,
_featureValueIndexesSet
);
allUpgrades[msg.sender].push(_commitment);
}
function pushUpgradeInfo(
bytes32 _commitment,
bool _useCharm,
uint256 _failureRate,
uint256[3] memory _tokenIds,
uint256[] memory _featureValueIndexesSet
) internal {
_upgradesInfoV2[_commitment] = UpgradeInfoV2({
user: msg.sender,
useCharm: _useCharm,
failureRate: _failureRate,
upgradeStatus: false,
settled: false,
tokenIds: _tokenIds,
featureValueIndexesSet: _featureValueIndexesSet,
previousBlockHash: blockhash(block.number - 1)
});
emit CommitUpgradeFeature(msg.sender, _commitment);
}
function transferTokensIn(uint256[3] memory _tokenIds) internal {
nft.transferFrom(msg.sender, address(this), _tokenIds[0]);
nft.transferFrom(msg.sender, address(this), _tokenIds[1]);
nft.transferFrom(msg.sender, address(this), _tokenIds[2]);
}
function settleUpgradeFeatures(bytes32 secret) public {
bytes32 commitment = keccak256(abi.encode(secret));
require(
_upgradesInfoV2[commitment].user != address(0),
"settleUpgradeFeatures: commitment not exist"
);
require(
!_upgradesInfoV2[commitment].settled,
"settleUpgradeFeatures: updated already settled"
);
(bool success, uint256 resultIndex) = notaryHook.getUpgradeResult(
secret,
address(this)
);
UpgradeInfoV2 storage u = _upgradesInfoV2[commitment];
bool shouldBurn = true;
if (!success && u.useCharm) {
if (nft.mappingLuckyCharm(u.user) > 0) {
nft.decreaseCharm(u.user);
//returning NFTs back
nft.transferFrom(address(this), u.user, u.tokenIds[0]);
nft.transferFrom(address(this), u.user, u.tokenIds[1]);
nft.transferFrom(address(this), u.user, u.tokenIds[2]);
shouldBurn = false;
}
}
if (shouldBurn) {
//burning all input NFTs
for (uint256 i = 0; i < u.tokenIds.length; i++) {
//burn NFTs
nft.burn(u.tokenIds[i]);
}
}
uint256 tokenId = 0;
if (success) {
(
bytes[] memory _featureNames,
bytes[] memory _featureValues
) = nftStorageHook.getFeaturesByIndex(resultIndex);
tokenId = nft.mint(u.user, _featureNames, _featureValues);
if (u.useCharm) {
nft.decreaseCharm(u.user);
}
}
u.upgradeStatus = success;
u.settled = true;
emit UpgradeToken(u.user, u.tokenIds, success, u.useCharm, tokenId);
}
function settleAllRemainingCommitments(
bytes32[] memory _boxCommitments,
bytes32[] memory _upgradeCommitments
) public {
for (uint256 i = 0; i < _boxCommitments.length; i++) {
settleOpenBox(_boxCommitments[i]);
}
for (uint256 i = 0; i < _upgradeCommitments.length; i++) {
settleUpgradeFeatures(_upgradeCommitments[i]);
}
}
function setNotaryHook(address _notaryHook) external onlyOwner {
notaryHook = INotaryNFT(_notaryHook);
}
function setMasterChef(address _masterChef) external onlyOwner {
masterChefs[_masterChef] = true;
emit SetMasterChef(_masterChef, true);
}
function removeMasterChef(address _masterChef) external onlyOwner {
masterChefs[_masterChef] = false;
emit SetMasterChef(_masterChef, false);
}
function setOldFactory(address _old) external onlyOwner {
oldFactory = INFTFactory(_old);
}
function setFactoryV2(address _v2) external onlyOwner {
factoryV2 = INFTFactoryV2(_v2);
}
function setXDRACE(address _xdrace) external onlyOwner {
xDrace = IMint(_xdrace);
}
function setXDraceVesting(address _v) external onlyOwner {
xDraceVesting = IxDraceDistributor(_v);
}
function setDevFundPercent(uint256 _p) external onlyOwner {
devFundPercent = _p;
}
function addBoxReward(address addr, uint256 reward) external override {
require(
masterChefs[msg.sender],
"only masterchef can update box reward"
);
uint256 _toMint = reward;
if (!alreadyMinted[addr] && !factoryV2.alreadyMinted(addr)) {
_toMint = oldFactory.boxRewards(addr).add(_toMint);
alreadyMinted[addr] = true;
}
xDrace.mint(addr, _toMint);
//10% to ecosystem fund
xDrace.mint(feeTo, (_toMint * devFundPercent) / 100);
}
function boxRewards(address _addr)
external
view
override
returns (uint256)
{
if (!alreadyMinted[_addr]) {
if (!factoryV2.alreadyMinted(_addr)) {
return oldFactory.boxRewards(_addr);
}
}
return IERC20Upgradeable(0x2F7694695d71CAaaE29FDF3F140530d057de970B).balanceOf(_addr);
}
function getXDraceLockInfo(address _addr)
external
view
returns (uint256, uint256)
{
return xDraceVesting.getLockedInfo(_addr);
}
function decreaseBoxReward(address addr, uint256 reduced)
external
override
{
//do nothing
}
}
| in case server lose secret, it basically revoke box for user to open again | function revokeBoxId(uint256 boxId) external onlyOwner {
committedBoxes[boxId] = false;
}
| 13,108,425 |
./partial_match/1/0x2CAD12a04d4b3507341314678f177A06033309b2/sources/RMFToken.sol | See {IERC20-approve}. NOTE: If `value` 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 value)
public
virtual
returns (bool)
{
address owner = _msgSender();
_approve(owner, spender, value);
return true;
}
| 4,370,938 |
pragma solidity ^0.4.8;
contract LuckyDAO {
enum Environment {UNDEFINED, PROD, TEST}
Environment public environment;
struct Guess {
uint floor; // start of the guess window
uint ceil; // end of the guess window = floor + paid wei
}
struct Participation {
mapping(uint8 => Guess) guesses;
uint8 guessCount;
uint totalPaid;
}
event NewGuess(address participant, uint amount, uint totalPaid, uint floor, uint ceil);
event GameClosed(uint secret);
mapping (address => Participation) participations;
uint public secret;
uint public endTimeStamp;
address public redeemer;
/*a mapping of ETH balances for the aprticipants*/
mapping (uint => address) participants;
uint public nbParticipants;
/*the constructor expects an endDate in seconds NOT miliseconds from 1970*/
function LuckyDAO(uint _endTimeStamp, address _redeemer, Environment _environment) {
environment = _environment;
endTimeStamp = _endTimeStamp;
redeemer = _redeemer;
}
function setEndTimeStamp(uint _endTimeStamp) {
if (environment == Environment.TEST) {
endTimeStamp = _endTimeStamp;
}
}
function computeSecret(uint _secretNum, address _address) constant returns (bytes32) {
return sha3(_secretNum, _address);
}
function getParticipant(uint i) constant returns (address) {
return participants[i];
}
/*returns the percent to a 6 digit precision. must be divided by 1'000'000 to get a percentage*/
function winProbability(address _participant) constant returns (uint) {
return (participations[_participant].totalPaid * 1000000) / this.balance;
}
function getGuessCount(address _participant) constant returns(uint8) {
return participations[_participant].guessCount;
}
function getGuess(address _participant, uint8 i) constant returns(uint floor, uint ceil) {
Guess guess = participations[_participant].guesses[i];
return (guess.floor, guess.ceil);
}
function isWinner(address _participant) constant returns (bool) {
for (uint8 i = 0; i < participations[_participant].guessCount; i++) {
Guess guess = participations[_participant].guesses[i];
if (secret >= guess.floor && secret < guess.ceil) {
return true;
}
}
return false;
}
function redeem() returns (bool) {
if(secret != 0){
return redeemer.send(this.balance);
}
}
/*Fallback function for the contract. send ETH to the contract to register*/
function() payable {
if (secret == 0 && msg.value > 0) {
Participation participation = participations[msg.sender];
if (participation.guessCount == 0) {
participants[nbParticipants++] = msg.sender;
}
Guess guess = participation.guesses[participation.guessCount++];
guess.floor = this.balance - msg.value;
guess.ceil = this.balance;
participation.totalPaid += msg.value;
NewGuess(msg.sender, msg.value, participation.totalPaid, guess.floor, guess.ceil);
} else if (secret > 0 && msg.value > 0) {
bool sent = msg.sender.send(msg.value);
}
/*the last participant closes the competition even if the value is 0*/
if (block.timestamp > endTimeStamp && secret == 0) {
secret = uint(sha3(block.timestamp, block.blockhash(block.number)
, block.blockhash(block.number - 1)
, block.blockhash(block.number - 2)
, block.blockhash(block.number - 3)
, block.blockhash(block.number - 4))) % this.balance;
GameClosed(secret);
}
}
} | returns the percent to a 6 digit precision. must be divided by 1'000'000 to get a percentage/ | function winProbability(address _participant) constant returns (uint) {
return (participations[_participant].totalPaid * 1000000) / this.balance;
}
| 7,276,001 |
./partial_match/80001/0x636C4701Fdd1C46e47177cef7032b26402Bf7251/sources/minter1.sol | Returns the downcasted int72 from int256, reverting on overflow (when the input is less than smallest int72 or greater than largest int72). Counterpart to Solidity's `int72` operator. Requirements: - input must fit into 72 bits _Available since v4.7._/ | function toInt72(int256 value) internal pure returns (int72 downcasted) {
downcasted = int72(value);
require(downcasted == value, "SafeCast: value doesn't fit in 72 bits");
}
| 8,818,507 |
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.4.24;
/**
* @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: openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.4.24;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(
ERC20Basic _token,
address _to,
uint256 _value
)
internal
{
require(_token.transfer(_to, _value));
}
function safeTransferFrom(
ERC20 _token,
address _from,
address _to,
uint256 _value
)
internal
{
require(_token.transferFrom(_from, _to, _value));
}
function safeApprove(
ERC20 _token,
address _spender,
uint256 _value
)
internal
{
require(_token.approve(_spender, _value));
}
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.4.24;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
assert(_b <= _a);
return _a - _b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
c = _a + _b;
assert(c >= _a);
return c;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/BasicToken.sol
pragma solidity ^0.4.24;
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) internal balances;
uint256 internal totalSupply_;
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev Transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_value <= balances[msg.sender]);
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/StandardToken.sol
pragma solidity ^0.4.24;
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* https://github.com/ethereum/EIPs/issues/20
* Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint256 _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint256 _subtractedValue
)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/Burnable.sol
pragma solidity ^0.4.24;
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract Burnable is StandardToken {
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 {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// 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[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
// File: contracts/Ownable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable is Burnable {
address public owner;
address public ownerCandidate;
/**
* @dev Fired whenever ownership is successfully transferred.
*/
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a new owner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a new owner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
ownerCandidate = _newOwner;
}
/**
* @dev New ownerschip Confirmation.
*/
function acceptOwnership() public {
_acceptOwnership();
}
/**
* @dev New ownerschip confirmation internal.
*/
function _acceptOwnership() internal {
require(msg.sender == ownerCandidate);
emit OwnershipTransferred(owner, ownerCandidate);
owner = ownerCandidate;
ownerCandidate = address(0);
}
/**
* @dev Transfers the current balance to the owner and terminates the contract.
* In case stuff goes bad.
*/
function destroy() public onlyOwner {
selfdestruct(owner);
}
function destroyAndSend(address _recipient) public onlyOwner {
selfdestruct(_recipient);
}
}
// File: contracts/Administrable.sol
pragma solidity ^0.4.24;
/**
* @title Ownable
* @dev The authentication manager details user accounts that have access to certain priviledges.
*/
contract Administrable is Ownable {
using SafeERC20 for ERC20Basic;
/**
* @dev Map addresses to admins.
*/
mapping (address => bool) admins;
/**
* @dev All admins that have ever existed.
*/
address[] adminAudit;
/**
* @dev Globally enable or disable admin access.
*/
bool allowAdmins = true;
/**
* @dev Fired whenever an admin is added to the contract.
*/
event AdminAdded(address addedBy, address admin);
/**
* @dev Fired whenever an admin is removed from the contracts.
*/
event AdminRemoved(address removedBy, address admin);
/**
* @dev Throws if called by any account other than the active admin or owner.
*/
modifier onlyAdmin {
require(isCurrentAciveAdmin(msg.sender));
_;
}
/**
* @dev Turn on admin role
*/
function enableAdmins() public onlyOwner {
require(allowAdmins == false);
allowAdmins = true;
}
/**
* @dev Turn off admin role
*/
function disableAdmins() public onlyOwner {
require(allowAdmins);
allowAdmins = false;
}
/**
* @dev Gets whether or not the specified address is currently an admin.
*/
function isCurrentAdmin(address _address) public view returns (bool) {
if(_address == owner)
return true;
else
return admins[_address];
}
/**
* @dev Gets whether or not the specified address is currently an active admin.
*/
function isCurrentAciveAdmin(address _address) public view returns (bool) {
if(_address == owner)
return true;
else
return allowAdmins && admins[_address];
}
/**
* @dev Gets whether or not the specified address has ever been an admin.
*/
function isCurrentOrPastAdmin(address _address) public view returns (bool) {
for (uint256 i = 0; i < adminAudit.length; i++)
if (adminAudit[i] == _address)
return true;
return false;
}
/**
* @dev Adds a user to our list of admins.
*/
function addAdmin(address _address) public onlyOwner {
require(admins[_address] == false);
admins[_address] = true;
emit AdminAdded(msg.sender, _address);
adminAudit.length++;
adminAudit[adminAudit.length - 1] = _address;
}
/**
* @dev Removes a user from our list of admins but keeps them in the history.
*/
function removeAdmin(address _address) public onlyOwner {
require(_address != msg.sender);
require(admins[_address]);
admins[_address] = false;
emit AdminRemoved(msg.sender, _address);
}
/**
* @dev Reclaim all ERC20Basic compatible tokens
* @param _token ERC20Basic The address of the token contract
*/
function reclaimToken(ERC20Basic _token) external onlyAdmin {
uint256 balance = _token.balanceOf(this);
_token.safeTransfer(msg.sender, balance);
}
}
// File: contracts/Pausable.sol
pragma solidity ^0.4.24;
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Administrable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyAdmin whenNotPaused {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyAdmin whenPaused {
paused = false;
emit Unpause();
}
}
// File: contracts/Rento.sol
pragma solidity ^0.4.24;
contract Rento is Pausable {
using SafeMath for uint256;
string public name = "Rento";
string public symbol = "RTO";
uint8 public decimals = 8;
/**
* @dev representing 1.0.
*/
uint256 public constant UNIT = 100000000;
uint256 constant INITIAL_SUPPLY = 600000000 * UNIT;
uint256 constant SALE_SUPPLY = 264000000 * UNIT;
uint256 internal SALE_SENT = 0;
uint256 constant OWNER_SUPPLY = 305000000 * UNIT;
uint256 internal OWNER_SENT = 0;
uint256 constant BOUNTY_SUPPLY = 6000000 * UNIT;
uint256 internal BOUNTY_SENT = 0;
uint256 constant ADVISORS_SUPPLY = 25000000 * UNIT;
uint256 internal ADVISORS_SENT = 0;
struct Stage {
uint8 cents;
uint256 limit;
}
Stage[] stages;
/**
* @dev Stages prices in cents
*/
mapping(uint => uint256) rates;
constructor() public {
totalSupply_ = INITIAL_SUPPLY;
stages.push(Stage( 2, 0));
stages.push(Stage( 6, 26400000 * UNIT));
stages.push(Stage( 6, 52800000 * UNIT));
stages.push(Stage(12, 158400000 * UNIT));
stages.push(Stage(12, SALE_SUPPLY));
}
/**
* @dev Sell tokens to address based on USD cents value.
* @param _to Buyer address.
* @param _value USC cents value.
*/
function sellWithCents(address _to, uint256 _value) public
onlyAdmin whenNotPaused
returns (bool success) {
return _sellWithCents(_to, _value);
}
/**
* @dev Sell tokens to address array based on USD cents array values.
*/
function sellWithCentsArray(address[] _dests, uint256[] _values) public
onlyAdmin whenNotPaused
returns (bool success) {
require(_dests.length == _values.length);
for (uint32 i = 0; i < _dests.length; i++)
if(!_sellWithCents(_dests[i], _values[i])) {
revert();
return false;
}
return true;
}
/**
* @dev Sell tokens to address based on USD cents value.
* @param _to Buyer address.
* @param _value USC cents value.
*/
function _sellWithCents(address _to, uint256 _value) internal
onlyAdmin whenNotPaused
returns (bool) {
require(_to != address(0) && _value > 0);
uint256 tokens_left = 0;
uint256 tokens_right = 0;
uint256 price_left = 0;
uint256 price_right = 0;
uint256 tokens;
uint256 i_r = 0;
uint256 i = 0;
while (i < stages.length) {
if(SALE_SENT >= stages[i].limit) {
if(i == stages.length-1) {
i_r = i;
} else {
i_r = i + 1;
}
price_left = uint(stages[i].cents);
price_right = uint(stages[i_r].cents);
}
i += 1;
}
if(price_left <= 0) {
revert();
return false;
}
tokens_left = _value.mul(UNIT).div(price_left);
if(SALE_SENT.add(tokens_left) <= stages[i_r].limit) {
tokens = tokens_left;
} else {
tokens_left = stages[i_r].limit.sub(SALE_SENT);
tokens_right = UNIT.mul(_value.sub((tokens_left.mul(price_left)).div(UNIT))).div(price_right);
}
tokens = tokens_left.add(tokens_right);
if(SALE_SENT.add(tokens) > SALE_SUPPLY) {
revert();
return false;
}
balances[_to] = balances[_to].add(tokens);
SALE_SENT = SALE_SENT.add(tokens);
emit Transfer(this, _to, tokens);
return true;
}
/**
* @dev Transfer tokens from contract directy to address.
* @param _to Buyer address.
* @param _value Tokens value.
*/
function sellDirect(address _to, uint256 _value) public
onlyAdmin whenNotPaused
returns (bool success) {
require(_to != address(0) && _value > 0 && SALE_SENT.add(_value) <= SALE_SUPPLY);
balances[_to] = balances[_to].add(_value);
SALE_SENT = SALE_SENT.add(_value);
emit Transfer(this, _to, _value);
return true;
}
/**
* @dev Sell tokens to address array based on USD cents array values.
*/
function sellDirectArray(address[] _dests, uint256[] _values) public
onlyAdmin whenNotPaused returns (bool success) {
require(_dests.length == _values.length);
for (uint32 i = 0; i < _dests.length; i++) {
if(_values[i] <= 0 || !sellDirect(_dests[i], _values[i])) {
revert();
return false;
}
}
return true;
}
/**
* @dev Transfer tokens from contract directy to owner.
* @param _value Tokens value.
*/
function transferOwnerTokens(uint256 _value) public
onlyAdmin whenNotPaused returns (bool success) {
require(_value > 0 && OWNER_SENT.add(_value) <= OWNER_SUPPLY);
balances[owner] = balances[owner].add(_value);
OWNER_SENT = OWNER_SENT.add(_value);
emit Transfer(this, owner, _value);
return true;
}
/**
* @dev Transfer Bounty Tokens from contract.
* @param _to Bounty recipient address.
* @param _value Tokens value.
*/
function transferBountyTokens(address _to, uint256 _value) public
onlyAdmin whenNotPaused returns (bool success) {
require(_to != address(0) && _value > 0 && BOUNTY_SENT.add(_value) <= BOUNTY_SUPPLY);
balances[_to] = balances[_to].add(_value);
BOUNTY_SENT = BOUNTY_SENT.add(_value);
emit Transfer(this, _to, _value);
return true;
}
/**
* @dev Transfer Bounty Tokens from contract to multiple recipients ant once.
* @param _to Bounty recipient addresses.
* @param _values Tokens values.
*/
function transferBountyTokensArray(address[] _to, uint256[] _values) public
onlyAdmin whenNotPaused returns (bool success) {
require(_to.length == _values.length);
for (uint32 i = 0; i < _to.length; i++)
if(!transferBountyTokens(_to[i], _values[i])) {
revert();
return false;
}
return true;
}
/**
* @dev Transfer Advisors Tokens from contract.
* @param _to Advisors recipient address.
* @param _value Tokens value.
*/
function transferAdvisorsTokens(address _to, uint256 _value) public
onlyAdmin whenNotPaused returns (bool success) {
require(_to != address(0) && _value > 0 && ADVISORS_SENT.add(_value) <= ADVISORS_SUPPLY);
balances[_to] = balances[_to].add(_value);
ADVISORS_SENT = ADVISORS_SENT.add(_value);
emit Transfer(this, _to, _value);
return true;
}
/**
* @dev Transfer Advisors Tokens from contract for multiple advisors.
* @param _to Advisors recipient addresses.
* @param _values Tokens valuees.
*/
function transferAdvisorsTokensArray(address[] _to, uint256[] _values) public
onlyAdmin whenNotPaused returns (bool success) {
require(_to.length == _values.length);
for (uint32 i = 0; i < _to.length; i++)
if(!transferAdvisorsTokens(_to[i], _values[i])) {
revert();
return false;
}
return true;
}
/**
* @dev Current Sale states methods.
*/
function soldTokensSent() external view returns (uint256) {
return SALE_SENT;
}
function soldTokensAvailable() external view returns (uint256) {
return SALE_SUPPLY.sub(SALE_SENT);
}
function ownerTokensSent() external view returns (uint256) {
return OWNER_SENT;
}
function ownerTokensAvailable() external view returns (uint256) {
return OWNER_SUPPLY.sub(OWNER_SENT);
}
function bountyTokensSent() external view returns (uint256) {
return BOUNTY_SENT;
}
function bountyTokensAvailable() external view returns (uint256) {
return BOUNTY_SUPPLY.sub(BOUNTY_SENT);
}
function advisorsTokensSent() external view returns (uint256) {
return ADVISORS_SENT;
}
function advisorsTokensAvailable() external view returns (uint256) {
return ADVISORS_SUPPLY.sub(ADVISORS_SENT);
}
/**
* @dev Transfer tokens from msg.sender account directy to address array with values array.
* param _dests recipients.
* @param _values Tokens values.
*/
function transferArray(address[] _dests, uint256[] _values) public returns (bool success) {
require(_dests.length == _values.length);
for (uint32 i = 0; i < _dests.length; i++) {
if(_values[i] > balances[msg.sender] || msg.sender == _dests[i] || _dests[i] == address(0)) {
revert();
return false;
}
balances[msg.sender] = balances[msg.sender].sub(_values[i]);
balances[_dests[i]] = balances[_dests[i]].add(_values[i]);
emit Transfer(msg.sender, _dests[i], _values[i]);
}
return true;
}
} | Sell tokens to address array based on USD cents array values./ | function sellDirectArray(address[] _dests, uint256[] _values) public
onlyAdmin whenNotPaused returns (bool success) {
require(_dests.length == _values.length);
for (uint32 i = 0; i < _dests.length; i++) {
if(_values[i] <= 0 || !sellDirect(_dests[i], _values[i])) {
revert();
return false;
}
}
return true;
}
| 15,798,352 |
./full_match/80001/0x268023DD238B747756eb6CF2f189aE4bA11702E5/sources/_thirdweb-dev/contracts/extension/Drop.sol | Lets an account claim tokens. Update contract state. If there's a price, collect price. Mint the relevant tokens to claimer. | function claim(
address _receiver,
uint256 _quantity,
address _currency,
uint256 _pricePerToken,
uint256 activeConditionId,
AllowlistProof calldata _allowlistProof,
bytes memory _data
) public payable virtual override {
_beforeClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data);
verifyClaim(activeConditionId, _dropMsgSender(), _quantity, _currency, _pricePerToken, _allowlistProof);
claimCondition.conditions[activeConditionId].supplyClaimed += _quantity;
claimCondition.supplyClaimedByWallet[activeConditionId][_dropMsgSender()] += _quantity;
_collectPriceOnClaim(address(0), _quantity, _currency, _pricePerToken);
uint256 startTokenId = _transferTokensOnClaim(_receiver, _quantity);
emit TokensClaimed(activeConditionId, _dropMsgSender(), _receiver, startTokenId, _quantity);
_afterClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data);
}
| 5,574,731 |
pragma solidity ^0.5.10;
import {TypedMemView} from "./TypedMemView.sol";
import {SafeMath} from "./SafeMath.sol";
library ViewCKB {
using TypedMemView for bytes29;
using SafeMath for uint;
uint256 public constant PERIOD_BLOCKS = 24 * 450 * 7; // 1 week in blocks
uint8 public constant NUMBER_SIZE = 4; // Size of Number in ckb molecule
uint64 public constant NUMBER_MASK = 16777215;
enum CKBTypes {
Unknown, // 0x0
Script, // 0x1
Outpoint,
CellInput,
CellOutput,
Bytes,
H256,
H160,
Header,
Nonce,
RawHeader,
Version,
CompactTarget,
Timestamp,
BlockNumber,
Epoch,
ParentHash,
TransactionsRoot,
UnclesHash,
HeaderVec,
Transaction
}
/// @notice requires `memView` to be of a specified type
/// @param memView a 29-byte view with a 5-byte type
/// @param t the expected type (e.g. CKBTypes.Outpoint, CKBTypes.Script, etc)
/// @return passes if it is the correct type, errors if not
modifier typeAssert(bytes29 memView, CKBTypes t) {
memView.assertType(uint40(t));
_;
}
/// @notice extracts the since as an integer from a CellInput
/// @param _input the CellInput
/// @return the since
function since(bytes29 _input) internal pure typeAssert(_input, CKBTypes.CellInput) returns (uint64) {
return uint64(_input.indexLEUint(0, 8));
}
/// @notice extracts the outpoint from a CellInput
/// @param _input the CellInput
/// @return the outpoint as a typed memory
function previousOutput(bytes29 _input) internal pure typeAssert(_input, CKBTypes.CellInput) returns (bytes29) {
return _input.slice(8, 36, uint40(CKBTypes.Outpoint));
}
/// @notice extracts the codeHash from a Script
/// @param _input the Script
/// @return the codeHash
function codeHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (bytes32) {
uint256 startIndex = _input.indexLEUint(4, 4);
return _input.index(startIndex, 32);
}
/// @notice extracts the hashType from a Script
/// @param _input the Script
/// @return the hashType
function hashType(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (uint8) {
uint256 startIndex = _input.indexLEUint(8, 4);
return uint8(_input.indexUint(startIndex, 1));
}
/// @notice extracts the args from a Script
/// @param _input the Script
/// @return the args
function args(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Script) returns (bytes29) {
uint256 startIndex = _input.indexLEUint(12, 4) + NUMBER_SIZE;
uint256 inputLength = _input.len();
return _input.slice(startIndex, inputLength - startIndex, uint40(CKBTypes.Bytes));
}
/// @notice extracts the rawHeader from a Header
/// @param _input the Header
/// @return the rawHeader as a typed memory
function rawHeader(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Header) returns (bytes29) {
return _input.slice(0, 192, uint40(CKBTypes.RawHeader));
}
/// @notice extracts the nonce from a Header
/// @param _input the Header
/// @return the nonce
function nonce(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Header) returns (uint128) {
return uint128(_input.indexLEUint(192, 16));
}
/// @notice extracts the version from a RawHeader
/// @param _input the RawHeader
/// @return the version
function version(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint32) {
return uint32(_input.indexLEUint(0, 4));
}
/// @notice extracts the compactTarget from a RawHeader
/// @param _input the RawHeader
/// @return the compactTarget
function compactTarget(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint32) {
return uint32(_input.indexLEUint(4, 4));
}
/// @notice extracts the timestamp from a RawHeader
/// @param _input the RawHeader
/// @return the timestamp
function timestamp(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) {
return uint64(_input.indexLEUint(8, 8));
}
/// @notice extracts the blockNumber from a RawHeader
/// @param _input the RawHeader
/// @return the blockNumber
function blockNumber(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) {
return uint64(_input.indexLEUint(16, 8));
}
/// @notice extracts the epoch from a RawHeader
/// @param _input the RawHeader
/// @return the epoch
function epoch(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (uint64) {
return uint64(_input.indexLEUint(24, 8)) & NUMBER_MASK;
}
/// @notice extracts the parentHash from a RawHeader
/// @param _input the RawHeader
/// @return the parentHash
function parentHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) {
return _input.index(32, 32);
}
/// @notice extracts the transactionsRoot from a RawHeader
/// @param _input the RawHeader
/// @return the transactionsRoot
function transactionsRoot(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) {
return _input.index(64, 32);
}
/// @notice extracts the unclesHash from a RawHeader
/// @param _input the RawHeader
/// @return the unclesHash
function unclesHash(bytes29 _input) internal pure typeAssert(_input, CKBTypes.RawHeader) returns (bytes32) {
return _input.index(128, 32);
}
/// @notice Index a header vector.
/// @dev Errors on overruns
/// @param _headers The header vector
/// @param index The 0-indexed location of the header to get
/// @return the typed header at `index`
function indexHeaderVec(bytes29 _headers, uint256 index) internal pure typeAssert(_headers, CKBTypes.HeaderVec) returns (bytes29) {
uint256 _start = 4 + index.mul(208);
return _headers.slice(_start, 208, uint40(CKBTypes.Header));
}
/// @notice return length of a header vector.
/// @dev Errors on overruns
/// @param _headers The header vector
/// @return the length of a header vector.
function lengthHeaderVec(bytes29 _headers) internal pure typeAssert(_headers, CKBTypes.HeaderVec) returns (uint32) {
return uint32(_headers.indexLEUint(0, 4));
}
}
| extracts the rawHeader from a Header _input the Header return the rawHeader as a typed memory | function rawHeader(bytes29 _input) internal pure typeAssert(_input, CKBTypes.Header) returns (bytes29) {
return _input.slice(0, 192, uint40(CKBTypes.RawHeader));
}
| 905,512 |
./full_match/1/0x39Ac1AC1B7c45b3E78f1290a542D428E7aB8E59C/sources/browser/XTrinity_flat.sol | helper to identify if we work with ETH or WETH/ | function isofETH(IERC20 token) internal pure returns (bool) {
return (address(token) == address(ZERO_ADDRESS) ||
address(token) == address(ETH_ADDRESS) ||
address(token) == address(WETH_ADDRESS));
}
| 4,980,475 |
pragma solidity ^0.4.24;
import "zos-lib/contracts/Initializable.sol";
import "./ERC20Detailed.sol";
import "./ERC20Mintable.sol";
import "./ERC20Pausable.sol";
/**
* @title Standard ERC20 token, with minting and pause functionality.
*
*/
contract StandaloneERC20 is Initializable, ERC20Detailed, ERC20Mintable, ERC20Pausable {
function initialize(
string name, string symbol, uint8 decimals, uint256 initialSupply, address initialHolder,
address[] minters, address[] pausers
) public initializer {
require(initialSupply > 0);
ERC20Detailed.initialize(name, symbol, decimals);
// Mint the initial supply
_mint(initialHolder, initialSupply);
// Initialize the minter and pauser roles, and renounce them
ERC20Mintable.initialize(address(this));
renounceMinter();
ERC20Pausable.initialize(address(this));
renouncePauser();
// Add the requested minters and pausers (this can be done after renouncing since
// these are the internal calls)
for (uint256 i = 0; i < minters.length; ++i) {
_addMinter(minters[i]);
}
for (i = 0; i < pausers.length; ++i) {
_addPauser(pausers[i]);
}
}
function initialize(
string name, string symbol, uint8 decimals, address[] minters, address[] pausers
) public initializer {
ERC20Detailed.initialize(name, symbol, decimals);
// Initialize the minter and pauser roles, and renounce them
ERC20Mintable.initialize(address(this));
renounceMinter();
ERC20Pausable.initialize(address(this));
renouncePauser();
// Add the requested minters and pausers (this can be done after renouncing since
// these are the internal calls)
for (uint256 i = 0; i < minters.length; ++i) {
_addMinter(minters[i]);
}
for (i = 0; i < pausers.length; ++i) {
_addPauser(pausers[i]);
}
}
}
| Initialize the minter and pauser roles, and renounce them Add the requested minters and pausers (this can be done after renouncing since these are the internal calls) | function initialize(
string name, string symbol, uint8 decimals, address[] minters, address[] pausers
) public initializer {
ERC20Detailed.initialize(name, symbol, decimals);
ERC20Mintable.initialize(address(this));
renounceMinter();
ERC20Pausable.initialize(address(this));
renouncePauser();
for (uint256 i = 0; i < minters.length; ++i) {
_addMinter(minters[i]);
}
for (i = 0; i < pausers.length; ++i) {
_addPauser(pausers[i]);
}
}
| 12,878,209 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./SigToken.sol";
/**
* @title FeeAdminV1DutchAuction
* @notice Sells admin fees from xsigma3pool for SigToken and burns it.
* Sell happens via Dutch Auction periodically from highest price to lowest one.
* Owner can change the auction settings.
*/
contract PeriodicDutchAuction is Ownable {
using SafeMath for uint256;
SigToken public sigToken;
address[] public coins;
/*
the price of the auction works like this:
from the block {startBlock} every {term} any of {coins} avaliable on balance
can be bought by Sig token using current sigPrice(currBlock).
the price(t) == a*t + b every term,
i.e. t = (currBlock - startBlock) % term,
so the highest price is b, and the lowest price is b - a*term
*/
uint256 public startBlock = 1e18; // INF at the beginning
uint256 public periodBlocks;
uint256 public a;
uint256 public b;
event SetSettings(
uint256 _startBlock,
uint256 _auctionPeriodBlocks,
uint256 _lowestSig1e18Price,
uint256 _highestSig1e18Price
);
event Bought(
address msg_sender,
uint256 sellSigAmount,
uint256 buyTokenId,
uint256 minBuyAmount,
uint256 outputAmount
);
constructor(
SigToken _sigToken,
address[3] memory _coins
) public {
sigToken = _sigToken;
for (uint256 i = 0; i < 3; i++) {
require(_coins[i] != address(0));
coins.push(_coins[i]);
}
}
/**
* @notice Set parameters for Dutch Auction as SigToken price.
* @param _startBlock - before this block number getPriceSig which revert
* @param _auctionPeriodBlocks - auction will happens every _term blocks from _startBlock
* @param _lowestSig1e18Price - start lowest price of Sig in usd,
* so if you want to start from 1 SigToken == 0.01 DAI,
* it should be 0.01*1e18.
* All stablecoins in the pool are considered worth of $1.
* @param _highestSig1e18Price - the last/highest SIG price on the auction
*/
function setAuctionSettings(
uint256 _startBlock,
uint256 _auctionPeriodBlocks,
uint256 _lowestSig1e18Price,
uint256 _highestSig1e18Price
) public onlyOwner {
startBlock = _startBlock;
periodBlocks = _auctionPeriodBlocks;
b = _lowestSig1e18Price;
a = _highestSig1e18Price.sub(_lowestSig1e18Price).div(periodBlocks.sub(1));
emit SetSettings(_startBlock, _auctionPeriodBlocks, _lowestSig1e18Price, _highestSig1e18Price);
}
/**
* @notice price for SIG token in USD * 1e18 at currBlock
*/
function getSig1e18Price(uint256 currBlock, uint256 tokenId) public view returns (uint256) {
require(startBlock <= currBlock, "Auction hasn't started yet");
uint256 t = (currBlock - startBlock) % periodBlocks;
uint256 price;
if (tokenId == 0) {
// i = 0 => DAI with 1e18 precision
price = b.add(a.mul(t));
} else {
// i = 1 || 2, => USDC/USDT with 1e6 precision
price = b.add(a.mul(t)).div(1e12);
}
return price;
}
/**
* @notice Try to exchange SIG token for one of stablecoins
* @param sellSigAmount - amount of SigToken
* @param buyTokenId - number of stablecoins, by default 0,1 or 2 for DAI, USDC or USDT
* @param buyAtLeastAmount - if there's not enough balance, buy at least specified amount of stablecoin
* if it's 0 - transaction will be reverted if there's no enough coins
*/
function sellSigForStablecoin(uint256 sellSigAmount, uint256 buyTokenId, uint256 buyAtLeastAmount) public {
// how much stablecoins should we give
uint256 sig1e18Price = getSig1e18Price(block.number, buyTokenId);
uint256 outputAmount = sellSigAmount.mul(sig1e18Price).div(1e18);
// maybe the contract has less stablecoins, but it's still enough to satisfy user request
if (IERC20(coins[buyTokenId]).balanceOf(address(this)) < outputAmount) {
//
if (buyAtLeastAmount == 0) {
revert("not enough stablecoins to buy");
}
// trying to buy as much as we can for current price
sellSigAmount = buyAtLeastAmount.mul(1e18).div(sig1e18Price);
outputAmount = buyAtLeastAmount;
}
// take Sig and burn
sigToken.burnFrom(msg.sender, sellSigAmount);
// return fee token
IERC20(coins[buyTokenId]).transfer(msg.sender, outputAmount);
emit Bought(msg.sender, sellSigAmount, buyTokenId, buyAtLeastAmount, outputAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
// SushiToken with Governance.
contract SigToken is ERC20, Ownable, ERC20Burnable {
using SafeMath for uint256;
// Bitcoin-like supply system:
// 50 tokens per block (however it's Ethereum ~15 seconds block vs Bitcoin 10 minutes)
// every 210,000 blocks is halving ~ 36 days 11 hours
// 32 eras ~ 3 years 71 days 16 hours until complete mint
// 21,000,000 is total supply
//
// i,e. if each block is about 15 seconds on average:
// 40,320 blocks/week
// 2,016,000 tokens/week before first halving
// 10,500,000 total before first halving
//
uint256 constant MAX_MAIN_SUPPLY = 21_000_000 * 1e18;
// the first week mint has x2 bonus = +2,016,000
// the second week mint has x1.5 bonus = +1,008,000
//
uint256 constant BONUS_SUPPLY = 3_024_000 * 1e18;
// so total max supply is 24,024,000 + 24 to init the uniswap pool
uint256 constant MAX_TOTAL_SUPPLY = MAX_MAIN_SUPPLY + BONUS_SUPPLY;
// The block number when SIG mining starts.
uint256 public startBlock;
uint256 constant DECIMALS_MUL = 1e18;
uint256 constant BLOCKS_PER_WEEK = 40_320;
uint256 constant HALVING_BLOCKS = 210_000;
// uint265 constant INITIAL_BLOCK_REWARD = 50;
function maxRewardMintAfterBlocks(uint256 t) public pure returns (uint256) {
// the first week x2 mint
if (t < BLOCKS_PER_WEEK) {
return DECIMALS_MUL * 100 * t;
}
// second week x1.5 mint
if (t < BLOCKS_PER_WEEK * 2) {
return DECIMALS_MUL * (100 * BLOCKS_PER_WEEK + 75 * (t - BLOCKS_PER_WEEK));
}
// after two weeks standard bitcoin issuance model https://en.bitcoin.it/wiki/Controlled_supply
uint256 totalBonus = DECIMALS_MUL * (BLOCKS_PER_WEEK * 50 + BLOCKS_PER_WEEK * 25);
assert(totalBonus >= 0);
// how many halvings so far?
uint256 era = t / HALVING_BLOCKS;
assert(0 <= era);
if (32 <= era) return MAX_TOTAL_SUPPLY;
// total reward before current era (mul base reward 50)
// sum : 1 + 1/2 + 1/4 … 1/2^n == 2 - 1/2^n == 1 - 1/1<<n == 1 - 1>>n
// era reward per block (*1e18 *50)
if (era == 0) {
return totalBonus + DECIMALS_MUL* 50 * (t % HALVING_BLOCKS);
}
uint256 eraRewardPerBlock = (DECIMALS_MUL >> era);
// assert(0 <= eraRewardPerBlock);
uint256 bcReward = (DECIMALS_MUL + DECIMALS_MUL - (eraRewardPerBlock<<1) ) * 50 * HALVING_BLOCKS;
// assert(0 <= bcReward);
// reward in the last era which isn't over
uint256 eraReward = eraRewardPerBlock * 50 * (t % HALVING_BLOCKS);
// assert(0 <= eraReward);
uint256 result = totalBonus + bcReward + eraReward;
assert(0 <= result);
return result;
}
constructor(
uint256 _tinyMint
) public ERC20("xSigma", "SIG") {
// dev needs a little of SIG tokens for uniswap SIG/ETH initialization
_mint(msg.sender, _tinyMint);
}
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping (address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator) external view returns (address) {
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "SIG::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "SIG::delegateBySig: invalid nonce");
require(now <= expiry, "SIG::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint256) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) external view returns (uint256) {
require(blockNumber < block.number, "SIG::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying SIGs (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes) internal {
uint32 blockNumber = safe32(block.number, "SIG::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's 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;
import "../../GSN/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 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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
abstract contract ERC20Burnable is Context, ERC20 {
using SafeMath for uint256;
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public virtual {
_burn(_msgSender(), amount);
}
/**
* @dev Destroys `amount` tokens from `account`, deducting from the caller's
* allowance.
*
* See {ERC20-_burn} and {ERC20-allowance}.
*
* Requirements:
*
* - the caller must have allowance for ``accounts``'s tokens of at least
* `amount`.
*/
function burnFrom(address account, uint256 amount) public virtual {
uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance");
_approve(account, _msgSender(), decreasedAllowance);
_burn(account, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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);
} | the first week x2 mint second week x1.5 mint total reward before current era (mul base reward 50) sum : 1 + 1/2 + 1/4 … 1/2^n == 2 - 1/2^n == 1 - 1/1<<n == 1 - 1>>n era reward per block (1e18 50) | function maxRewardMintAfterBlocks(uint256 t) public pure returns (uint256) {
if (t < BLOCKS_PER_WEEK) {
return DECIMALS_MUL * 100 * t;
}
if (t < BLOCKS_PER_WEEK * 2) {
return DECIMALS_MUL * (100 * BLOCKS_PER_WEEK + 75 * (t - BLOCKS_PER_WEEK));
}
assert(totalBonus >= 0);
assert(0 <= era);
if (32 <= era) return MAX_TOTAL_SUPPLY;
if (era == 0) {
return totalBonus + DECIMALS_MUL* 50 * (t % HALVING_BLOCKS);
}
uint256 eraRewardPerBlock = (DECIMALS_MUL >> era);
assert(0 <= result);
return result;
}
constructor(
uint256 _tinyMint
| 573,107 |
./full_match/4/0xA155EAaF67122C82a61f9f017B2CA721cB20B0A8/sources/contracts/UpbondNFTMintableCreator.sol | Get edition given the created ID editionId id of edition to get contract for return UpbondNFTMintable Edition NFT contract | function getEditionAtId(uint256 editionId)
external
view
returns (UpbondNFTMintable)
{
return
UpbondNFTMintable(
ClonesUpgradeable.predictDeterministicAddress(
implementation,
bytes32(abi.encodePacked(editionId)),
address(this)
)
);
}
uint256 indexed editionId,
address indexed creator,
uint256 seriesSize,
address editionContractAddress
);
| 790,784 |
pragma solidity >=0.4.25;
import "../node_modules/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
// Flight status codees
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
struct Flight {
bool isRegistered;
uint8 statusCode;
uint256 updatedTimestamp;
address airline;
}
enum PolicyStatus {
Inforce,
Paid,
Expired
}
struct InsurancePolicy{
address passenger;
uint256 amount;
PolicyStatus status;
}
mapping(bytes32 => Flight) private flights;
mapping (address => uint256) private registeredAirlines;
mapping (address => uint256) private balances;
mapping (address => uint256) private authorizedContracts;
mapping (bytes32 => InsurancePolicy[]) private insurancePolicies;
address[] airlines;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor
(
)
public
{
contractOwner = msg.sender;
}
/********************************************************************************************/
/* 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 requireIsOperational()
{
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 requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
modifier requireRegisteredAirline(address caller){
require(registeredAirlines[caller] != 0, "Caller must be a registered airline.");
_;
}
modifier requireIsCallerAuthorized(){
require(authorizedContracts[msg.sender] == 1, "Caller is not an authorized contract.");
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational()
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
requireContractOwner
{
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
function authorizeCaller
(
address contractAddress
)
external
requireContractOwner
{
authorizedContracts[contractAddress] = 1;
}
function deauthorizeCaller
(
address contractAddress
)
external
requireContractOwner
{
delete authorizedContracts[contractAddress];
}
/**
* @dev Add an airline to the registration queue
* Can only be called from FlightSuretyApp contract
*
*/
function registerAirline
(
address airline
)
public
requireIsCallerAuthorized
{
airlines.push(airline);
registeredAirlines[airline] = 1;
}
function registerFlight
(
address airline,
string flight,
uint256 timestamp
)
external
requireIsCallerAuthorized
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
flights[flightKey] = Flight({
isRegistered: true,
statusCode: STATUS_CODE_UNKNOWN,
updatedTimestamp: now,
airline: airline
});
}
function isAirlineRegistered(address airline)
external view
returns(bool registered, uint256 fundRemained)
{
return (registeredAirlines[airline] != 0, balances[airline]);
}
function isFlightRegistered(
address airline, string flight, uint256 timestamp
)
external view
returns(bool registered)
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return flights[flightKey].isRegistered == true;
}
function getRegisteredAirlinesCount() external view returns(uint256){
return airlines.length;
}
function getPassengerIssuredAmount(address airline, string flight, uint256 timestamp,
address passenger ) external view returns(uint256){
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
InsurancePolicy[] storage policies = insurancePolicies[flightKey];
for(uint256 i=0; i<policies.length; ++i){
if(policies[i].passenger == passenger){
return policies[i].amount;
}
}
return 0;
}
function getFlightStatus(address airline, string flight, uint256 timestamp) external view returns(uint8){
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
return flights[flightKey].statusCode;
}
/**
* @dev Buy insurance for a flight
*
*/
function buy
(
address airline, string flight, uint256 timestamp,
address passenger,
uint256 value
)
external
payable
requireIsCallerAuthorized
{
require(registeredAirlines[passenger] == 0, "Passenger cannot be registered airline.");
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
require(flights[flightKey].isRegistered, "Flight has not registered");
Flight storage flightInfo = flights[flightKey];
require(flightInfo.statusCode == STATUS_CODE_UNKNOWN, "Flight has already taken off.");
insurancePolicies[flightKey].push(InsurancePolicy({
passenger: passenger,
amount: value,
status: PolicyStatus.Inforce
}));
}
/**
* @dev Credits payouts to insurees
*/
function creditInsurees
(
address airline, string flight, uint256 timestamp,
uint256 numerator, uint256 denominator
)
external
requireIsCallerAuthorized()
{
bytes32 flightKey = getFlightKey(airline, flight, timestamp);
for(uint i=0; i<insurancePolicies[flightKey].length; ++i){
address passenger = insurancePolicies[flightKey][i].passenger;
uint256 amount = insurancePolicies[flightKey][i].amount;
PolicyStatus status = insurancePolicies[flightKey][i].status;
if(status == PolicyStatus.Inforce){
uint256 payoutValue = 0;
if (numerator != 0){
payoutValue = amount * numerator / denominator;
}
if(payoutValue > 0){
insurancePolicies[flightKey][i].status = PolicyStatus.Paid;
uint256 finalAmount = balances[passenger] + payoutValue;
balances[passenger] = finalAmount;
}
else{
insurancePolicies[flightKey][i].status = PolicyStatus.Expired;
}
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
*/
function pay
(
address passenger,
uint256 amount
)
external
requireIsCallerAuthorized
returns(uint256)
{
//Check
require(balances[passenger] >= amount, "Insufficient credit.");
require(address(this).balance >= amount, "Contract does not have enough ether to make the payment.");
uint256 val = balances[passenger] - amount;
//Effect
balances[passenger] = val;
//Interaction
passenger.transfer(amount);
return val;
}
function getExistingAirlines() external view returns(address[]){
return airlines;
}
function getBalance(address entity) external view returns(uint256){
return balances[entity];
}
function AirlineFunding(
address airline,
uint amount
)
external
requireIsCallerAuthorized
{
balances[airline] += amount;
}
/**
* @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
(
)
public
payable
{
}
function getFlightKey
(
address airline,
string memory flight,
uint256 timestamp
)
pure
internal
returns(bytes32)
{
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function()
external
payable
{
//require(msg.data.length == 0, "Prevent attack.");
fund();
}
}
| Add an airline to the registration queue Can only be called from FlightSuretyApp contract/ | function registerAirline
(
address airline
)
public
requireIsCallerAuthorized
{
airlines.push(airline);
registeredAirlines[airline] = 1;
}
| 13,088,573 |
./full_match/80001/0x5d085dE8Df8C88cFE4B13B2f2DBDa92DD6cDF4e6/sources/contracts/Rentables.sol | Make the token available to be soldOnly Landlord can set the key if Token has expired | function makeAvailable(
uint256 from,
uint256 tenantId,
string memory key
) public virtual {
_existing(from);
_existing(tenantId);
require(hasTenant(from, tenantId), "Tenant not found");
Storage storage s = getStorage();
uint256 landlord = s.tokens[tenantId].landlord;
require(determineOwner(landlord, false) == msg.sender, "Not Allowed");
s.offerKey[tenantId] = key;
s.tenantByKey[key] = tenantId;
_safeTransferFrom(
determineOwner(tenantId, true),
address(this),
tenantId
);
}
| 9,523,462 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.8.10;
import "./IERC20.sol";
import "./IUniswapV2Router02.sol";
import "./IUniswapV2Factory.sol";
import "./IUniswapV2Pair.sol";
import "./IHyperDeFi.sol";
import "./IHyperDeFiBuffer.sol";
import "./IHyperDeFiIDO.sol";
import "./Ownable.sol";
import "./Math.sol";
import "./HyperDeFiTokenMetadata.sol";
/**
* @dev DeFi Token
*/
contract HyperDeFiToken is Ownable, IHyperDeFi, HyperDeFiTokenMetadata {
using Math for uint256;
struct Percentage {
uint8 farm;
uint8 airdrop;
uint8 fomo;
uint8 liquidity;
uint8 fund;
uint8 destroy;
}
struct Snap {
uint256 totalSupply;
uint256 totalTax;
}
bool private _swapLock;
uint256 internal _totalSupply;
uint256 internal _distributed;
uint256 internal _totalFarm;
uint256 internal _totalUsername;
uint256 internal _fomoTimestamp;
address[] internal _flats;
address[] internal _slots;
address[] internal _funds;
address[] internal _holders;
// Resources
IHyperDeFiIDO internal constant IDO = IHyperDeFiIDO(ADDRESS_IDO);
IHyperDeFiBuffer internal constant BUFFER = IHyperDeFiBuffer(ADDRESS_BUFFER);
IUniswapV2Router02 internal constant DEX = IUniswapV2Router02(ADDRESS_DEX);
IUniswapV2Factory internal immutable DEX_FACTORY;
IUniswapV2Pair internal immutable DEX_PAIR;
IERC20 internal immutable WRAP;
//
uint256 internal _initPrice;
uint256 internal _timestampLiquidityCreated;
address internal _fomoNextAccount;
// tax
Percentage internal TAKER_TAX = Percentage(3, 1, 2, 5, 1, 3);
Percentage internal MAKER_TAX = Percentage(3, 1, 1, 4, 1, 0);
Percentage internal WHALE_TAX = Percentage(3, 1, 1, 5, 1, 19);
Percentage internal ROBBER_TAX = Percentage(3, 1, 1, 5, 1, 74);
mapping (address => uint256) internal _balance;
mapping (address => uint256) internal _totalHarvest;
mapping (address => uint256) internal _totalFarmSnap;
mapping (address => string) internal _username;
mapping (address => bool) internal _usernamed;
mapping (string => address) internal _username2address;
mapping (address => uint256) internal _coupon;
mapping (uint256 => address) internal _inviter;
mapping (address => uint256) internal _couponUsed;
mapping (address => uint256) internal _visitors;
mapping (address => bool) internal _isFlat;
mapping (address => bool) internal _isSlot;
mapping (address => bool) internal _isFund;
mapping (address => bool) internal _isHolder;
mapping (address => mapping (address => uint256)) internal _allowances;
// enum
enum TX_TYPE {MINT, HARVEST, FLAT, TAKER, MAKER, WHALE, ROBBER}
// events
event TX(uint8 indexed txType, address indexed sender, address indexed recipient, uint256 amount, uint256 txAmount);
event SlotRegistered(address account);
event UsernameSet(address indexed account, string username);
event CouponVisitor(address inviter, address visitor);
event Airdrop(address indexed account, uint256 amount);
event Bonus(address indexed account, uint256 amount);
event Fund(address indexed account, uint256 amount);
//
modifier withSwapLock {
_swapLock = true;
_;
_swapLock = false;
}
//
constructor () {
WRAP = IERC20(DEX.WETH());
DEX_FACTORY = IUniswapV2Factory(DEX.factory());
DEX_PAIR = IUniswapV2Pair(DEX_FACTORY.createPair(address(WRAP), address(this)));
_registerFund(FOMO);
_registerFund(BLACK_HOLE);
_registerFund(address(BUFFER));
_registerFund(address(IDO));
_registerFund(address(this));
_registerFund(_msgSender());
_mint(BLACK_HOLE, BURN_AMOUNT);
_mint(address(IDO), IDO_AMOUNT);
_isHolder[owner()] = true;
_holders.push(owner());
}
function getIDOConfigs() public pure returns
(
uint256 IDOAmount,
uint256 IDODepositCap,
uint256 IDODepositMax,
uint32 IDOTimestampFrom,
uint32 IDOTimestampTo,
address buffer
) {
IDOAmount = IDO_AMOUNT;
IDODepositCap = IDO_DEPOSIT_CAP;
IDODepositMax = IDO_DEPOSIT_MAX;
IDOTimestampFrom = IDO_TIMESTAMP_FROM;
IDOTimestampTo = IDO_TIMESTAMP_TO;
buffer = ADDRESS_BUFFER;
}
function getBufferConfigs() public pure returns
(
address dex,
address usd
) {
dex = ADDRESS_DEX;
usd = ADDRESS_USD;
}
function isInitialLiquidityCreated() public view returns (bool) {
return 0 < _timestampLiquidityCreated;
}
/**
* @dev Set username for `_msgSender()`
*/
function setUsername(string calldata value) external {
require(0 < balanceOf(_msgSender()) || IDO.isFounder(_msgSender()), "HyperDeFi: balance is zero");
require(address(0) == _username2address[value], "HyperDeFi: username is already benn taken");
require(!_usernamed[_msgSender()], "HyperDeFi: username cannot be changed");
_username[_msgSender()] = value;
_usernamed[_msgSender()] = true;
_username2address[value] = _msgSender();
_totalUsername++;
emit UsernameSet(_msgSender(), value);
_mayAutoSwapIntoLiquidity();
}
/**
* @dev Generate coupon for `_msgSender()`
*/
function genConpon() external {
require(0 < balanceOf(_msgSender()) || IDO.isFounder(_msgSender()), "HyperDeFi Conpon: balance is zero");
require(_coupon[_msgSender()] == 0, "HyperDeFi Conpon: already generated");
uint256 coupon = uint256(keccak256(abi.encode(blockhash(block.number - 1), _msgSender()))) % type(uint32).max;
require(0 < coupon, "HyperDeFi Conpon: invalid code, please retry");
_coupon[_msgSender()] = coupon;
_inviter[coupon] = _msgSender();
_mayAutoSwapIntoLiquidity();
}
/**
* @dev Set coupon for `_msgSender()`
*/
function useCoupon(uint256 coupon) external {
address inviter = _inviter[coupon];
require(isValidCouponForAccount(coupon, _msgSender()), "HyperDeFi Coupon: invalid");
_couponUsed[_msgSender()] = coupon;
_visitors[inviter]++;
emit CouponVisitor(inviter, _msgSender());
_mayAutoSwapIntoLiquidity();
}
/**
* @dev Returns `true` if `coupon` is valid for `account`
*/
function isValidCouponForAccount(uint256 coupon, address account) public view returns (bool) {
address inviter = _inviter[coupon];
if (inviter == address(0)) return false;
for (uint8 i = 1; i < BONUS.length; i++) {
if (inviter == account) return false;
inviter = _inviter[_couponUsed[inviter]];
if (inviter == address(0)) return true;
}
return true;
}
/**
* @dev Pay TAX
*/
function payFee(uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy) public returns (bool) {
uint256 amount = farm + airdrop + fomo + liquidity + fund + destroy;
require(amount > 0, "HyperDeFi: fee amount is zero");
require(amount <= balanceOf(_msgSender()), "HyperDeFi: fee amount exceeds balance");
unchecked {
_balance[_msgSender()] -= amount;
}
if (0 < farm) _payFarm( _msgSender(), farm);
if (0 < airdrop) _payAirdrop( _msgSender(), airdrop, _generateRandom(tx.origin));
if (0 < fomo) _payFomo( _msgSender(), fomo);
if (0 < liquidity) _payLiquidity(_msgSender(), liquidity);
if (0 < fund) _payFund( _msgSender(), fund);
if (0 < destroy) _payDestroy( _msgSender(), destroy);
_mayAutoSwapIntoLiquidity();
return true;
}
/**
* @dev Pay TAX from `sender`
*/
function payFeeFrom(address sender, uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy) public returns (bool) {
uint256 amount = farm + airdrop + fomo + liquidity + fund + destroy;
require(amount > 0, "HyperDeFi: fee amount is zero");
require(amount <= balanceOf(sender), "HyperDeFi: fee amount exceeds balance");
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "HyperDeFi: fee amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
_balance[sender] -= amount;
}
if (0 < farm) _payFarm( sender, farm);
if (0 < airdrop) _payAirdrop( sender, airdrop, _generateRandom(tx.origin));
if (0 < fomo) _payFomo( sender, fomo);
if (0 < liquidity) _payLiquidity(sender, liquidity);
if (0 < fund) _payFund( sender, fund);
if (0 < destroy) _payDestroy( sender, destroy);
_mayAutoSwapIntoLiquidity();
return true;
}
function harvestOf(address account) public view returns (uint256) {
if (_totalFarm <= _totalFarmSnap[account]) return 0; // never happens
uint256 harvest = _balance[account] * (_totalFarm - _totalFarmSnap[account]) / _totalSupply;
return harvest.min(balanceOf(FARM));
}
function takeHarvest() public returns (bool) {
_takeHarvest(_msgSender());
_mayAutoSwapIntoLiquidity();
return true;
}
/**
* @dev Register a slot for DApp
*/
function registerSlot(address account) public onlyOwner {
require(!_isSlot[account], "The slot is already exist");
require(!_isHolder[account], "The holder is already exist");
_isSlot[account] = true;
_isFlat[account] = true;
_slots.push(account);
_flats.push(account);
emit SlotRegistered(account);
_mayAutoSwapIntoLiquidity();
}
// --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ERC20
/**
* @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 _balance[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 override returns (bool) {
if (BLACK_HOLE == recipient || address(this) == recipient) {
_burn(_msgSender(), amount);
return true;
}
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev Create initial liquidity
*/
function createInitLiquidity() public payable returns (bool) {
require(_msgSender() == address(IDO), "HyperDeFi: caller is not the IDO contract");
require(0 == _timestampLiquidityCreated, "HyperDeFi: initial liquidity has been created");
_initPrice = address(this).balance * 10 ** _decimals / INIT_LIQUIDITY;
_mint(address(this), INIT_LIQUIDITY);
_approve(address(this), ADDRESS_DEX, type(uint256).max);
DEX.addLiquidityETH{value: address(this).balance}(
address(this),
INIT_LIQUIDITY,
0,
0,
BLACK_HOLE,
block.timestamp
);
_timestampLiquidityCreated = block.timestamp;
return true;
}
/**
* @dev Burn
*/
function burn(uint256 amount) public returns (bool) {
_burn(_msgSender(), amount);
_mayAutoSwapIntoLiquidity();
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view 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 override returns (bool) {
_approve(_msgSender(), spender, amount);
_mayAutoSwapIntoLiquidity();
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 override returns (bool) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
_transfer(sender, recipient, amount);
return true;
}
/**
* @dev Burn from `sender`
*/
function burnFrom(address sender, uint256 amount) public returns (bool) {
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
_burn(sender, amount);
_mayAutoSwapIntoLiquidity();
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] + addedValue);
_mayAutoSwapIntoLiquidity();
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) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
_mayAutoSwapIntoLiquidity();
return true;
}
/**
* @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 {
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 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) private {
require(account != address(0), "ERC20: mint to the zero address");
require(TOTAL_SUPPLY_CAP >= _totalSupply + amount, "ERC20: cap exceeded");
_totalSupply += amount;
_balance[account] += amount;
emit Transfer(address(0), account, amount);
emit TX(uint8(TX_TYPE.MINT), address(0), account, amount, amount);
}
/**
* @dev Destroys `amount` tokens from `account` to black-hole.
*
* 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");
require(_totalSupply >= amount, "ERC20: burn amount exceeds total supply");
require(_balance[account] >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balance[account] -= amount;
_balance[BLACK_HOLE] += amount;
}
emit Transfer(account, BLACK_HOLE, amount);
}
// --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- --------- ERC20 <END>
function _priceToken2WRAP() internal view returns (uint256 price) {
uint256 pairTokenAmount = balanceOf(address(DEX_PAIR));
if (0 < pairTokenAmount) {
return BUFFER.priceToken2WRAP();
}
else {
return IDO.priceToken2WRAP();
}
}
function _priceToken2USD() internal view returns (uint256 price) {
uint256 pairTokenAmount = balanceOf(address(DEX_PAIR));
if (0 < pairTokenAmount) {
return BUFFER.priceToken2USD();
}
else {
return IDO.priceToken2USD();
}
}
function _takeHarvest(address account) internal {
uint256 amount = harvestOf(account);
if (0 == amount) return;
_totalFarmSnap[account] = _totalFarm;
if (0 == amount) return;
if (_balance[FARM] < amount) return;
unchecked {
_balance[FARM] -= amount;
}
_balance[account] += amount;
_totalHarvest[account] += amount;
emit Transfer(FARM, account, amount);
emit TX(uint8(TX_TYPE.HARVEST), FARM, account, amount, amount);
}
/**
* @dev Register a fund for this DeFi token
*/
function _registerFund(address account) internal {
require(!_isFund[account], "The fund is already exist");
require(!_isHolder[account], "The holder is already exist");
_isFund[account] = true;
_isFlat[account] = true;
_funds.push(account);
_flats.push(account);
}
/**
* @dev Add Holder
*/
function _addHolder(address account) internal {
if (_isHolder[account] || _isSlot[account] || _isFund[account]) return;
if (account == ADDRESS_DEX || account == address(DEX_PAIR)) return;
_isHolder[account] = true;
_holders.push(account);
}
/**
* @dev Auto-swap amount
*/
function _getAutoSwapAmountMin() internal view returns (uint256) {
uint256 pairBalance = balanceOf(address(DEX_PAIR));
if (0 < pairBalance) return pairBalance * AUTO_SWAP_NUMERATOR_MIN / AUTO_SWAP_DENOMINATOR;
return INIT_LIQUIDITY * AUTO_SWAP_NUMERATOR_MIN / AUTO_SWAP_DENOMINATOR;
}
function _getAutoSwapAmountMax() internal view returns (uint256) {
uint256 pairBalance = balanceOf(address(DEX_PAIR));
if (0 < pairBalance) return pairBalance * AUTO_SWAP_NUMERATOR_MAX / AUTO_SWAP_DENOMINATOR;
return INIT_LIQUIDITY * AUTO_SWAP_NUMERATOR_MAX / AUTO_SWAP_DENOMINATOR;
}
/**
* @dev Returns whale balance amount
*/
function _getWhaleThreshold() internal view returns (uint256 amount) {
uint256 pairBalance = balanceOf(address(DEX_PAIR));
if (0 < pairBalance) return pairBalance * WHALE_NUMERATOR / WHALE_DENOMINATOR;
}
/**
* @dev Returns robber balance amount
*/
function _getRobberThreshold() internal view returns (uint256 amount) {
uint256 pairBalance = balanceOf(address(DEX_PAIR));
if (0 < pairBalance) return pairBalance * ROBBER_PERCENTAGE / 100;
}
/**
* @dev FOMO amount
*/
function _getFomoAmount() internal view returns (uint256) {
return balanceOf(FOMO) * FOMO_PERCENTAGE / 100;
}
/**
* @dev May auto-swap into liquidity - from the `_BUFFER` contract
*/
function _mayAutoSwapIntoLiquidity() internal withSwapLock {
// may mint to `_BUFFER`
_mayMintToBuffer();
// may swap
uint256 amount = balanceOf(address(BUFFER));
if (0 == amount) return;
if (amount < _getAutoSwapAmountMin()) return;
_approve(address(BUFFER), address(DEX), balanceOf(address(BUFFER)));
BUFFER.swapIntoLiquidity(amount.min(_getAutoSwapAmountMax()));
}
/**
* @dev Transfer token
*/
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");
require(amount > 0, "ERC20: transfer amount is zero");
require(amount <= balanceOf(sender), "ERC20: transfer amount exceeds the balance");
// may transfer fomo
_mayMoveFomo();
// get harvest for recipient
if (recipient != address(DEX_PAIR)) _takeHarvest(recipient);
// may auto-swap into liquidity
if (sender != address(DEX_PAIR) && recipient != address(DEX_PAIR) && !_swapLock) _mayAutoSwapIntoLiquidity();
// tx type
uint256 coupon = sender == address(DEX_PAIR) ? _couponUsed[recipient] : _couponUsed[sender];
TX_TYPE txType = TX_TYPE.TAKER;
if (_isFlat[sender] || _isFlat[recipient]) txType = TX_TYPE.FLAT;
else if (sender == address(DEX_PAIR)) txType = TX_TYPE.MAKER;
// whale or robber
if (txType != TX_TYPE.FLAT) {
require(block.timestamp > TIMESTAMP_LAUNCH, "HyperDeFi: transfer before the `LAUNCH_TIMESTAMP`");
uint256 whaleThreshold = _getWhaleThreshold();
uint256 txAmountIfWhale = amount * (100 - WHALE_TAX.farm - WHALE_TAX.airdrop - WHALE_TAX.fomo - WHALE_TAX.liquidity - WHALE_TAX.fund - WHALE_TAX.destroy) / 100;
// buy as/to a whale
if (sender == address(DEX_PAIR) && whaleThreshold < balanceOf(recipient) + txAmountIfWhale) txType = TX_TYPE.WHALE;
// sell as a whale
else if (recipient == address(DEX_PAIR) && whaleThreshold < balanceOf(sender)) txType = TX_TYPE.WHALE;
// send from a whale
else if (sender != address(DEX_PAIR) && recipient != address(DEX_PAIR) && whaleThreshold < balanceOf(sender)) txType = TX_TYPE.WHALE;
// // send to a whale
// else if (sender != DEX_PAIR && recipient != DEX_PAIR && whaleThreshold < balanceOf(recipient)) txType = TX_TYPE.WHALE;
// buy/sell as a robber
if ((sender == address(DEX_PAIR) || recipient == address(DEX_PAIR)) && _getRobberThreshold() < amount) txType = TX_TYPE.ROBBER;
}
// tx
uint256 rand = _generateRandom(tx.origin);
(uint256 farm, uint256 airdrop, uint256 fomo, uint256 liquidity, uint256 fund, uint256 destroy, uint256 txAmount) = _txData(amount, txType, coupon);
_balance[sender] -= amount;
_balance[recipient] += txAmount;
emit Transfer(sender, recipient, txAmount);
// buy from liquidity, non-slot
if (sender == address(DEX_PAIR) && !_isFlat[recipient] && !_isSlot[recipient] && txType != TX_TYPE.ROBBER) {
// fomo
_fomoNextAccount = recipient;
_fomoTimestamp = block.timestamp + FOMO_TIMESTAMP_STEP;
}
// fee
if (0 < farm) _payFarm( sender, farm);
if (0 < airdrop) _payAirdrop( sender, airdrop, rand);
if (0 < fomo) _payFomo( sender, fomo);
if (0 < liquidity) _payLiquidity(sender, liquidity);
if (0 < fund) _payFund( sender, fund);
if (0 < destroy) _payDestroy( sender, destroy);
// Tx event
emit TX(uint8(txType), sender, recipient, amount, txAmount);
// // may mint to `_BUFFER`
// if (!_isFlat[sender] && !_isFlat[recipient]) _mayMintToBuffer();
// add holder
_addHolder(sender);
_addHolder(recipient);
}
/**
* @dev Generate random from account
*/
function _generateRandom(address account) private view returns (uint256) {
return uint256(keccak256(abi.encode(blockhash(block.number - 1), account)));
}
/**
* @dev TxData
*/
function _txData(uint256 amount, TX_TYPE txType, uint256 coupon) private view
returns (
uint256 farm,
uint256 airdrop,
uint256 fomo,
uint256 liquidity,
uint256 fund,
uint256 destroy,
uint256 txAmount
)
{
(farm, airdrop, fomo, liquidity, fund, destroy) = _txDataWithoutTxAmount(amount, txType, coupon);
txAmount = amount - farm - airdrop - fomo - liquidity - fund - destroy;
return (farm, airdrop, fomo, liquidity, fund, destroy, txAmount);
}
function _txDataWithoutTxAmount(uint256 amount, TX_TYPE txType, uint256 coupon) private view
returns (
uint256 farm,
uint256 airdrop,
uint256 fomo,
uint256 liquidity,
uint256 fund,
uint256 destroy
)
{
if (txType == TX_TYPE.FLAT) return (0, 0, 0, 0, 0, 0);
Percentage memory percentage;
if (txType == TX_TYPE.MAKER) percentage = MAKER_TAX;
else if (txType == TX_TYPE.WHALE) percentage = WHALE_TAX;
else if (txType == TX_TYPE.ROBBER) percentage = ROBBER_TAX;
else percentage = TAKER_TAX;
if (0 < percentage.farm) farm = amount * percentage.farm / 100;
if (0 < percentage.airdrop) airdrop = amount * percentage.airdrop / 100;
if (0 < percentage.fomo) fomo = amount * percentage.fomo / 100;
if (0 < percentage.liquidity) {
if (coupon == 0 || txType == TX_TYPE.ROBBER) {
liquidity = amount * percentage.liquidity / 100;
} else {
liquidity = amount * (percentage.liquidity - 1) / 100;
}
}
if (0 < percentage.fund) fund = amount * percentage.fund / 100;
if (0 < percentage.destroy) destroy = amount * percentage.destroy / 100;
return (farm, airdrop, fomo, liquidity, fund, destroy);
}
/**
* @dev Pay FARM
*/
function _payFarm(address account, uint256 amount) private {
_totalFarm += amount;
_balance[FARM] += amount;
emit Transfer(account, FARM, amount);
}
/**
* @dev Pay AIRDROP
*/
function _payAirdrop(address account, uint256 amount, uint256 rand) private {
uint256 destroy;
uint256 airdrop = amount;
address accountAirdrop = _holders[rand % _holders.length];
address accountLoop = accountAirdrop;
for (uint8 i; i < BONUS.length; i++) {
address inviter = _inviter[_couponUsed[accountLoop]];
if (inviter == address(0)) {
break;
}
uint256 bonus = amount * BONUS[i] / 100;
airdrop -= bonus;
if (balanceOf(inviter) < AIRDROP_THRESHOLD) {
destroy += bonus;
} else {
_balance[inviter] += bonus;
emit Transfer(account, inviter, bonus);
emit Bonus(inviter, bonus);
}
accountLoop = inviter;
}
if (balanceOf(accountAirdrop) < AIRDROP_THRESHOLD) {
destroy += airdrop;
airdrop = 0;
}
if (0 < destroy) {
_payDestroy(account, destroy);
}
if (0 < airdrop) {
_balance[accountAirdrop] += airdrop;
emit Transfer(account, accountAirdrop, airdrop);
emit Airdrop(accountAirdrop, airdrop);
}
}
/**
* @dev Pay FOMO to `_fomo`
*/
function _payFomo(address account, uint256 amount) private {
_balance[FOMO] += amount;
emit Transfer(account, FOMO, amount);
}
/**
* @dev Pay LIQUIDITY
*/
function _payLiquidity(address account, uint256 amount) private {
_balance[address(BUFFER)] += amount;
emit Transfer(account, address(BUFFER), amount);
}
/**
* @dev Pay FUND
*/
function _payFund(address account, uint256 amount) private {
_balance[owner()] += amount;
emit Transfer(account, owner(), amount);
emit Fund(account, amount);
}
/**
* @dev pay DESTROY
*/
function _payDestroy(address account, uint256 amount) internal {
_balance[BLACK_HOLE] += amount;
emit Transfer(account, BLACK_HOLE, amount);
}
/**
* @dev May move FOMO amount
*/
function _mayMoveFomo() private {
if (_fomoNextAccount == address(0) || block.timestamp < _fomoTimestamp) return;
uint256 amount = _getFomoAmount();
_balance[FOMO] -= amount;
_balance[_fomoNextAccount] += amount;
emit Transfer(FOMO, _fomoNextAccount, amount);
_fomoNextAccount = address(0);
}
/**
* @dev May mint to `_BUFFER`
*/
function _mayMintToBuffer() private {
if (0 == _initPrice) return;
if (0 == balanceOf(address(DEX_PAIR))) return;
uint256 amount = DIST_AMOUNT * BUFFER.priceToken2WRAP() / _initPrice / 1024;
if (amount >= DIST_AMOUNT) return;
if (_distributed >= amount) return;
amount -= _distributed;
_distributed += amount;
_mint(address(BUFFER), amount);
}
}
| Returns `true` if `coupon` is valid for `account`/ | function isValidCouponForAccount(uint256 coupon, address account) public view returns (bool) {
address inviter = _inviter[coupon];
if (inviter == address(0)) return false;
for (uint8 i = 1; i < BONUS.length; i++) {
if (inviter == account) return false;
inviter = _inviter[_couponUsed[inviter]];
if (inviter == address(0)) return true;
}
return true;
}
| 5,439,700 |
./full_match/4/0xB27a670E36D0F5e49242F4C0EE4c6fc99BCf6eBa/sources/browser/Factorydexswap.sol | update reserves and, on the first call per block, price accumulators never overflows, and + overflow is desired | function _update(uint balance0, uint balance1, uint112 _reserve0, uint112 _reserve1) private {
require(balance0 <= uint112(-1) && balance1 <= uint112(-1), 'PocketSwap: OVERFLOW');
uint32 blockTimestamp = uint32(block.timestamp % 2**32);
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
price1CumulativeLast += uint(UQ112x112.encode(_reserve0).uqdiv(_reserve1)) * timeElapsed;
}
reserve0 = uint112(balance0);
reserve1 = uint112(balance1);
blockTimestampLast = blockTimestamp;
emit Sync(reserve0, reserve1);
}
| 724,218 |
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPool.sol";
import "../cover/Quotation.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "./MCR.sol";
contract Pool is IPool, MasterAware, ReentrancyGuard {
using Address for address;
using SafeMath for uint;
using SafeERC20 for IERC20;
struct AssetData {
uint112 minAmount;
uint112 maxAmount;
uint32 lastSwapTime;
// 18 decimals of precision. 0.01% -> 0.0001 -> 1e14
uint maxSlippageRatio;
}
/* storage */
address[] public assets;
mapping(address => AssetData) public assetData;
// contracts
Quotation public quotation;
NXMToken public nxmToken;
TokenController public tokenController;
MCR public mcr;
// parameters
address public swapController;
uint public minPoolEth;
PriceFeedOracle public priceFeedOracle;
address public swapOperator;
/* constants */
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint public constant MCR_RATIO_DECIMALS = 4;
uint public constant MAX_MCR_RATIO = 40000; // 400%
uint public constant MAX_BUY_SELL_MCR_ETH_FRACTION = 500; // 5%. 4 decimal points
uint internal constant CONSTANT_C = 5800000;
uint internal constant CONSTANT_A = 1028 * 1e13;
uint internal constant TOKEN_EXPONENT = 4;
/* events */
event Payout(address indexed to, address indexed asset, uint amount);
event NXMSold (address indexed member, uint nxmIn, uint ethOut);
event NXMBought (address indexed member, uint ethIn, uint nxmOut);
event Swapped(address indexed fromAsset, address indexed toAsset, uint amountIn, uint amountOut);
/* logic */
modifier onlySwapOperator {
require(msg.sender == swapOperator, "Pool: not swapOperator");
_;
}
constructor (
address[] memory _assets,
uint112[] memory _minAmounts,
uint112[] memory _maxAmounts,
uint[] memory _maxSlippageRatios,
address _master,
address _priceOracle,
address _swapOperator
) public {
require(_assets.length == _minAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxAmounts.length, "Pool: length mismatch");
require(_assets.length == _maxSlippageRatios.length, "Pool: length mismatch");
for (uint i = 0; i < _assets.length; i++) {
address asset = _assets[i];
require(asset != address(0), "Pool: asset is zero address");
require(_maxAmounts[i] >= _minAmounts[i], "Pool: max < min");
require(_maxSlippageRatios[i] <= 1 ether, "Pool: max < min");
assets.push(asset);
assetData[asset].minAmount = _minAmounts[i];
assetData[asset].maxAmount = _maxAmounts[i];
assetData[asset].maxSlippageRatio = _maxSlippageRatios[i];
}
master = INXMMaster(_master);
priceFeedOracle = PriceFeedOracle(_priceOracle);
swapOperator = _swapOperator;
}
// fallback function
function() external payable {}
// for legacy Pool1 upgrade compatibility
function sendEther() external payable {}
/**
* @dev Calculates total value of all pool assets in ether
*/
function getPoolValueInEth() public view returns (uint) {
uint total = address(this).balance;
for (uint i = 0; i < assets.length; i++) {
address assetAddress = assets[i];
IERC20 token = IERC20(assetAddress);
uint rate = priceFeedOracle.getAssetToEthRate(assetAddress);
require(rate > 0, "Pool: zero rate");
uint assetBalance = token.balanceOf(address(this));
uint assetValue = assetBalance.mul(rate).div(1e18);
total = total.add(assetValue);
}
return total;
}
/* asset related functions */
function getAssets() external view returns (address[] memory) {
return assets;
}
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
) {
AssetData memory data = assetData[_asset];
return (data.minAmount, data.maxAmount, data.lastSwapTime, data.maxSlippageRatio);
}
function addAsset(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_asset != address(0), "Pool: asset is zero address");
require(_max >= _min, "Pool: max < min");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
require(_asset != assets[i], "Pool: asset exists");
}
assets.push(_asset);
assetData[_asset] = AssetData(_min, _max, 0, _maxSlippageRatio);
}
function removeAsset(address _asset) external onlyGovernance {
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
delete assetData[_asset];
assets[i] = assets[assets.length - 1];
assets.pop();
return;
}
revert("Pool: asset not found");
}
function setAssetDetails(
address _asset,
uint112 _min,
uint112 _max,
uint _maxSlippageRatio
) external onlyGovernance {
require(_min <= _max, "Pool: min > max");
require(_maxSlippageRatio <= 1 ether, "Pool: max slippage ratio > 1");
for (uint i = 0; i < assets.length; i++) {
if (_asset != assets[i]) {
continue;
}
assetData[_asset].minAmount = _min;
assetData[_asset].maxAmount = _max;
assetData[_asset].maxSlippageRatio = _maxSlippageRatio;
return;
}
revert("Pool: asset not found");
}
/* claim related functions */
/**
* @dev Execute the payout in case a claim is accepted
* @param asset token address or 0xEee...EEeE for ether
* @param payoutAddress send funds to this address
* @param amount amount to send
*/
function sendClaimPayout (
address asset,
address payable payoutAddress,
uint amount
) external onlyInternal nonReentrant returns (bool success) {
bool ok;
if (asset == ETH) {
// solhint-disable-next-line avoid-low-level-calls
(ok, /* data */) = payoutAddress.call.value(amount)("");
} else {
ok = _safeTokenTransfer(asset, payoutAddress, amount);
}
if (ok) {
emit Payout(payoutAddress, asset, amount);
}
return ok;
}
/**
* @dev safeTransfer implementation that does not revert
* @param tokenAddress ERC20 address
* @param to destination
* @param value amount to send
* @return success true if the transfer was successfull
*/
function _safeTokenTransfer (
address tokenAddress,
address to,
uint256 value
) internal returns (bool) {
// token address is not a contract
if (!tokenAddress.isContract()) {
return false;
}
IERC20 token = IERC20(tokenAddress);
bytes memory data = abi.encodeWithSelector(token.transfer.selector, to, value);
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = tokenAddress.call(data);
// low-level call failed/reverted
if (!success) {
return false;
}
// tokens that don't have return data
if (returndata.length == 0) {
return true;
}
// tokens that have return data will return a bool
return abi.decode(returndata, (bool));
}
/* pool lifecycle functions */
function transferAsset(
address asset,
address payable destination,
uint amount
) external onlyGovernance nonReentrant {
require(assetData[asset].maxAmount == 0, "Pool: max not zero");
require(destination != address(0), "Pool: dest zero");
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferableAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferableAmount);
}
function upgradeCapitalPool(address payable newPoolAddress) external onlyMaster nonReentrant {
// transfer ether
uint ethBalance = address(this).balance;
(bool ok, /* data */) = newPoolAddress.call.value(ethBalance)("");
require(ok, "Pool: transfer failed");
// transfer assets
for (uint i = 0; i < assets.length; i++) {
IERC20 token = IERC20(assets[i]);
uint tokenBalance = token.balanceOf(address(this));
token.safeTransfer(newPoolAddress, tokenBalance);
}
}
/**
* @dev Update dependent contract address
* @dev Implements MasterAware interface function
*/
function changeDependentContractAddress() public {
nxmToken = NXMToken(master.tokenAddress());
tokenController = TokenController(master.getLatestAddress("TC"));
quotation = Quotation(master.getLatestAddress("QT"));
mcr = MCR(master.getLatestAddress("MC"));
}
/* cover purchase functions */
/// @dev Enables user to purchase cover with funding in ETH.
/// @param smartCAdd Smart Contract Address
function makeCoverBegin(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public payable onlyMember whenNotPaused {
require(coverCurr == "ETH", "Pool: Unexpected asset type");
require(msg.value == coverDetails[1], "Pool: ETH amount does not match premium");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
/**
* @dev Enables user to purchase cover via currency asset eg DAI
*/
function makeCoverUsingCA(
address smartCAdd,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyMember whenNotPaused {
require(coverCurr != "ETH", "Pool: Unexpected asset type");
quotation.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s);
}
function transferAssetFrom (address asset, address from, uint amount) public onlyInternal whenNotPaused {
IERC20 token = IERC20(asset);
token.safeTransferFrom(from, address(this), amount);
}
function transferAssetToSwapOperator (address asset, uint amount) public onlySwapOperator nonReentrant whenNotPaused {
if (asset == ETH) {
(bool ok, /* data */) = swapOperator.call.value(amount)("");
require(ok, "Pool: Eth transfer failed");
return;
}
IERC20 token = IERC20(asset);
token.safeTransfer(swapOperator, amount);
}
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) public onlySwapOperator whenNotPaused {
assetData[asset].lastSwapTime = lastSwapTime;
}
/* token sale functions */
/**
* @dev (DEPRECATED, use sellTokens function instead) Allows selling of NXM for ether.
* Seller first needs to give this contract allowance to
* transfer/burn tokens in the NXMToken contract
* @param _amount Amount of NXM to sell
* @return success returns true on successfull sale
*/
function sellNXMTokens(uint _amount) public onlyMember whenNotPaused returns (bool success) {
sellNXM(_amount, 0);
return true;
}
/**
* @dev (DEPRECATED, use calculateNXMForEth function instead) Returns the amount of wei a seller will get for selling NXM
* @param amount Amount of NXM to sell
* @return weiToPay Amount of wei the seller will get
*/
function getWei(uint amount) external view returns (uint weiToPay) {
return getEthForNXM(amount);
}
/**
* @dev Buys NXM tokens with ETH.
* @param minTokensOut Minimum amount of tokens to be bought. Revert if boughtTokens falls below this number.
* @return boughtTokens number of bought tokens.
*/
function buyNXM(uint minTokensOut) public payable onlyMember whenNotPaused {
uint ethIn = msg.value;
require(ethIn > 0, "Pool: ethIn > 0");
uint totalAssetValue = getPoolValueInEth().sub(ethIn);
uint mcrEth = mcr.getMCR();
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
require(mcrRatio <= MAX_MCR_RATIO, "Pool: Cannot purchase if MCR% > 400%");
uint tokensOut = calculateNXMForEth(ethIn, totalAssetValue, mcrEth);
require(tokensOut >= minTokensOut, "Pool: tokensOut is less than minTokensOut");
tokenController.mint(msg.sender, tokensOut);
// evaluate the new MCR for the current asset value including the ETH paid in
mcr.updateMCRInternal(totalAssetValue.add(ethIn), false);
emit NXMBought(msg.sender, ethIn, tokensOut);
}
/**
* @dev Sell NXM tokens and receive ETH.
* @param tokenAmount Amount of tokens to sell.
* @param minEthOut Minimum amount of ETH to be received. Revert if ethOut falls below this number.
* @return ethOut amount of ETH received in exchange for the tokens.
*/
function sellNXM(uint tokenAmount, uint minEthOut) public onlyMember nonReentrant whenNotPaused {
require(nxmToken.balanceOf(msg.sender) >= tokenAmount, "Pool: Not enough balance");
require(nxmToken.isLockedForMV(msg.sender) <= now, "Pool: NXM tokens are locked for voting");
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint ethOut = calculateEthForNXM(tokenAmount, currentTotalAssetValue, mcrEth);
require(currentTotalAssetValue.sub(ethOut) >= mcrEth, "Pool: MCR% cannot fall below 100%");
require(ethOut >= minEthOut, "Pool: ethOut < minEthOut");
tokenController.burnFrom(msg.sender, tokenAmount);
(bool ok, /* data */) = msg.sender.call.value(ethOut)("");
require(ok, "Pool: Sell transfer failed");
// evaluate the new MCR for the current asset value excluding the paid out ETH
mcr.updateMCRInternal(currentTotalAssetValue.sub(ethOut), false);
emit NXMSold(msg.sender, tokenAmount, ethOut);
}
/**
* @dev Get value in tokens for an ethAmount purchase.
* @param ethAmount amount of ETH used for buying.
* @return tokenValue tokens obtained by buying worth of ethAmount
*/
function getNXMForEth(
uint ethAmount
) public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateNXMForEth(ethAmount, totalAssetValue, mcrEth);
}
function calculateNXMForEth(
uint ethAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Purchases worth higher than 5% of MCReth are not allowed"
);
/*
The price formula is:
P(V) = A + MCReth / C * MCR% ^ 4
where MCR% = V / MCReth
P(V) = A + 1 / (C * MCReth ^ 3) * V ^ 4
To compute the number of tokens issued we can integrate with respect to V the following:
ΔT = ΔV / P(V)
which assumes that for an infinitesimally small change in locked value V price is constant and we
get an infinitesimally change in token supply ΔT.
This is not computable on-chain, below we use an approximation that works well assuming
* MCR% stays within [100%, 400%]
* ethAmount <= 5% * MCReth
Use a simplified formula excluding the constant A price offset to compute the amount of tokens to be minted.
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
AdjustedP(V) = 1 / (C * MCReth ^ 3) * V ^ 4
For a very small variation in tokens ΔT, we have, ΔT = ΔV / P(V), to get total T we integrate with respect to V.
adjustedTokenAmount = ∫ (dV / AdjustedP(V)) from V0 (currentTotalAssetValue) to V1 (nextTotalAssetValue)
adjustedTokenAmount = ∫ ((C * MCReth ^ 3) / V ^ 4 * dV) from V0 to V1
Evaluating the above using the antiderivative of the function we get:
adjustedTokenAmount = - MCReth ^ 3 * C / (3 * V1 ^3) + MCReth * C /(3 * V0 ^ 3)
*/
if (currentTotalAssetValue == 0 || mcrEth.div(currentTotalAssetValue) > 1e12) {
/*
If the currentTotalAssetValue = 0, adjustedTokenPrice approaches 0. Therefore we can assume the price is A.
If currentTotalAssetValue is far smaller than mcrEth, MCR% approaches 0, let the price be A (baseline price).
This avoids overflow in the calculateIntegralAtPoint computation.
This approximation is safe from arbitrage since at MCR% < 100% no sells are possible.
*/
uint tokenPrice = CONSTANT_A;
return ethAmount.mul(1e18).div(tokenPrice);
}
// MCReth * C /(3 * V0 ^ 3)
uint point0 = calculateIntegralAtPoint(currentTotalAssetValue, mcrEth);
// MCReth * C / (3 * V1 ^3)
uint nextTotalAssetValue = currentTotalAssetValue.add(ethAmount);
uint point1 = calculateIntegralAtPoint(nextTotalAssetValue, mcrEth);
uint adjustedTokenAmount = point0.sub(point1);
/*
Compute a preliminary adjustedTokenPrice for the minted tokens based on the adjustedTokenAmount above,
and to that add the A constant (the price offset previously removed in the adjusted Price formula)
to obtain the finalPrice and ultimately the tokenValue based on the finalPrice.
adjustedPrice = ethAmount / adjustedTokenAmount
finalPrice = adjustedPrice + A
tokenValue = ethAmount / finalPrice
*/
// ethAmount is multiplied by 1e18 to cancel out the multiplication factor of 1e18 of the adjustedTokenAmount
uint adjustedTokenPrice = ethAmount.mul(1e18).div(adjustedTokenAmount);
uint tokenPrice = adjustedTokenPrice.add(CONSTANT_A);
return ethAmount.mul(1e18).div(tokenPrice);
}
/**
* @dev integral(V) = MCReth ^ 3 * C / (3 * V ^ 3) * 1e18
* computation result is multiplied by 1e18 to allow for a precision of 18 decimals.
* NOTE: omits the minus sign of the correct integral to use a uint result type for simplicity
* WARNING: this low-level function should be called from a contract which checks that
* mcrEth / assetValue < 1e17 (no overflow) and assetValue != 0
*/
function calculateIntegralAtPoint(
uint assetValue,
uint mcrEth
) internal pure returns (uint) {
return CONSTANT_C
.mul(1e18)
.div(3)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue)
.mul(mcrEth).div(assetValue);
}
function getEthForNXM(uint nxmAmount) public view returns (uint ethAmount) {
uint currentTotalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateEthForNXM(nxmAmount, currentTotalAssetValue, mcrEth);
}
/**
* @dev Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%.
* for values in ETH of the sale <= 1% * MCReth the sell spread is very close to the exact value of 2.5%.
* for values higher than that sell spread may exceed 2.5%
* (The higher amount being sold at any given time the higher the spread)
*/
function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
// Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
// Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
// Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ]
// Sell Spread = 2.5%
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
function calculateMCRRatio(uint totalAssetValue, uint mcrEth) public pure returns (uint) {
return totalAssetValue.mul(10 ** MCR_RATIO_DECIMALS).div(mcrEth);
}
/**
* @dev Calculates token price in ETH 1 NXM token. TokenPrice = A + (MCReth / C) * MCR%^4
*/
function calculateTokenSpotPrice(uint totalAssetValue, uint mcrEth) public pure returns (uint tokenPrice) {
uint mcrRatio = calculateMCRRatio(totalAssetValue, mcrEth);
uint precisionDecimals = 10 ** TOKEN_EXPONENT.mul(MCR_RATIO_DECIMALS);
return mcrEth
.mul(mcrRatio ** TOKEN_EXPONENT)
.div(CONSTANT_C)
.div(precisionDecimals)
.add(CONSTANT_A);
}
/**
* @dev Returns the NXM price in a given asset
* @param asset Asset name.
*/
function getTokenPrice(address asset) public view returns (uint tokenPrice) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
uint tokenSpotPriceEth = calculateTokenSpotPrice(totalAssetValue, mcrEth);
return priceFeedOracle.getAssetForEth(asset, tokenSpotPriceEth);
}
function getMCRRatio() public view returns (uint) {
uint totalAssetValue = getPoolValueInEth();
uint mcrEth = mcr.getMCR();
return calculateMCRRatio(totalAssetValue, mcrEth);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MIN_ETH") {
minPoolEth = value;
return;
}
revert("Pool: unknown parameter");
}
function updateAddressParameters(bytes8 code, address value) external onlyGovernance {
if (code == "SWP_OP") {
swapOperator = value;
return;
}
if (code == "PRC_FEED") {
priceFeedOracle = PriceFeedOracle(value);
return;
}
revert("Pool: unknown parameter");
}
}
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;
}
}
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);
}
pragma solidity ^0.5.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 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");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
constructor () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
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");
}
}
/*
Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/
*/
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract MasterAware {
INXMMaster public master;
modifier onlyMember {
require(master.isMember(msg.sender), "Caller is not a member");
_;
}
modifier onlyInternal {
require(master.isInternal(msg.sender), "Caller is not an internal contract");
_;
}
modifier onlyMaster {
if (address(master) != address(0)) {
require(address(master) == msg.sender, "Not master");
}
_;
}
modifier onlyGovernance {
require(
master.checkIsAuthToGoverned(msg.sender),
"Caller is not authorized to govern"
);
_;
}
modifier whenPaused {
require(master.isPause(), "System is not paused");
_;
}
modifier whenNotPaused {
require(!master.isPause(), "System is paused");
_;
}
function changeDependentContractAddress() external;
function changeMasterAddress(address masterAddress) public onlyMaster {
master = INXMMaster(masterAddress);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0;
interface IPool {
function transferAssetToSwapOperator(address asset, uint amount) external;
function getAssetDetails(address _asset) external view returns (
uint112 min,
uint112 max,
uint32 lastAssetSwapTime,
uint maxSlippageRatio
);
function setAssetDataLastSwapTime(address asset, uint32 lastSwapTime) external;
function minPoolEth() external returns (uint);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../claims/Incidents.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "./QuotationData.sol";
contract Quotation is MasterAware, ReentrancyGuard {
using SafeMath for uint;
ClaimsReward public cr;
Pool public pool;
IPooledStaking public pooledStaking;
QuotationData public qd;
TokenController public tc;
TokenData public td;
Incidents public incidents;
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
cr = ClaimsReward(master.getLatestAddress("CR"));
pool = Pool(master.getLatestAddress("P1"));
pooledStaking = IPooledStaking(master.getLatestAddress("PS"));
qd = QuotationData(master.getLatestAddress("QD"));
tc = TokenController(master.getLatestAddress("TC"));
td = TokenData(master.getLatestAddress("TD"));
incidents = Incidents(master.getLatestAddress("IC"));
}
// solhint-disable-next-line no-empty-blocks
function sendEther() public payable {}
/**
* @dev Expires a cover after a set period of time and changes the status of the cover
* @dev Reduces the total and contract sum assured
* @param coverId Cover Id.
*/
function expireCover(uint coverId) external {
uint expirationDate = qd.getValidityOfCover(coverId);
require(expirationDate < now, "Quotation: cover is not due to expire");
uint coverStatus = qd.getCoverStatusNo(coverId);
require(coverStatus != uint(QuotationData.CoverStatus.CoverExpired), "Quotation: cover already expired");
(/* claim count */, bool hasOpenClaim, /* accepted */) = tc.coverInfo(coverId);
require(!hasOpenClaim, "Quotation: cover has an open claim");
if (coverStatus != uint(QuotationData.CoverStatus.ClaimAccepted)) {
(,, address contractAddress, bytes4 currency, uint amount,) = qd.getCoverDetailsByCoverID1(coverId);
qd.subFromTotalSumAssured(currency, amount);
qd.subFromTotalSumAssuredSC(contractAddress, currency, amount);
}
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.CoverExpired));
}
function withdrawCoverNote(address coverOwner, uint[] calldata coverIds, uint[] calldata reasonIndexes) external {
uint gracePeriod = tc.claimSubmissionGracePeriod();
for (uint i = 0; i < coverIds.length; i++) {
uint expirationDate = qd.getValidityOfCover(coverIds[i]);
require(expirationDate.add(gracePeriod) < now, "Quotation: cannot withdraw before grace period expiration");
}
tc.withdrawCoverNote(coverOwner, coverIds, reasonIndexes);
}
function getWithdrawableCoverNoteCoverIds(
address coverOwner
) public view returns (
uint[] memory expiredCoverIds,
bytes32[] memory lockReasons
) {
uint[] memory coverIds = qd.getAllCoversOfUser(coverOwner);
uint[] memory expiredIdsQueue = new uint[](coverIds.length);
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint expiredQueueLength = 0;
for (uint i = 0; i < coverIds.length; i++) {
uint coverExpirationDate = qd.getValidityOfCover(coverIds[i]);
uint gracePeriodExpirationDate = coverExpirationDate.add(gracePeriod);
(/* claimCount */, bool hasOpenClaim, /* hasAcceptedClaim */) = tc.coverInfo(coverIds[i]);
if (!hasOpenClaim && gracePeriodExpirationDate < now) {
expiredIdsQueue[expiredQueueLength] = coverIds[i];
expiredQueueLength++;
}
}
expiredCoverIds = new uint[](expiredQueueLength);
lockReasons = new bytes32[](expiredQueueLength);
for (uint i = 0; i < expiredQueueLength; i++) {
expiredCoverIds[i] = expiredIdsQueue[i];
lockReasons[i] = keccak256(abi.encodePacked("CN", coverOwner, expiredIdsQueue[i]));
}
}
function getWithdrawableCoverNotesAmount(address coverOwner) external view returns (uint) {
uint withdrawableAmount;
bytes32[] memory lockReasons;
(/*expiredCoverIds*/, lockReasons) = getWithdrawableCoverNoteCoverIds(coverOwner);
for (uint i = 0; i < lockReasons.length; i++) {
uint coverNoteAmount = tc.tokensLocked(coverOwner, lockReasons[i]);
withdrawableAmount = withdrawableAmount.add(coverNoteAmount);
}
return withdrawableAmount;
}
/**
* @dev Makes Cover funded via NXM tokens.
* @param smartCAdd Smart Contract Address
*/
function makeCoverUsingNXMTokens(
uint[] calldata coverDetails,
uint16 coverPeriod,
bytes4 coverCurr,
address smartCAdd,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyMember whenNotPaused {
tc.burnFrom(msg.sender, coverDetails[2]); // needs allowance
_verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s, true);
}
/**
* @dev Verifies cover details signed off chain.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) public onlyInternal {
_verifyCoverDetails(
from,
scAddress,
coverCurr,
coverDetails,
coverPeriod,
_v,
_r,
_s,
false
);
}
/**
* @dev Verifies signature.
* @param coverDetails details related to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
* @param _v argument from vrs hash.
* @param _r argument from vrs hash.
* @param _s argument from vrs hash.
*/
function verifySignature(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress,
uint8 _v,
bytes32 _r,
bytes32 _s
) public view returns (bool) {
require(contractAddress != address(0));
bytes32 hash = getOrderHash(coverDetails, coverPeriod, currency, contractAddress);
return isValidSignature(hash, _v, _r, _s);
}
/**
* @dev Gets order hash for given cover details.
* @param coverDetails details realted to cover.
* @param coverPeriod validity of cover.
* @param contractAddress smart contract address.
*/
function getOrderHash(
uint[] memory coverDetails,
uint16 coverPeriod,
bytes4 currency,
address contractAddress
) public view returns (bytes32) {
return keccak256(
abi.encodePacked(
coverDetails[0],
currency,
coverPeriod,
contractAddress,
coverDetails[1],
coverDetails[2],
coverDetails[3],
coverDetails[4],
address(this)
)
);
}
/**
* @dev Verifies signature.
* @param hash order hash
* @param v argument from vrs hash.
* @param r argument from vrs hash.
* @param s argument from vrs hash.
*/
function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns (bool) {
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash));
address a = ecrecover(prefixedHash, v, r, s);
return (a == qd.getAuthQuoteEngine());
}
/**
* @dev Creates cover of the quotation, changes the status of the quotation ,
* updates the total sum assured and locks the tokens of the cover against a quote.
* @param from Quote member Ethereum address.
*/
function _makeCover(//solhint-disable-line
address payable from,
address contractAddress,
bytes4 coverCurrency,
uint[] memory coverDetails,
uint16 coverPeriod
) internal {
address underlyingToken = incidents.underlyingToken(contractAddress);
if (underlyingToken != address(0)) {
address coverAsset = cr.getCurrencyAssetAddress(coverCurrency);
require(coverAsset == underlyingToken, "Quotation: Unsupported cover asset for this product");
}
uint cid = qd.getCoverLength();
qd.addCover(
coverPeriod,
coverDetails[0],
from,
coverCurrency,
contractAddress,
coverDetails[1],
coverDetails[2]
);
uint coverNoteAmount = coverDetails[2].mul(qd.tokensRetained()).div(100);
if (underlyingToken == address(0)) {
uint gracePeriod = tc.claimSubmissionGracePeriod();
uint claimSubmissionPeriod = uint(coverPeriod).mul(1 days).add(gracePeriod);
bytes32 reason = keccak256(abi.encodePacked("CN", from, cid));
// mint and lock cover note
td.setDepositCNAmount(cid, coverNoteAmount);
tc.mintCoverNote(from, reason, coverNoteAmount, claimSubmissionPeriod);
} else {
// minted directly to member's wallet
tc.mint(from, coverNoteAmount);
}
qd.addInTotalSumAssured(coverCurrency, coverDetails[0]);
qd.addInTotalSumAssuredSC(contractAddress, coverCurrency, coverDetails[0]);
uint coverPremiumInNXM = coverDetails[2];
uint stakersRewardPercentage = td.stakerCommissionPer();
uint rewardValue = coverPremiumInNXM.mul(stakersRewardPercentage).div(100);
pooledStaking.accumulateReward(contractAddress, rewardValue);
}
/**
* @dev Makes a cover.
* @param from address of funder.
* @param scAddress Smart Contract Address
*/
function _verifyCoverDetails(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] memory coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s,
bool isNXM
) internal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
address asset = cr.getCurrencyAssetAddress(coverCurr);
if (coverCurr != "ETH" && !isNXM) {
pool.transferAssetFrom(asset, from, coverDetails[1]);
}
require(verifySignature(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod);
}
function createCover(
address payable from,
address scAddress,
bytes4 currency,
uint[] calldata coverDetails,
uint16 coverPeriod,
uint8 _v,
bytes32 _r,
bytes32 _s
) external onlyInternal {
require(coverDetails[3] > now, "Quotation: Quote has expired");
require(coverPeriod >= 30 && coverPeriod <= 365, "Quotation: Cover period out of bounds");
require(!qd.timestampRepeated(coverDetails[4]), "Quotation: Quote already used");
qd.setTimestampRepeated(coverDetails[4]);
require(verifySignature(coverDetails, coverPeriod, currency, scAddress, _v, _r, _s), "Quotation: signature mismatch");
_makeCover(from, scAddress, currency, coverDetails, coverPeriod);
}
// referenced in master, keeping for now
// solhint-disable-next-line no-empty-blocks
function transferAssetsToNewContract(address) external pure {}
function freeUpHeldCovers() external nonReentrant {
IERC20 dai = IERC20(cr.getCurrencyAssetAddress("DAI"));
uint membershipFee = td.joiningFee();
uint lastCoverId = 106;
for (uint id = 1; id <= lastCoverId; id++) {
if (qd.holdedCoverIDStatus(id) != uint(QuotationData.HCIDStatus.kycPending)) {
continue;
}
(/*id*/, /*sc*/, bytes4 currency, /*period*/) = qd.getHoldedCoverDetailsByID1(id);
(/*id*/, address payable userAddress, uint[] memory coverDetails) = qd.getHoldedCoverDetailsByID2(id);
uint refundedETH = membershipFee;
uint coverPremium = coverDetails[1];
if (qd.refundEligible(userAddress)) {
qd.setRefundEligible(userAddress, false);
}
qd.setHoldedCoverIDStatus(id, uint(QuotationData.HCIDStatus.kycFailedOrRefunded));
if (currency == "ETH") {
refundedETH = refundedETH.add(coverPremium);
} else {
require(dai.transfer(userAddress, coverPremium), "Quotation: DAI refund transfer failed");
}
userAddress.transfer(refundedETH);
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
interface Aggregator {
function latestAnswer() external view returns (int);
}
contract PriceFeedOracle {
using SafeMath for uint;
mapping(address => address) public aggregators;
address public daiAddress;
address public stETH;
address constant public ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
constructor (
address _daiAggregator,
address _daiAddress,
address _stEthAddress
) public {
aggregators[_daiAddress] = _daiAggregator;
daiAddress = _daiAddress;
stETH = _stEthAddress;
}
/**
* @dev Returns the amount of ether in wei that are equivalent to 1 unit (10 ** decimals) of asset
* @param asset quoted currency
* @return price in ether
*/
function getAssetToEthRate(address asset) public view returns (uint) {
if (asset == ETH || asset == stETH) {
return 1 ether;
}
address aggregatorAddress = aggregators[asset];
if (aggregatorAddress == address(0)) {
revert("PriceFeedOracle: Oracle asset not found");
}
int rate = Aggregator(aggregatorAddress).latestAnswer();
require(rate > 0, "PriceFeedOracle: Rate must be > 0");
return uint(rate);
}
/**
* @dev Returns the amount of currency that is equivalent to ethIn amount of ether.
* @param asset quoted Supported values: ["DAI", "ETH"]
* @param ethIn amount of ether to be converted to the currency
* @return price in ether
*/
function getAssetForEth(address asset, uint ethIn) external view returns (uint) {
if (asset == daiAddress) {
return ethIn.mul(1e18).div(getAssetToEthRate(daiAddress));
}
if (asset == ETH || asset == stETH) {
return ethIn;
}
revert("PriceFeedOracle: Unknown asset");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "./external/OZIERC20.sol";
import "./external/OZSafeMath.sol";
contract NXMToken is OZIERC20 {
using OZSafeMath for uint256;
event WhiteListed(address indexed member);
event BlackListed(address indexed member);
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowed;
mapping(address => bool) public whiteListed;
mapping(address => uint) public isLockedForMV;
uint256 private _totalSupply;
string public name = "NXM";
string public symbol = "NXM";
uint8 public decimals = 18;
address public operator;
modifier canTransfer(address _to) {
require(whiteListed[_to]);
_;
}
modifier onlyOperator() {
if (operator != address(0))
require(msg.sender == operator);
_;
}
constructor(address _founderAddress, uint _initialSupply) public {
_mint(_founderAddress, _initialSupply);
}
/**
* @dev Total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Gets the balance of the specified address.
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address owner) public view returns (uint256) {
return _balances[owner];
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param owner address The address which owns the funds.
* @param spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address owner,
address spender
)
public
view
returns (uint256)
{
return _allowed[owner][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value) public returns (bool) {
require(spender != address(0));
_allowed[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param addedValue The amount of tokens to increase the allowance by.
*/
function increaseAllowance(
address spender,
uint256 addedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].add(addedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
* approve should be called when allowed_[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param spender The address which will spend the funds.
* @param subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseAllowance(
address spender,
uint256 subtractedValue
)
public
returns (bool)
{
require(spender != address(0));
_allowed[msg.sender][spender] = (
_allowed[msg.sender][spender].sub(subtractedValue));
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
/**
* @dev Adds a user to whitelist
* @param _member address to add to whitelist
*/
function addToWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = true;
emit WhiteListed(_member);
return true;
}
/**
* @dev removes a user from whitelist
* @param _member address to remove from whitelist
*/
function removeFromWhiteList(address _member) public onlyOperator returns (bool) {
whiteListed[_member] = false;
emit BlackListed(_member);
return true;
}
/**
* @dev change operator address
* @param _newOperator address of new operator
*/
function changeOperator(address _newOperator) public onlyOperator returns (bool) {
operator = _newOperator;
return true;
}
/**
* @dev burns an amount of the tokens of the message sender
* account.
* @param amount The amount that will be burnt.
*/
function burn(uint256 amount) public returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens from the target address and decrements allowance
* @param from address The address which you want to send tokens from
* @param value uint256 The amount of token to be burned
*/
function burnFrom(address from, uint256 value) public returns (bool) {
_burnFrom(from, value);
return true;
}
/**
* @dev function that mints an amount of the token and assigns it to
* an account.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function mint(address account, uint256 amount) public onlyOperator {
_mint(account, amount);
}
/**
* @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 canTransfer(to) returns (bool) {
require(isLockedForMV[msg.sender] < now); // if not voted under governance
require(value <= _balances[msg.sender]);
_transfer(to, value);
return true;
}
/**
* @dev Transfer tokens to the operator from the specified address
* @param from The address to transfer from.
* @param value The amount to be transferred.
*/
function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) {
require(value <= _balances[from]);
_transferFrom(from, operator, 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
canTransfer(to)
returns (bool)
{
require(isLockedForMV[from] < now); // if not voted under governance
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_transferFrom(from, to, value);
return true;
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyOperator {
if (_days.add(now) > isLockedForMV[_of])
isLockedForMV[_of] = _days.add(now);
}
/**
* @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) internal {
_balances[msg.sender] = _balances[msg.sender].sub(value);
_balances[to] = _balances[to].add(value);
emit Transfer(msg.sender, to, value);
}
/**
* @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
)
internal
{
_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);
}
/**
* @dev Internal function that mints an amount of the token and assigns it to
* an account. This encapsulates the modification of balances such that the
* proper events are emitted.
* @param account The account that will receive the created tokens.
* @param amount The amount that will be created.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account.
* @param account The account whose tokens will be burnt.
* @param amount The amount that will be burnt.
*/
function _burn(address account, uint256 amount) internal {
require(amount <= _balances[account]);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = _balances[account].sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Internal function that burns an amount of the token of a given
* account, deducting from the sender's allowance for said account. Uses the
* internal burn function.
* @param account The account whose tokens will be burnt.
* @param value The amount that will be burnt.
*/
function _burnFrom(address account, uint256 value) internal {
require(value <= _allowed[account][msg.sender]);
// Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted,
// this function needs to emit an event with the updated approval.
_allowed[account][msg.sender] = _allowed[account][msg.sender].sub(
value);
_burn(account, value);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
import "../../interfaces/IPooledStaking.sol";
import "../claims/ClaimsData.sol";
import "./NXMToken.sol";
import "./external/LockHandler.sol";
contract TokenController is LockHandler, Iupgradable {
using SafeMath for uint256;
struct CoverInfo {
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// note: still 224 bits available here, can be used later
}
NXMToken public token;
IPooledStaking public pooledStaking;
uint public minCALockTime;
uint public claimSubmissionGracePeriod;
// coverId => CoverInfo
mapping(uint => CoverInfo) public coverInfo;
event Locked(address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity);
event Unlocked(address indexed _of, bytes32 indexed _reason, uint256 _amount);
event Burned(address indexed member, bytes32 lockedUnder, uint256 amount);
modifier onlyGovernance {
require(msg.sender == ms.getLatestAddress("GV"), "TokenController: Caller is not governance");
_;
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {
token = NXMToken(ms.tokenAddress());
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
}
function markCoverClaimOpen(uint coverId) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
uint16 claimCount;
bool hasOpenClaim;
bool hasAcceptedClaim;
// reads all of them using a single SLOAD
(claimCount, hasOpenClaim, hasAcceptedClaim) = (info.claimCount, info.hasOpenClaim, info.hasAcceptedClaim);
// no safemath for uint16 but should be safe from
// overflows as there're max 2 claims per cover
claimCount = claimCount + 1;
require(claimCount <= 2, "TokenController: Max claim count exceeded");
require(hasOpenClaim == false, "TokenController: Cover already has an open claim");
require(hasAcceptedClaim == false, "TokenController: Cover already has accepted claims");
// should use a single SSTORE for both
(info.claimCount, info.hasOpenClaim) = (claimCount, true);
}
/**
* @param coverId cover id (careful, not claim id!)
* @param isAccepted claim verdict
*/
function markCoverClaimClosed(uint coverId, bool isAccepted) external onlyInternal {
CoverInfo storage info = coverInfo[coverId];
require(info.hasOpenClaim == true, "TokenController: Cover claim is not marked as open");
// should use a single SSTORE for both
(info.hasOpenClaim, info.hasAcceptedClaim) = (false, isAccepted);
}
/**
* @dev to change the operator address
* @param _newOperator is the new address of operator
*/
function changeOperator(address _newOperator) public onlyInternal {
token.changeOperator(_newOperator);
}
/**
* @dev Proxies token transfer through this contract to allow staking when members are locked for voting
* @param _from Source address
* @param _to Destination address
* @param _value Amount to transfer
*/
function operatorTransfer(address _from, address _to, uint _value) external onlyInternal returns (bool) {
require(msg.sender == address(pooledStaking), "TokenController: Call is only allowed from PooledStaking address");
token.operatorTransfer(_from, _value);
token.transfer(_to, _value);
return true;
}
/**
* @dev Locks a specified amount of tokens,
* for CLA reason and for a specified time
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lockClaimAssessmentTokens(uint256 _amount, uint256 _time) external checkPause {
require(minCALockTime <= _time, "TokenController: Must lock for minimum time");
require(_time <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
// If tokens are already locked, then functions extendLock or
// increaseClaimAssessmentLock should be used to make any changes
_lock(msg.sender, "CLA", _amount, _time);
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
* @param _of address whose tokens are to be locked
*/
function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time)
public
onlyInternal
returns (bool)
{
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
_lock(_of, _reason, _amount, _time);
return true;
}
/**
* @dev Mints and locks a specified amount of tokens against an address,
* for a CN reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function mintCoverNote(
address _of,
bytes32 _reason,
uint256 _amount,
uint256 _time
) external onlyInternal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.mint(address(this), _amount);
uint256 lockedUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, lockedUntil, false);
emit Locked(_of, _reason, _amount, lockedUntil);
}
/**
* @dev Extends lock for reason CLA for a specified time
* @param _time Lock extension time in seconds
*/
function extendClaimAssessmentLock(uint256 _time) external checkPause {
uint256 validity = getLockedTokensValidity(msg.sender, "CLA");
require(validity.add(_time).sub(block.timestamp) <= 180 days, "TokenController: Tokens can be locked for 180 days maximum");
_extendLock(msg.sender, "CLA", _time);
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLockOf(address _of, bytes32 _reason, uint256 _time)
public
onlyInternal
returns (bool)
{
_extendLock(_of, _reason, _time);
return true;
}
/**
* @dev Increase number of tokens locked for a CLA reason
* @param _amount Number of tokens to be increased
*/
function increaseClaimAssessmentLock(uint256 _amount) external checkPause
{
require(_tokensLocked(msg.sender, "CLA") > 0, "TokenController: No tokens locked");
token.operatorTransfer(msg.sender, _amount);
locked[msg.sender]["CLA"].amount = locked[msg.sender]["CLA"].amount.add(_amount);
emit Locked(msg.sender, "CLA", _amount, locked[msg.sender]["CLA"].validity);
}
/**
* @dev burns tokens of an address
* @param _of is the address to burn tokens of
* @param amount is the amount to burn
* @return the boolean status of the burning process
*/
function burnFrom(address _of, uint amount) public onlyInternal returns (bool) {
return token.burnFrom(_of, amount);
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal {
_burnLockedTokens(_of, _reason, _amount);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal {
_reduceLock(_of, _reason, _time);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount)
public
onlyInternal
{
_releaseLockedTokens(_of, _reason, _amount);
}
/**
* @dev Adds an address to whitelist maintained in the contract
* @param _member address to add to whitelist
*/
function addToWhitelist(address _member) public onlyInternal {
token.addToWhiteList(_member);
}
/**
* @dev Removes an address from the whitelist in the token
* @param _member address to remove
*/
function removeFromWhitelist(address _member) public onlyInternal {
token.removeFromWhiteList(_member);
}
/**
* @dev Mints new token for an address
* @param _member address to reward the minted tokens
* @param _amount number of tokens to mint
*/
function mint(address _member, uint _amount) public onlyInternal {
token.mint(_member, _amount);
}
/**
* @dev Lock the user's tokens
* @param _of user's address.
*/
function lockForMemberVote(address _of, uint _days) public onlyInternal {
token.lockForMemberVote(_of, _days);
}
/**
* @dev Unlocks the withdrawable tokens against CLA of a specified address
* @param _of Address of user, claiming back withdrawable tokens against CLA
*/
function withdrawClaimAssessmentTokens(address _of) external checkPause {
uint256 withdrawableTokens = _tokensUnlockable(_of, "CLA");
if (withdrawableTokens > 0) {
locked[_of]["CLA"].claimed = true;
emit Unlocked(_of, "CLA", withdrawableTokens);
token.transfer(_of, withdrawableTokens);
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param value value to set
*/
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "MNCLT") {
minCALockTime = value;
return;
}
if (code == "GRACEPER") {
claimSubmissionGracePeriod = value;
return;
}
revert("TokenController: invalid param code");
}
function getLockReasons(address _of) external view returns (bytes32[] memory reasons) {
return lockReason[_of];
}
/**
* @dev Gets the validity of locked tokens of a specified address
* @param _of The address to query the validity
* @param reason reason for which tokens were locked
*/
function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) {
validity = locked[_of][reason].validity;
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i]));
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensLocked(_of, _reason);
}
/**
* @dev Returns tokens locked and validity for a specified address and reason
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLockedWithValidity(address _of, bytes32 _reason)
public
view
returns (uint256 amount, uint256 validity)
{
bool claimed = locked[_of][_reason].claimed;
amount = locked[_of][_reason].amount;
validity = locked[_of][_reason].validity;
if (claimed) {
amount = 0;
}
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, bytes32 _reason)
public
view
returns (uint256 amount)
{
return _tokensUnlockable(_of, _reason);
}
function totalSupply() public view returns (uint256)
{
return token.totalSupply();
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
public
view
returns (uint256 amount)
{
return _tokensLockedAtTime(_of, _reason, _time);
}
/**
* @dev Returns the total amount of tokens held by an address:
* transferable + locked + staked for pooled staking - pending burns.
* Used by Claims and Governance in member voting to calculate the user's vote weight.
*
* @param _of The address to query the total balance of
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of) public view returns (uint256 amount) {
amount = token.balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
uint stakerReward = pooledStaking.stakerReward(_of);
uint stakerDeposit = pooledStaking.stakerDeposit(_of);
amount = amount.add(stakerDeposit).add(stakerReward);
}
/**
* @dev Returns the total amount of locked and staked tokens.
* Used by MemberRoles to check eligibility for withdraw / switch membership.
* Includes tokens locked for claim assessment, tokens staked for risk assessment, and locked cover notes
* Does not take into account pending burns.
* @param _of member whose locked tokens are to be calculate
*/
function totalLockedBalance(address _of) public view returns (uint256 amount) {
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount.add(_tokensLocked(_of, lockReason[_of][i]));
}
amount = amount.add(pooledStaking.stakerDeposit(_of));
}
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _of address whose tokens are to be locked
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal {
require(_tokensLocked(_of, _reason) == 0, "TokenController: An amount of tokens is already locked");
require(_amount != 0, "TokenController: Amount shouldn't be zero");
if (locked[_of][_reason].amount == 0) {
lockReason[_of].push(_reason);
}
token.operatorTransfer(_of, _amount);
uint256 validUntil = now.add(_time);
locked[_of][_reason] = LockToken(_amount, validUntil, false);
emit Locked(_of, _reason, _amount, validUntil);
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function _tokensLocked(address _of, bytes32 _reason)
internal
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time)
internal
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function _extendLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev reduce lock duration for a specified reason and time
* @param _of The address whose tokens are locked
* @param _reason The reason to lock tokens
* @param _time Lock reduction time in seconds
*/
function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal {
require(_tokensLocked(_of, _reason) > 0, "TokenController: No tokens locked");
emit Unlocked(_of, _reason, locked[_of][_reason].amount);
locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time);
emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity);
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) {
amount = locked[_of][_reason].amount;
}
}
/**
* @dev Burns locked tokens of a user
* @param _of address whose tokens are to be burned
* @param _reason lock reason for which tokens are to be burned
* @param _amount amount of tokens to burn
*/
function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal {
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.burn(_amount);
emit Burned(_of, _reason, _amount);
}
/**
* @dev Released locked tokens of an address locked for a specific reason
* @param _of address whose tokens are to be released from lock
* @param _reason reason of the lock
* @param _amount amount of tokens to release
*/
function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal
{
uint256 amount = _tokensLocked(_of, _reason);
require(amount >= _amount, "TokenController: Amount exceedes locked tokens amount");
if (amount == _amount) {
locked[_of][_reason].claimed = true;
}
locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount);
// lock reason removal is skipped here: needs to be done from offchain
token.transfer(_of, _amount);
emit Unlocked(_of, _reason, _amount);
}
function withdrawCoverNote(
address _of,
uint[] calldata _coverIds,
uint[] calldata _indexes
) external onlyInternal {
uint reasonCount = lockReason[_of].length;
uint lastReasonIndex = reasonCount.sub(1, "TokenController: No locked cover notes found");
uint totalAmount = 0;
// The iteration is done from the last to first to prevent reason indexes from
// changing due to the way we delete the items (copy last to current and pop last).
// The provided indexes array must be ordered, otherwise reason index checks will fail.
for (uint i = _coverIds.length; i > 0; i--) {
bool hasOpenClaim = coverInfo[_coverIds[i - 1]].hasOpenClaim;
require(hasOpenClaim == false, "TokenController: Cannot withdraw for cover with an open claim");
// note: cover owner is implicitly checked using the reason hash
bytes32 _reason = keccak256(abi.encodePacked("CN", _of, _coverIds[i - 1]));
uint _reasonIndex = _indexes[i - 1];
require(lockReason[_of][_reasonIndex] == _reason, "TokenController: Bad reason index");
uint amount = locked[_of][_reason].amount;
totalAmount = totalAmount.add(amount);
delete locked[_of][_reason];
if (lastReasonIndex != _reasonIndex) {
lockReason[_of][_reasonIndex] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
emit Unlocked(_of, _reason, amount);
if (lastReasonIndex > 0) {
lastReasonIndex = lastReasonIndex.sub(1, "TokenController: Reason count mismatch");
}
}
token.transfer(_of, totalAmount);
}
function removeEmptyReason(address _of, bytes32 _reason, uint _index) external {
_removeEmptyReason(_of, _reason, _index);
}
function removeMultipleEmptyReasons(
address[] calldata _members,
bytes32[] calldata _reasons,
uint[] calldata _indexes
) external {
require(_members.length == _reasons.length, "TokenController: members and reasons array lengths differ");
require(_reasons.length == _indexes.length, "TokenController: reasons and indexes array lengths differ");
for (uint i = _members.length; i > 0; i--) {
uint idx = i - 1;
_removeEmptyReason(_members[idx], _reasons[idx], _indexes[idx]);
}
}
function _removeEmptyReason(address _of, bytes32 _reason, uint _index) internal {
uint lastReasonIndex = lockReason[_of].length.sub(1, "TokenController: lockReason is empty");
require(lockReason[_of][_index] == _reason, "TokenController: bad reason index");
require(locked[_of][_reason].amount == 0, "TokenController: reason amount is not zero");
if (lastReasonIndex != _index) {
lockReason[_of][_index] = lockReason[_of][lastReasonIndex];
}
lockReason[_of].pop();
}
function initialize() external {
require(claimSubmissionGracePeriod == 0, "TokenController: Already initialized");
claimSubmissionGracePeriod = 120 days;
migrate();
}
function migrate() internal {
ClaimsData cd = ClaimsData(ms.getLatestAddress("CD"));
uint totalClaims = cd.actualClaimLength() - 1;
// fix stuck claims 21 & 22
cd.changeFinalVerdict(20, -1);
cd.setClaimStatus(20, 6);
cd.changeFinalVerdict(21, -1);
cd.setClaimStatus(21, 6);
// reduce claim assessment lock period for members locked for more than 180 days
// extracted using scripts/extract-ca-locked-more-than-180.js
address payable[3] memory members = [
0x4a9fA34da6d2378c8f3B9F6b83532B169beaEDFc,
0x6b5DCDA27b5c3d88e71867D6b10b35372208361F,
0x8B6D1e5b4db5B6f9aCcc659e2b9619B0Cd90D617
];
for (uint i = 0; i < members.length; i++) {
if (locked[members[i]]["CLA"].validity > now + 180 days) {
locked[members[i]]["CLA"].validity = now + 180 days;
}
}
for (uint i = 1; i <= totalClaims; i++) {
(/*id*/, uint status) = cd.getClaimStatusNumber(i);
(/*id*/, uint coverId) = cd.getClaimCoverId(i);
int8 verdict = cd.getFinalVerdict(i);
// SLOAD
CoverInfo memory info = coverInfo[coverId];
info.claimCount = info.claimCount + 1;
info.hasAcceptedClaim = (status == 14);
info.hasOpenClaim = (verdict == 0);
// SSTORE
coverInfo[coverId] = info;
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../../abstract/MasterAware.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../oracles/PriceFeedOracle.sol";
import "../token/NXMToken.sol";
import "../token/TokenData.sol";
import "./LegacyMCR.sol";
contract MCR is MasterAware {
using SafeMath for uint;
Pool public pool;
QuotationData public qd;
// sizeof(qd) + 96 = 160 + 96 = 256 (occupies entire slot)
uint96 _unused;
// the following values are expressed in basis points
uint24 public mcrFloorIncrementThreshold = 13000;
uint24 public maxMCRFloorIncrement = 100;
uint24 public maxMCRIncrement = 500;
uint24 public gearingFactor = 48000;
// min update between MCR updates in seconds
uint24 public minUpdateTime = 3600;
uint112 public mcrFloor;
uint112 public mcr;
uint112 public desiredMCR;
uint32 public lastUpdateTime;
LegacyMCR public previousMCR;
event MCRUpdated(
uint mcr,
uint desiredMCR,
uint mcrFloor,
uint mcrETHWithGear,
uint totalSumAssured
);
uint constant UINT24_MAX = ~uint24(0);
uint constant MAX_MCR_ADJUSTMENT = 100;
uint constant BASIS_PRECISION = 10000;
constructor (address masterAddress) public {
changeMasterAddress(masterAddress);
if (masterAddress != address(0)) {
previousMCR = LegacyMCR(master.getLatestAddress("MC"));
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
qd = QuotationData(master.getLatestAddress("QD"));
pool = Pool(master.getLatestAddress("P1"));
initialize();
}
function initialize() internal {
address currentMCR = master.getLatestAddress("MC");
if (address(previousMCR) == address(0) || currentMCR != address(this)) {
// already initialized or not ready for initialization
return;
}
// fetch MCR parameters from previous contract
uint112 minCap = 7000 * 1e18;
mcrFloor = uint112(previousMCR.variableMincap()) + minCap;
mcr = uint112(previousMCR.getLastMCREther());
desiredMCR = mcr;
mcrFloorIncrementThreshold = uint24(previousMCR.dynamicMincapThresholdx100());
maxMCRFloorIncrement = uint24(previousMCR.dynamicMincapIncrementx100());
// set last updated time to now
lastUpdateTime = uint32(block.timestamp);
previousMCR = LegacyMCR(address(0));
}
/**
* @dev Gets total sum assured (in ETH).
* @return amount of sum assured
*/
function getAllSumAssurance() public view returns (uint) {
PriceFeedOracle priceFeed = pool.priceFeedOracle();
address daiAddress = priceFeed.daiAddress();
uint ethAmount = qd.getTotalSumAssured("ETH").mul(1e18);
uint daiAmount = qd.getTotalSumAssured("DAI").mul(1e18);
uint daiRate = priceFeed.getAssetToEthRate(daiAddress);
uint daiAmountInEth = daiAmount.mul(daiRate).div(1e18);
return ethAmount.add(daiAmountInEth);
}
/*
* @dev trigger an MCR update. Current virtual MCR value is synced to storage, mcrFloor is potentially updated
* and a new desiredMCR value to move towards is set.
*
*/
function updateMCR() public {
_updateMCR(pool.getPoolValueInEth(), false);
}
function updateMCRInternal(uint poolValueInEth, bool forceUpdate) public onlyInternal {
_updateMCR(poolValueInEth, forceUpdate);
}
function _updateMCR(uint poolValueInEth, bool forceUpdate) internal {
// read with 1 SLOAD
uint _mcrFloorIncrementThreshold = mcrFloorIncrementThreshold;
uint _maxMCRFloorIncrement = maxMCRFloorIncrement;
uint _gearingFactor = gearingFactor;
uint _minUpdateTime = minUpdateTime;
uint _mcrFloor = mcrFloor;
// read with 1 SLOAD
uint112 _mcr = mcr;
uint112 _desiredMCR = desiredMCR;
uint32 _lastUpdateTime = lastUpdateTime;
if (!forceUpdate && _lastUpdateTime + _minUpdateTime > block.timestamp) {
return;
}
if (block.timestamp > _lastUpdateTime && pool.calculateMCRRatio(poolValueInEth, _mcr) >= _mcrFloorIncrementThreshold) {
// MCR floor updates by up to maxMCRFloorIncrement percentage per day whenever the MCR ratio exceeds 1.3
// MCR floor is monotonically increasing.
uint basisPointsAdjustment = min(
_maxMCRFloorIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days),
_maxMCRFloorIncrement
);
uint newMCRFloor = _mcrFloor.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION);
require(newMCRFloor <= uint112(~0), 'MCR: newMCRFloor overflow');
mcrFloor = uint112(newMCRFloor);
}
// sync the current virtual MCR value to storage
uint112 newMCR = uint112(getMCR());
if (newMCR != _mcr) {
mcr = newMCR;
}
// the desiredMCR cannot fall below the mcrFloor but may have a higher or lower target value based
// on the changes in the totalSumAssured in the system.
uint totalSumAssured = getAllSumAssurance();
uint gearedMCR = totalSumAssured.mul(BASIS_PRECISION).div(_gearingFactor);
uint112 newDesiredMCR = uint112(max(gearedMCR, mcrFloor));
if (newDesiredMCR != _desiredMCR) {
desiredMCR = newDesiredMCR;
}
lastUpdateTime = uint32(block.timestamp);
emit MCRUpdated(mcr, desiredMCR, mcrFloor, gearedMCR, totalSumAssured);
}
/**
* @dev Calculates the current virtual MCR value. The virtual MCR value moves towards the desiredMCR value away
* from the stored mcr value at constant velocity based on how much time passed from the lastUpdateTime.
* The total change in virtual MCR cannot exceed 1% of stored mcr.
*
* This approach allows for the MCR to change smoothly across time without sudden jumps between values, while
* always progressing towards the desiredMCR goal. The desiredMCR can change subject to the call of _updateMCR
* so the virtual MCR value may change direction and start decreasing instead of increasing or vice-versa.
*
* @return mcr
*/
function getMCR() public view returns (uint) {
// read with 1 SLOAD
uint _mcr = mcr;
uint _desiredMCR = desiredMCR;
uint _lastUpdateTime = lastUpdateTime;
if (block.timestamp == _lastUpdateTime) {
return _mcr;
}
uint _maxMCRIncrement = maxMCRIncrement;
uint basisPointsAdjustment = _maxMCRIncrement.mul(block.timestamp - _lastUpdateTime).div(1 days);
basisPointsAdjustment = min(basisPointsAdjustment, MAX_MCR_ADJUSTMENT);
if (_desiredMCR > _mcr) {
return min(_mcr.mul(basisPointsAdjustment.add(BASIS_PRECISION)).div(BASIS_PRECISION), _desiredMCR);
}
// in case desiredMCR <= mcr
return max(_mcr.mul(BASIS_PRECISION - basisPointsAdjustment).div(BASIS_PRECISION), _desiredMCR);
}
function getGearedMCR() external view returns (uint) {
return getAllSumAssurance().mul(BASIS_PRECISION).div(gearingFactor);
}
function min(uint x, uint y) pure internal returns (uint) {
return x < y ? x : y;
}
function max(uint x, uint y) pure internal returns (uint) {
return x > y ? x : y;
}
/**
* @dev Updates Uint Parameters
* @param code parameter code
* @param val new value
*/
function updateUintParameters(bytes8 code, uint val) public {
require(master.checkIsAuthToGoverned(msg.sender));
if (code == "DMCT") {
require(val <= UINT24_MAX, "MCR: value too large");
mcrFloorIncrementThreshold = uint24(val);
} else if (code == "DMCI") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRFloorIncrement = uint24(val);
} else if (code == "MMIC") {
require(val <= UINT24_MAX, "MCR: value too large");
maxMCRIncrement = uint24(val);
} else if (code == "GEAR") {
require(val <= UINT24_MAX, "MCR: value too large");
gearingFactor = uint24(val);
} else if (code == "MUTI") {
require(val <= UINT24_MAX, "MCR: value too large");
minUpdateTime = uint24(val);
} else {
revert("Invalid param code");
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract INXMMaster {
address public tokenAddress;
address public owner;
uint public pauseTime;
function delegateCallBack(bytes32 myid) external;
function masterInitialized() public view returns (bool);
function isInternal(address _add) public view returns (bool);
function isPause() public view returns (bool check);
function isOwner(address _add) public view returns (bool);
function isMember(address _add) public view returns (bool);
function checkIsAuthToGoverned(address _add) public view returns (bool);
function updatePauseTime(uint _time) public;
function dAppLocker() public view returns (address _add);
function dAppToken() public view returns (address _add);
function getLatestAddress(bytes2 _contractName) public view returns (address payable contractAddress);
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
//Claims Reward Contract contains the functions for calculating number of tokens
// that will get rewarded, unlocked or burned depending upon the status of claim.
pragma solidity ^0.5.0;
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../cover/QuotationData.sol";
import "../governance/Governance.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Claims.sol";
import "./ClaimsData.sol";
import "../capital/MCR.sol";
contract ClaimsReward is Iupgradable {
using SafeMath for uint;
NXMToken internal tk;
TokenController internal tc;
TokenData internal td;
QuotationData internal qd;
Claims internal c1;
ClaimsData internal cd;
Pool internal pool;
Governance internal gv;
IPooledStaking internal pooledStaking;
MemberRoles internal memberRoles;
MCR public mcr;
// assigned in constructor
address public DAI;
// constants
address public constant ETH = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
uint private constant DECIMAL1E18 = uint(10) ** 18;
constructor (address masterAddress, address _daiAddress) public {
changeMasterAddress(masterAddress);
DAI = _daiAddress;
}
function changeDependentContractAddress() public onlyInternal {
c1 = Claims(ms.getLatestAddress("CL"));
cd = ClaimsData(ms.getLatestAddress("CD"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
td = TokenData(ms.getLatestAddress("TD"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
pooledStaking = IPooledStaking(ms.getLatestAddress("PS"));
memberRoles = MemberRoles(ms.getLatestAddress("MR"));
pool = Pool(ms.getLatestAddress("P1"));
mcr = MCR(ms.getLatestAddress("MC"));
}
/// @dev Decides the next course of action for a given claim.
function changeClaimStatus(uint claimid) public checkPause onlyInternal {
(, uint coverid) = cd.getClaimCoverId(claimid);
(, uint status) = cd.getClaimStatusNumber(claimid);
// when current status is "Pending-Claim Assessor Vote"
if (status == 0) {
_changeClaimStatusCA(claimid, coverid, status);
} else if (status >= 1 && status <= 5) {
_changeClaimStatusMV(claimid, coverid, status);
} else if (status == 12) {// when current status is "Claim Accepted Payout Pending"
bool payoutSucceeded = attemptClaimPayout(coverid);
if (payoutSucceeded) {
c1.setClaimStatus(claimid, 14);
} else {
c1.setClaimStatus(claimid, 12);
}
}
}
function getCurrencyAssetAddress(bytes4 currency) public view returns (address) {
if (currency == "ETH") {
return ETH;
}
if (currency == "DAI") {
return DAI;
}
revert("ClaimsReward: unknown asset");
}
function attemptClaimPayout(uint coverId) internal returns (bool success) {
uint sumAssured = qd.getCoverSumAssured(coverId);
// TODO: when adding new cover currencies, fetch the correct decimals for this multiplication
uint sumAssuredWei = sumAssured.mul(1e18);
// get asset address
bytes4 coverCurrency = qd.getCurrencyOfCover(coverId);
address asset = getCurrencyAssetAddress(coverCurrency);
// get payout address
address payable coverHolder = qd.getCoverMemberAddress(coverId);
address payable payoutAddress = memberRoles.getClaimPayoutAddress(coverHolder);
// execute the payout
bool payoutSucceeded = pool.sendClaimPayout(asset, payoutAddress, sumAssuredWei);
if (payoutSucceeded) {
// burn staked tokens
(, address scAddress) = qd.getscAddressOfCover(coverId);
uint tokenPrice = pool.getTokenPrice(asset);
// note: for new assets "18" needs to be replaced with target asset decimals
uint burnNXMAmount = sumAssuredWei.mul(1e18).div(tokenPrice);
pooledStaking.pushBurn(scAddress, burnNXMAmount);
// adjust total sum assured
(, address coverContract) = qd.getscAddressOfCover(coverId);
qd.subFromTotalSumAssured(coverCurrency, sumAssured);
qd.subFromTotalSumAssuredSC(coverContract, coverCurrency, sumAssured);
// update MCR since total sum assured and MCR% change
mcr.updateMCRInternal(pool.getPoolValueInEth(), true);
return true;
}
return false;
}
/// @dev Amount of tokens to be rewarded to a user for a particular vote id.
/// @param check 1 -> CA vote, else member vote
/// @param voteid vote id for which reward has to be Calculated
/// @param flag if 1 calculate even if claimed,else don't calculate if already claimed
/// @return tokenCalculated reward to be given for vote id
/// @return lastClaimedCheck true if final verdict is still pending for that voteid
/// @return tokens number of tokens locked under that voteid
/// @return perc percentage of reward to be given.
function getRewardToBeGiven(
uint check,
uint voteid,
uint flag
)
public
view
returns (
uint tokenCalculated,
bool lastClaimedCheck,
uint tokens,
uint perc
)
{
uint claimId;
int8 verdict;
bool claimed;
uint tokensToBeDist;
uint totalTokens;
(tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid);
lastClaimedCheck = false;
int8 claimVerdict = cd.getFinalVerdict(claimId);
if (claimVerdict == 0) {
lastClaimedCheck = true;
}
if (claimVerdict == verdict && (claimed == false || flag == 1)) {
if (check == 1) {
(perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId);
} else {
(, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId);
}
if (perc > 0) {
if (check == 1) {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenCA(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenCA(claimId);
}
} else {
if (verdict == 1) {
(, totalTokens,) = cd.getClaimsTokenMV(claimId);
} else {
(,, totalTokens) = cd.getClaimsTokenMV(claimId);
}
}
tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100));
}
}
}
/// @dev Transfers all tokens held by contract to a new contract in case of upgrade.
function upgrade(address _newAdd) public onlyInternal {
uint amount = tk.balanceOf(address(this));
if (amount > 0) {
require(tk.transfer(_newAdd, amount));
}
}
/// @dev Total reward in token due for claim by a user.
/// @return total total number of tokens
function getRewardToBeDistributedByUser(address _add) public view returns (uint total) {
uint lengthVote = cd.getVoteAddressCALength(_add);
uint lastIndexCA;
uint lastIndexMV;
uint tokenForVoteId;
uint voteId;
(lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add);
for (uint i = lastIndexCA; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(_add, i);
(tokenForVoteId,,,) = getRewardToBeGiven(1, voteId, 0);
total = total.add(tokenForVoteId);
}
lengthVote = cd.getVoteAddressMemberLength(_add);
for (uint j = lastIndexMV; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(_add, j);
(tokenForVoteId,,,) = getRewardToBeGiven(0, voteId, 0);
total = total.add(tokenForVoteId);
}
return (total);
}
/// @dev Gets reward amount and claiming status for a given claim id.
/// @return reward amount of tokens to user.
/// @return claimed true if already claimed false if yet to be claimed.
function getRewardAndClaimedStatus(uint check, uint claimId) public view returns (uint reward, bool claimed) {
uint voteId;
uint claimid;
uint lengthVote;
if (check == 1) {
lengthVote = cd.getVoteAddressCALength(msg.sender);
for (uint i = 0; i < lengthVote; i++) {
voteId = cd.getVoteAddressCA(msg.sender, i);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
} else {
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
for (uint j = 0; j < lengthVote; j++) {
voteId = cd.getVoteAddressMember(msg.sender, j);
(, claimid, , claimed) = cd.getVoteDetails(voteId);
if (claimid == claimId) {break;}
}
}
(reward,,,) = getRewardToBeGiven(check, voteId, 1);
}
/**
* @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance
* Claim assesment, Risk assesment, Governance rewards
*/
function claimAllPendingReward(uint records) public isMemberAndcheckPause {
_claimRewardToBeDistributed(records);
pooledStaking.withdrawReward(msg.sender);
uint governanceRewards = gv.claimReward(msg.sender, records);
if (governanceRewards > 0) {
require(tk.transfer(msg.sender, governanceRewards));
}
}
/**
* @dev Function used to get pending rewards of a particular user address.
* @param _add user address.
* @return total reward amount of the user
*/
function getAllPendingRewardOfUser(address _add) public view returns (uint) {
uint caReward = getRewardToBeDistributedByUser(_add);
uint pooledStakingReward = pooledStaking.stakerReward(_add);
uint governanceReward = gv.getPendingReward(_add);
return caReward.add(pooledStakingReward).add(governanceReward);
}
/// @dev Rewards/Punishes users who participated in Claims assessment.
// Unlocking and burning of the tokens will also depend upon the status of claim.
/// @param claimid Claim Id.
function _rewardAgainstClaim(uint claimid, uint coverid, uint status) internal {
uint premiumNXM = qd.getCoverPremiumNXM(coverid);
uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100); // 20% of premium
uint percCA;
uint percMV;
(percCA, percMV) = cd.getRewardStatus(status);
cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens);
if (percCA > 0 || percMV > 0) {
tc.mint(address(this), distributableTokens);
}
// denied
if (status == 6 || status == 9 || status == 11) {
cd.changeFinalVerdict(claimid, -1);
tc.markCoverClaimClosed(coverid, false);
_burnCoverNoteDeposit(coverid);
// accepted
} else if (status == 7 || status == 8 || status == 10) {
cd.changeFinalVerdict(claimid, 1);
tc.markCoverClaimClosed(coverid, true);
_unlockCoverNote(coverid);
bool payoutSucceeded = attemptClaimPayout(coverid);
// 12 = payout pending, 14 = payout succeeded
uint nextStatus = payoutSucceeded ? 14 : 12;
c1.setClaimStatus(claimid, nextStatus);
}
}
function _burnCoverNoteDeposit(uint coverId) internal {
address _of = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId));
uint lockedAmount = tc.tokensLocked(_of, reason);
(uint amount,) = td.depositedCN(coverId);
amount = amount.div(2);
// limit burn amount to actual amount locked
uint burnAmount = lockedAmount < amount ? lockedAmount : amount;
if (burnAmount != 0) {
tc.burnLockedTokens(_of, reason, amount);
}
}
function _unlockCoverNote(uint coverId) internal {
address coverHolder = qd.getCoverMemberAddress(coverId);
bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId));
uint lockedCN = tc.tokensLocked(coverHolder, reason);
if (lockedCN != 0) {
tc.releaseLockedTokens(coverHolder, reason, lockedCN);
}
}
/// @dev Computes the result of Claim Assessors Voting for a given claim id.
function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency.
uint accept;
uint deny;
uint acceptAndDeny;
bool rewardOrPunish;
uint sumAssured;
(, accept) = cd.getClaimVote(claimid, 1);
(, deny) = cd.getClaimVote(claimid, - 1);
acceptAndDeny = accept.add(deny);
accept = accept.mul(100);
deny = deny.mul(100);
if (caTokens == 0) {
status = 3;
} else {
sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
// Min threshold reached tokens used for voting > 5* sum assured
if (caTokens > sumAssured.mul(5)) {
if (accept.div(acceptAndDeny) > 70) {
status = 7;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted));
rewardOrPunish = true;
} else if (deny.div(acceptAndDeny) > 70) {
status = 6;
qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied));
rewardOrPunish = true;
} else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 4;
} else {
status = 5;
}
} else {
if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) {
status = 2;
} else {
status = 3;
}
}
}
c1.setClaimStatus(claimid, status);
if (rewardOrPunish) {
_rewardAgainstClaim(claimid, coverid, status);
}
}
}
/// @dev Computes the result of Member Voting for a given claim id.
function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal {
// Check if voting should be closed or not
if (c1.checkVoteClosing(claimid) == 1) {
uint8 coverStatus;
uint statusOrig = status;
uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency.
// If tokens used for acceptance >50%, claim is accepted
uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18);
uint thresholdUnreached = 0;
// Minimum threshold for member voting is reached only when
// value of tokens used for voting > 5* sum assured of claim id
if (mvTokens < sumAssured.mul(5)) {
thresholdUnreached = 1;
}
uint accept;
(, accept) = cd.getClaimMVote(claimid, 1);
uint deny;
(, deny) = cd.getClaimMVote(claimid, - 1);
if (accept.add(deny) > 0) {
if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 8;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 &&
statusOrig <= 5 && thresholdUnreached == 0) {
status = 9;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
}
if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) {
status = 10;
coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted);
} else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) {
status = 11;
coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied);
}
c1.setClaimStatus(claimid, status);
qd.changeCoverStatusNo(coverid, uint8(coverStatus));
// Reward/Punish Claim Assessors and Members who participated in Claims assessment
_rewardAgainstClaim(claimid, coverid, status);
}
}
/// @dev Allows a user to claim all pending Claims assessment rewards.
function _claimRewardToBeDistributed(uint _records) internal {
uint lengthVote = cd.getVoteAddressCALength(msg.sender);
uint voteid;
uint lastIndex;
(lastIndex,) = cd.getRewardDistributedIndex(msg.sender);
uint total = 0;
uint tokenForVoteId = 0;
bool lastClaimedCheck;
uint _days = td.lockCADays();
bool claimed;
uint counter = 0;
uint claimId;
uint perc;
uint i;
uint lastClaimed = lengthVote;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressCA(msg.sender, i);
(tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (perc > 0 && !claimed) {
counter++;
cd.setRewardClaimed(voteid, true);
} else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) {
(perc,,) = cd.getClaimRewardDetail(claimId);
if (perc == 0) {
counter++;
}
cd.setRewardClaimed(voteid, true);
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexCA(msg.sender, i);
}
else {
cd.setRewardDistributedIndexCA(msg.sender, lastClaimed);
}
lengthVote = cd.getVoteAddressMemberLength(msg.sender);
lastClaimed = lengthVote;
_days = _days.mul(counter);
if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) {
tc.reduceLock(msg.sender, "CLA", _days);
}
(, lastIndex) = cd.getRewardDistributedIndex(msg.sender);
lastClaimed = lengthVote;
counter = 0;
for (i = lastIndex; i < lengthVote && counter < _records; i++) {
voteid = cd.getVoteAddressMember(msg.sender, i);
(tokenForVoteId, lastClaimedCheck,,) = getRewardToBeGiven(0, voteid, 0);
if (lastClaimed == lengthVote && lastClaimedCheck == true) {
lastClaimed = i;
}
(, claimId, , claimed) = cd.getVoteDetails(voteid);
if (claimed == false && cd.getFinalVerdict(claimId) != 0) {
cd.setRewardClaimed(voteid, true);
counter++;
}
if (tokenForVoteId > 0) {
total = tokenForVoteId.add(total);
}
}
if (total > 0) {
require(tk.transfer(msg.sender, total));
}
if (lastClaimed == lengthVote) {
cd.setRewardDistributedIndexMV(msg.sender, i);
}
else {
cd.setRewardDistributedIndexMV(msg.sender, lastClaimed);
}
}
/**
* @dev Function used to claim the commission earned by the staker.
*/
function _claimStakeCommission(uint _records, address _user) external onlyInternal {
uint total = 0;
uint len = td.getStakerStakedContractLength(_user);
uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user);
uint commissionEarned;
uint commissionRedeemed;
uint maxCommission;
uint lastCommisionRedeemed = len;
uint counter;
uint i;
for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) {
commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i);
commissionEarned = td.getStakerEarnedStakeCommission(_user, i);
maxCommission = td.getStakerInitialStakedAmountOnContract(
_user, i).mul(td.stakerMaxCommissionPer()).div(100);
if (lastCommisionRedeemed == len && maxCommission != commissionEarned)
lastCommisionRedeemed = i;
td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed));
total = total.add(commissionEarned.sub(commissionRedeemed));
counter++;
}
if (lastCommisionRedeemed == len) {
td.setLastCompletedStakeCommissionIndex(_user, i);
} else {
td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed);
}
if (total > 0)
require(tk.transfer(_user, total)); // solhint-disable-line
}
}
/* Copyright (C) 2021 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../../abstract/MasterAware.sol";
import "../../interfaces/IPooledStaking.sol";
import "../capital/Pool.sol";
import "../claims/ClaimsData.sol";
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../governance/MemberRoles.sol";
import "../token/TokenController.sol";
import "../capital/MCR.sol";
contract Incidents is MasterAware {
using SafeERC20 for IERC20;
using SafeMath for uint;
struct Incident {
address productId;
uint32 date;
uint priceBefore;
}
// contract identifiers
enum ID {CD, CR, QD, TC, MR, P1, PS, MC}
mapping(uint => address payable) public internalContracts;
Incident[] public incidents;
// product id => underlying token (ex. yDAI -> DAI)
mapping(address => address) public underlyingToken;
// product id => covered token (ex. 0xc7ed.....1 -> yDAI)
mapping(address => address) public coveredToken;
// claim id => payout amount
mapping(uint => uint) public claimPayout;
// product id => accumulated burn amount
mapping(address => uint) public accumulatedBurn;
// burn ratio in bps, ex 2000 for 20%
uint public BURN_RATIO;
// burn ratio in bps
uint public DEDUCTIBLE_RATIO;
uint constant BASIS_PRECISION = 10000;
event ProductAdded(
address indexed productId,
address indexed coveredToken,
address indexed underlyingToken
);
event IncidentAdded(
address indexed productId,
uint incidentDate,
uint priceBefore
);
modifier onlyAdvisoryBoard {
uint abRole = uint(MemberRoles.Role.AdvisoryBoard);
require(
memberRoles().checkRole(msg.sender, abRole),
"Incidents: Caller is not an advisory board member"
);
_;
}
function initialize() external {
require(BURN_RATIO == 0, "Already initialized");
BURN_RATIO = 2000;
DEDUCTIBLE_RATIO = 9000;
}
function addProducts(
address[] calldata _productIds,
address[] calldata _coveredTokens,
address[] calldata _underlyingTokens
) external onlyAdvisoryBoard {
require(
_productIds.length == _coveredTokens.length,
"Incidents: Protocols and covered tokens lengths differ"
);
require(
_productIds.length == _underlyingTokens.length,
"Incidents: Protocols and underyling tokens lengths differ"
);
for (uint i = 0; i < _productIds.length; i++) {
address id = _productIds[i];
require(coveredToken[id] == address(0), "Incidents: covered token is already set");
require(underlyingToken[id] == address(0), "Incidents: underlying token is already set");
coveredToken[id] = _coveredTokens[i];
underlyingToken[id] = _underlyingTokens[i];
emit ProductAdded(id, _coveredTokens[i], _underlyingTokens[i]);
}
}
function incidentCount() external view returns (uint) {
return incidents.length;
}
function addIncident(
address productId,
uint incidentDate,
uint priceBefore
) external onlyGovernance {
address underlying = underlyingToken[productId];
require(underlying != address(0), "Incidents: Unsupported product");
Incident memory incident = Incident(productId, uint32(incidentDate), priceBefore);
incidents.push(incident);
emit IncidentAdded(productId, incidentDate, priceBefore);
}
function redeemPayoutForMember(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address member
) external onlyInternal returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, member);
}
function redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount
) external returns (uint claimId, uint payoutAmount, address payoutToken) {
(claimId, payoutAmount, payoutToken) = _redeemPayout(coverId, incidentId, coveredTokenAmount, msg.sender);
}
function _redeemPayout(
uint coverId,
uint incidentId,
uint coveredTokenAmount,
address coverOwner
) internal returns (uint claimId, uint payoutAmount, address coverAsset) {
QuotationData qd = quotationData();
Incident memory incident = incidents[incidentId];
uint sumAssured;
bytes4 currency;
{
address productId;
address _coverOwner;
(/* id */, _coverOwner, productId,
currency, sumAssured, /* premiumNXM */
) = qd.getCoverDetailsByCoverID1(coverId);
// check ownership and covered protocol
require(coverOwner == _coverOwner, "Incidents: Not cover owner");
require(productId == incident.productId, "Incidents: Bad incident id");
}
{
uint coverPeriod = uint(qd.getCoverPeriod(coverId)).mul(1 days);
uint coverExpirationDate = qd.getValidityOfCover(coverId);
uint coverStartDate = coverExpirationDate.sub(coverPeriod);
// check cover validity
require(coverStartDate <= incident.date, "Incidents: Cover start date is after the incident");
require(coverExpirationDate >= incident.date, "Incidents: Cover end date is before the incident");
// check grace period
uint gracePeriod = tokenController().claimSubmissionGracePeriod();
require(coverExpirationDate.add(gracePeriod) >= block.timestamp, "Incidents: Grace period has expired");
}
{
// assumes 18 decimals (eth & dai)
uint decimalPrecision = 1e18;
uint maxAmount;
// sumAssured is currently stored without decimals
uint coverAmount = sumAssured.mul(decimalPrecision);
{
// max amount check
uint deductiblePriceBefore = incident.priceBefore.mul(DEDUCTIBLE_RATIO).div(BASIS_PRECISION);
maxAmount = coverAmount.mul(decimalPrecision).div(deductiblePriceBefore);
require(coveredTokenAmount <= maxAmount, "Incidents: Amount exceeds sum assured");
}
// payoutAmount = coveredTokenAmount / maxAmount * coverAmount
// = coveredTokenAmount * coverAmount / maxAmount
payoutAmount = coveredTokenAmount.mul(coverAmount).div(maxAmount);
}
{
TokenController tc = tokenController();
// mark cover as having a successful claim
tc.markCoverClaimOpen(coverId);
tc.markCoverClaimClosed(coverId, true);
// create the claim
ClaimsData cd = claimsData();
claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
cd.setClaimStatus(claimId, 14);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimAccepted));
claimPayout[claimId] = payoutAmount;
}
coverAsset = claimsReward().getCurrencyAssetAddress(currency);
_sendPayoutAndPushBurn(
incident.productId,
address(uint160(coverOwner)),
coveredTokenAmount,
coverAsset,
payoutAmount
);
qd.subFromTotalSumAssured(currency, sumAssured);
qd.subFromTotalSumAssuredSC(incident.productId, currency, sumAssured);
mcr().updateMCRInternal(pool().getPoolValueInEth(), true);
}
function pushBurns(address productId, uint maxIterations) external {
uint burnAmount = accumulatedBurn[productId];
delete accumulatedBurn[productId];
require(burnAmount > 0, "Incidents: No burns to push");
require(maxIterations >= 30, "Incidents: Pass at least 30 iterations");
IPooledStaking ps = pooledStaking();
ps.pushBurn(productId, burnAmount);
ps.processPendingActions(maxIterations);
}
function withdrawAsset(address asset, address destination, uint amount) external onlyGovernance {
IERC20 token = IERC20(asset);
uint balance = token.balanceOf(address(this));
uint transferAmount = amount > balance ? balance : amount;
token.safeTransfer(destination, transferAmount);
}
function _sendPayoutAndPushBurn(
address productId,
address payable coverOwner,
uint coveredTokenAmount,
address coverAsset,
uint payoutAmount
) internal {
address _coveredToken = coveredToken[productId];
// pull depegged tokens
IERC20(_coveredToken).safeTransferFrom(msg.sender, address(this), coveredTokenAmount);
Pool p1 = pool();
// send the payoutAmount
{
address payable payoutAddress = memberRoles().getClaimPayoutAddress(coverOwner);
bool success = p1.sendClaimPayout(coverAsset, payoutAddress, payoutAmount);
require(success, "Incidents: Payout failed");
}
{
// burn
uint decimalPrecision = 1e18;
uint assetPerNxm = p1.getTokenPrice(coverAsset);
uint maxBurnAmount = payoutAmount.mul(decimalPrecision).div(assetPerNxm);
uint burnAmount = maxBurnAmount.mul(BURN_RATIO).div(BASIS_PRECISION);
accumulatedBurn[productId] = accumulatedBurn[productId].add(burnAmount);
}
}
function claimsData() internal view returns (ClaimsData) {
return ClaimsData(internalContracts[uint(ID.CD)]);
}
function claimsReward() internal view returns (ClaimsReward) {
return ClaimsReward(internalContracts[uint(ID.CR)]);
}
function quotationData() internal view returns (QuotationData) {
return QuotationData(internalContracts[uint(ID.QD)]);
}
function tokenController() internal view returns (TokenController) {
return TokenController(internalContracts[uint(ID.TC)]);
}
function memberRoles() internal view returns (MemberRoles) {
return MemberRoles(internalContracts[uint(ID.MR)]);
}
function pool() internal view returns (Pool) {
return Pool(internalContracts[uint(ID.P1)]);
}
function pooledStaking() internal view returns (IPooledStaking) {
return IPooledStaking(internalContracts[uint(ID.PS)]);
}
function mcr() internal view returns (MCR) {
return MCR(internalContracts[uint(ID.MC)]);
}
function updateUintParameters(bytes8 code, uint value) external onlyGovernance {
if (code == "BURNRATE") {
require(value <= BASIS_PRECISION, "Incidents: Burn ratio cannot exceed 10000");
BURN_RATIO = value;
return;
}
if (code == "DEDUCTIB") {
require(value <= BASIS_PRECISION, "Incidents: Deductible ratio cannot exceed 10000");
DEDUCTIBLE_RATIO = value;
return;
}
revert("Incidents: Invalid parameter");
}
function changeDependentContractAddress() external {
INXMMaster master = INXMMaster(master);
internalContracts[uint(ID.CD)] = master.getLatestAddress("CD");
internalContracts[uint(ID.CR)] = master.getLatestAddress("CR");
internalContracts[uint(ID.QD)] = master.getLatestAddress("QD");
internalContracts[uint(ID.TC)] = master.getLatestAddress("TC");
internalContracts[uint(ID.MR)] = master.getLatestAddress("MR");
internalContracts[uint(ID.P1)] = master.getLatestAddress("P1");
internalContracts[uint(ID.PS)] = master.getLatestAddress("PS");
internalContracts[uint(ID.MC)] = master.getLatestAddress("MC");
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract TokenData is Iupgradable {
using SafeMath for uint;
address payable public walletAddress;
uint public lockTokenTimeAfterCoverExp;
uint public bookTime;
uint public lockCADays;
uint public lockMVDays;
uint public scValidDays;
uint public joiningFee;
uint public stakerCommissionPer;
uint public stakerMaxCommissionPer;
uint public tokenExponent;
uint public priceStep;
struct StakeCommission {
uint commissionEarned;
uint commissionRedeemed;
}
struct Stake {
address stakedContractAddress;
uint stakedContractIndex;
uint dateAdd;
uint stakeAmount;
uint unlockedAmount;
uint burnedAmount;
uint unLockableBeforeLastBurn;
}
struct Staker {
address stakerAddress;
uint stakerIndex;
}
struct CoverNote {
uint amount;
bool isDeposited;
}
/**
* @dev mapping of uw address to array of sc address to fetch
* all staked contract address of underwriter, pushing
* data into this array of Stake returns stakerIndex
*/
mapping(address => Stake[]) public stakerStakedContracts;
/**
* @dev mapping of sc address to array of UW address to fetch
* all underwritters of the staked smart contract
* pushing data into this mapped array returns scIndex
*/
mapping(address => Staker[]) public stakedContractStakers;
/**
* @dev mapping of staked contract Address to the array of StakeCommission
* here index of this array is stakedContractIndex
*/
mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission;
mapping(address => uint) public lastCompletedStakeCommission;
/**
* @dev mapping of the staked contract address to the current
* staker index who will receive commission.
*/
mapping(address => uint) public stakedContractCurrentCommissionIndex;
/**
* @dev mapping of the staked contract address to the
* current staker index to burn token from.
*/
mapping(address => uint) public stakedContractCurrentBurnIndex;
/**
* @dev mapping to return true if Cover Note deposited against coverId
*/
mapping(uint => CoverNote) public depositedCN;
mapping(address => uint) internal isBookedTokens;
event Commission(
address indexed stakedContractAddress,
address indexed stakerAddress,
uint indexed scIndex,
uint commissionAmount
);
constructor(address payable _walletAdd) public {
walletAddress = _walletAdd;
bookTime = 12 hours;
joiningFee = 2000000000000000; // 0.002 Ether
lockTokenTimeAfterCoverExp = 35 days;
scValidDays = 250;
lockCADays = 7 days;
lockMVDays = 2 days;
stakerCommissionPer = 20;
stakerMaxCommissionPer = 50;
tokenExponent = 4;
priceStep = 1000;
}
/**
* @dev Change the wallet address which receive Joining Fee
*/
function changeWalletAddress(address payable _address) external onlyInternal {
walletAddress = _address;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "TOKEXP") {
val = tokenExponent;
} else if (code == "TOKSTEP") {
val = priceStep;
} else if (code == "RALOCKT") {
val = scValidDays;
} else if (code == "RACOMM") {
val = stakerCommissionPer;
} else if (code == "RAMAXC") {
val = stakerMaxCommissionPer;
} else if (code == "CABOOKT") {
val = bookTime / (1 hours);
} else if (code == "CALOCKT") {
val = lockCADays / (1 days);
} else if (code == "MVLOCKT") {
val = lockMVDays / (1 days);
} else if (code == "QUOLOCKT") {
val = lockTokenTimeAfterCoverExp / (1 days);
} else if (code == "JOINFEE") {
val = joiningFee;
}
}
/**
* @dev Just for interface
*/
function changeDependentContractAddress() public {//solhint-disable-line
}
/**
* @dev to get the contract staked by a staker
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return the address of staked contract
*/
function getStakerStakedContractByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (address stakedContractAddress)
{
stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
}
/**
* @dev to get the staker's staked burned
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount burned
*/
function getStakerStakedBurnedByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint burnedAmount)
{
burnedAmount = stakerStakedContracts[
_stakerAddress][_stakerIndex].burnedAmount;
}
/**
* @dev to get the staker's staked unlockable before the last burn
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return unlockable staked tokens
*/
function getStakerStakedUnlockableBeforeLastBurnByIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint unlockable)
{
unlockable = stakerStakedContracts[
_stakerAddress][_stakerIndex].unLockableBeforeLastBurn;
}
/**
* @dev to get the staker's staked contract index
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return is the index of the smart contract address
*/
function getStakerStakedContractIndex(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint scIndex)
{
scIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
}
/**
* @dev to get the staker index of the staked contract
* @param _stakedContractAddress is the address of the staked contract
* @param _stakedContractIndex is the index of staked contract
* @return is the index of the staker
*/
function getStakedContractStakerIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (uint sIndex)
{
sIndex = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerIndex;
}
/**
* @dev to get the staker's initial staked amount on the contract
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return staked amount
*/
function getStakerInitialStakedAmountOnContract(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakeAmount;
}
/**
* @dev to get the staker's staked contract length
* @param _stakerAddress is the address of the staker
* @return length of staked contract
*/
function getStakerStakedContractLength(
address _stakerAddress
)
public
view
returns (uint length)
{
length = stakerStakedContracts[_stakerAddress].length;
}
/**
* @dev to get the staker's unlocked tokens which were staked
* @param _stakerAddress is the address of the staker
* @param _stakerIndex is the index of staker
* @return amount
*/
function getStakerUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint amount)
{
amount = stakerStakedContracts[
_stakerAddress][_stakerIndex].unlockedAmount;
}
/**
* @dev pushes the unlocked staked tokens by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushUnlockedStakedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].unlockedAmount.add(_amount);
}
/**
* @dev pushes the Burned tokens for a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be burned.
*/
function pushBurnedTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][
_stakerIndex].burnedAmount.add(_amount);
}
/**
* @dev pushes the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function pushUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn.add(_amount);
}
/**
* @dev sets the unLockable tokens for a staker before last burn.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker.
* @param _amount amount to be added to unlockable.
*/
function setUnlockableBeforeLastBurnTokens(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
stakerStakedContracts[_stakerAddress][
_stakerIndex].unLockableBeforeLastBurn = _amount;
}
/**
* @dev pushes the earned commission earned by a staker.
* @param _stakerAddress address of staker.
* @param _stakedContractAddress address of smart contract.
* @param _stakedContractIndex index of the staker to distribute commission.
* @param _commissionAmount amount to be given as commission.
*/
function pushEarnedStakeCommissions(
address _stakerAddress,
address _stakedContractAddress,
uint _stakedContractIndex,
uint _commissionAmount
)
public
onlyInternal
{
stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex].
commissionEarned = stakedContractStakeCommission[_stakedContractAddress][
_stakedContractIndex].commissionEarned.add(_commissionAmount);
emit Commission(
_stakerAddress,
_stakedContractAddress,
_stakedContractIndex,
_commissionAmount
);
}
/**
* @dev pushes the redeemed commission redeemed by a staker.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker to distribute commission.
* @param _amount amount to be given as commission.
*/
function pushRedeemedStakeCommissions(
address _stakerAddress,
uint _stakerIndex,
uint _amount
)
public
onlyInternal
{
uint stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
address stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
stakedContractStakeCommission[stakedContractAddress][stakedContractIndex].
commissionRedeemed = stakedContractStakeCommission[
stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount);
}
/**
* @dev Gets stake commission given to an underwriter
* for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets stake commission redeemed by an underwriter
* for particular staked contract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
* @return commissionEarned total amount given to staker.
*/
function getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
public
view
returns (uint)
{
return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex);
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalEarnedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionEarned)
{
totalCommissionEarned = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionEarned = totalCommissionEarned.
add(_getStakerEarnedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev Gets total stake commission given to an underwriter
* @param _stakerAddress address of staker.
* @return totalCommissionEarned total commission earned by staker.
*/
function getStakerTotalReedmedStakeCommission(
address _stakerAddress
)
public
view
returns (uint totalCommissionRedeemed)
{
totalCommissionRedeemed = 0;
for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) {
totalCommissionRedeemed = totalCommissionRedeemed.add(
_getStakerRedeemedStakeCommission(_stakerAddress, i));
}
}
/**
* @dev set flag to deposit/ undeposit cover note
* against a cover Id
* @param coverId coverId of Cover
* @param flag true/false for deposit/undeposit
*/
function setDepositCN(uint coverId, bool flag) public onlyInternal {
if (flag == true) {
require(!depositedCN[coverId].isDeposited, "Cover note already deposited");
}
depositedCN[coverId].isDeposited = flag;
}
/**
* @dev set locked cover note amount
* against a cover Id
* @param coverId coverId of Cover
* @param amount amount of nxm to be locked
*/
function setDepositCNAmount(uint coverId, uint amount) public onlyInternal {
depositedCN[coverId].amount = amount;
}
/**
* @dev to get the staker address on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @param _stakedContractIndex is the index of staked contract's index
* @return address of staker
*/
function getStakedContractStakerByIndex(
address _stakedContractAddress,
uint _stakedContractIndex
)
public
view
returns (address stakerAddress)
{
stakerAddress = stakedContractStakers[
_stakedContractAddress][_stakedContractIndex].stakerAddress;
}
/**
* @dev to get the length of stakers on a staked contract
* @param _stakedContractAddress is the address of the staked contract in concern
* @return length in concern
*/
function getStakedContractStakersLength(
address _stakedContractAddress
)
public
view
returns (uint length)
{
length = stakedContractStakers[_stakedContractAddress].length;
}
/**
* @dev Adds a new stake record.
* @param _stakerAddress staker address.
* @param _stakedContractAddress smart contract address.
* @param _amount amountof NXM to be staked.
*/
function addStake(
address _stakerAddress,
address _stakedContractAddress,
uint _amount
)
public
onlyInternal
returns (uint scIndex)
{
scIndex = (stakedContractStakers[_stakedContractAddress].push(
Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1);
stakerStakedContracts[_stakerAddress].push(
Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0));
}
/**
* @dev books the user's tokens for maintaining Assessor Velocity,
* i.e. once a token is used to cast a vote as a Claims assessor,
* @param _of user's address.
*/
function bookCATokens(address _of) public onlyInternal {
require(!isCATokensBooked(_of), "Tokens already booked");
isBookedTokens[_of] = now.add(bookTime);
}
/**
* @dev to know if claim assessor's tokens are booked or not
* @param _of is the claim assessor's address in concern
* @return boolean representing the status of tokens booked
*/
function isCATokensBooked(address _of) public view returns (bool res) {
if (now < isBookedTokens[_of])
res = true;
}
/**
* @dev Sets the index which will receive commission.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentCommissionIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index;
}
/**
* @dev Sets the last complete commission index
* @param _stakerAddress smart contract address.
* @param _index current index.
*/
function setLastCompletedStakeCommissionIndex(
address _stakerAddress,
uint _index
)
public
onlyInternal
{
lastCompletedStakeCommission[_stakerAddress] = _index;
}
/**
* @dev Sets the index till which commission is distrubuted.
* @param _stakedContractAddress smart contract address.
* @param _index current index.
*/
function setStakedContractCurrentBurnIndex(
address _stakedContractAddress,
uint _index
)
public
onlyInternal
{
stakedContractCurrentBurnIndex[_stakedContractAddress] = _index;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "TOKEXP") {
_setTokenExponent(val);
} else if (code == "TOKSTEP") {
_setPriceStep(val);
} else if (code == "RALOCKT") {
_changeSCValidDays(val);
} else if (code == "RACOMM") {
_setStakerCommissionPer(val);
} else if (code == "RAMAXC") {
_setStakerMaxCommissionPer(val);
} else if (code == "CABOOKT") {
_changeBookTime(val * 1 hours);
} else if (code == "CALOCKT") {
_changelockCADays(val * 1 days);
} else if (code == "MVLOCKT") {
_changelockMVDays(val * 1 days);
} else if (code == "QUOLOCKT") {
_setLockTokenTimeAfterCoverExp(val * 1 days);
} else if (code == "JOINFEE") {
_setJoiningFee(val);
} else {
revert("Invalid param code");
}
}
/**
* @dev Internal function to get stake commission given to an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerEarnedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionEarned;
}
/**
* @dev Internal function to get stake commission redeemed by an
* underwriter for particular stakedcontract on given index.
* @param _stakerAddress address of staker.
* @param _stakerIndex index of the staker commission.
*/
function _getStakerRedeemedStakeCommission(
address _stakerAddress,
uint _stakerIndex
)
internal
view
returns (uint amount)
{
uint _stakedContractIndex;
address _stakedContractAddress;
_stakedContractAddress = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractAddress;
_stakedContractIndex = stakerStakedContracts[
_stakerAddress][_stakerIndex].stakedContractIndex;
amount = stakedContractStakeCommission[
_stakedContractAddress][_stakedContractIndex].commissionRedeemed;
}
/**
* @dev to set the percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerCommissionPer(uint _val) internal {
stakerCommissionPer = _val;
}
/**
* @dev to set the max percentage of staker commission
* @param _val is new percentage value
*/
function _setStakerMaxCommissionPer(uint _val) internal {
stakerMaxCommissionPer = _val;
}
/**
* @dev to set the token exponent value
* @param _val is new value
*/
function _setTokenExponent(uint _val) internal {
tokenExponent = _val;
}
/**
* @dev to set the price step
* @param _val is new value
*/
function _setPriceStep(uint _val) internal {
priceStep = _val;
}
/**
* @dev Changes number of days for which NXM needs to staked in case of underwriting
*/
function _changeSCValidDays(uint _days) internal {
scValidDays = _days;
}
/**
* @dev Changes the time period up to which tokens will be locked.
* Used to generate the validity period of tokens booked by
* a user for participating in claim's assessment/claim's voting.
*/
function _changeBookTime(uint _time) internal {
bookTime = _time;
}
/**
* @dev Changes lock CA days - number of days for which tokens
* are locked while submitting a vote.
*/
function _changelockCADays(uint _val) internal {
lockCADays = _val;
}
/**
* @dev Changes lock MV days - number of days for which tokens are locked
* while submitting a vote.
*/
function _changelockMVDays(uint _val) internal {
lockMVDays = _val;
}
/**
* @dev Changes extra lock period for a cover, post its expiry.
*/
function _setLockTokenTimeAfterCoverExp(uint time) internal {
lockTokenTimeAfterCoverExp = time;
}
/**
* @dev Set the joining fee for membership
*/
function _setJoiningFee(uint _amount) internal {
joiningFee = _amount;
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract QuotationData is Iupgradable {
using SafeMath for uint;
enum HCIDStatus {NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover}
enum CoverStatus {Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested}
struct Cover {
address payable memberAddress;
bytes4 currencyCode;
uint sumAssured;
uint16 coverPeriod;
uint validUntil;
address scAddress;
uint premiumNXM;
}
struct HoldCover {
uint holdCoverId;
address payable userAddress;
address scAddress;
bytes4 coverCurr;
uint[] coverDetails;
uint16 coverPeriod;
}
address public authQuoteEngine;
mapping(bytes4 => uint) internal currencyCSA;
mapping(address => uint[]) internal userCover;
mapping(address => uint[]) public userHoldedCover;
mapping(address => bool) public refundEligible;
mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd;
mapping(uint => uint8) public coverStatus;
mapping(uint => uint) public holdedCoverIDStatus;
mapping(uint => bool) public timestampRepeated;
Cover[] internal allCovers;
HoldCover[] internal allCoverHolded;
uint public stlp;
uint public stl;
uint public pm;
uint public minDays;
uint public tokensRetained;
address public kycAuthAddress;
event CoverDetailsEvent(
uint indexed cid,
address scAdd,
uint sumAssured,
uint expiry,
uint premium,
uint premiumNXM,
bytes4 curr
);
event CoverStatusEvent(uint indexed cid, uint8 statusNum);
constructor(address _authQuoteAdd, address _kycAuthAdd) public {
authQuoteEngine = _authQuoteAdd;
kycAuthAddress = _kycAuthAdd;
stlp = 90;
stl = 100;
pm = 30;
minDays = 30;
tokensRetained = 10;
allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0));
uint[] memory arr = new uint[](1);
allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0));
}
/// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be added.
function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address.
/// @param _add Smart Contract Address.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal {
currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount);
}
/// @dev Subtracts the amount from Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be subtracted.
function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].sub(_amount);
}
/// @dev Adds the amount in Total Sum Assured of a given currency.
/// @param _curr Currency Name.
/// @param _amount Amount to be added.
function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal {
currencyCSA[_curr] = currencyCSA[_curr].add(_amount);
}
/// @dev sets bit for timestamp to avoid replay attacks.
function setTimestampRepeated(uint _timestamp) external onlyInternal {
timestampRepeated[_timestamp] = true;
}
/// @dev Creates a blank new cover.
function addCover(
uint16 _coverPeriod,
uint _sumAssured,
address payable _userAddress,
bytes4 _currencyCode,
address _scAddress,
uint premium,
uint premiumNXM
)
external
onlyInternal
{
uint expiryDate = now.add(uint(_coverPeriod).mul(1 days));
allCovers.push(Cover(_userAddress, _currencyCode,
_sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM));
uint cid = allCovers.length.sub(1);
userCover[_userAddress].push(cid);
emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode);
}
/// @dev create holded cover which will process after verdict of KYC.
function addHoldCover(
address payable from,
address scAddress,
bytes4 coverCurr,
uint[] calldata coverDetails,
uint16 coverPeriod
)
external
onlyInternal
{
uint holdedCoverLen = allCoverHolded.length;
holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending);
allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress,
coverCurr, coverDetails, coverPeriod));
userHoldedCover[from].push(allCoverHolded.length.sub(1));
}
///@dev sets refund eligible bit.
///@param _add user address.
///@param status indicates if user have pending kyc.
function setRefundEligible(address _add, bool status) external onlyInternal {
refundEligible[_add] = status;
}
/// @dev to set current status of particular holded coverID (1 for not completed KYC,
/// 2 for KYC passed, 3 for failed KYC or full refunded,
/// 4 for KYC completed but cover not processed)
function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal {
holdedCoverIDStatus[holdedCoverID] = status;
}
/**
* @dev to set address of kyc authentication
* @param _add is the new address
*/
function setKycAuthAddress(address _add) external onlyInternal {
kycAuthAddress = _add;
}
/// @dev Changes authorised address for generating quote off chain.
function changeAuthQuoteEngine(address _add) external onlyInternal {
authQuoteEngine = _add;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "STLP") {
val = stlp;
} else if (code == "STL") {
val = stl;
} else if (code == "PM") {
val = pm;
} else if (code == "QUOMIND") {
val = minDays;
} else if (code == "QUOTOK") {
val = tokensRetained;
}
}
/// @dev Gets Product details.
/// @return _minDays minimum cover period.
/// @return _PM Profit margin.
/// @return _STL short term Load.
/// @return _STLP short term load period.
function getProductDetails()
external
view
returns (
uint _minDays,
uint _pm,
uint _stl,
uint _stlp
)
{
_minDays = minDays;
_pm = pm;
_stl = stl;
_stlp = stlp;
}
/// @dev Gets total number covers created till date.
function getCoverLength() external view returns (uint len) {
return (allCovers.length);
}
/// @dev Gets Authorised Engine address.
function getAuthQuoteEngine() external view returns (address _add) {
_add = authQuoteEngine;
}
/// @dev Gets the Total Sum Assured amount of a given currency.
function getTotalSumAssured(bytes4 _curr) external view returns (uint amount) {
amount = currencyCSA[_curr];
}
/// @dev Gets all the Cover ids generated by a given address.
/// @param _add User's address.
/// @return allCover array of covers.
function getAllCoversOfUser(address _add) external view returns (uint[] memory allCover) {
return (userCover[_add]);
}
/// @dev Gets total number of covers generated by a given address
function getUserCoverLength(address _add) external view returns (uint len) {
len = userCover[_add].length;
}
/// @dev Gets the status of a given cover.
function getCoverStatusNo(uint _cid) external view returns (uint8) {
return coverStatus[_cid];
}
/// @dev Gets the Cover Period (in days) of a given cover.
function getCoverPeriod(uint _cid) external view returns (uint32 cp) {
cp = allCovers[_cid].coverPeriod;
}
/// @dev Gets the Sum Assured Amount of a given cover.
function getCoverSumAssured(uint _cid) external view returns (uint sa) {
sa = allCovers[_cid].sumAssured;
}
/// @dev Gets the Currency Name in which a given cover is assured.
function getCurrencyOfCover(uint _cid) external view returns (bytes4 curr) {
curr = allCovers[_cid].currencyCode;
}
/// @dev Gets the validity date (timestamp) of a given cover.
function getValidityOfCover(uint _cid) external view returns (uint date) {
date = allCovers[_cid].validUntil;
}
/// @dev Gets Smart contract address of cover.
function getscAddressOfCover(uint _cid) external view returns (uint, address) {
return (_cid, allCovers[_cid].scAddress);
}
/// @dev Gets the owner address of a given cover.
function getCoverMemberAddress(uint _cid) external view returns (address payable _add) {
_add = allCovers[_cid].memberAddress;
}
/// @dev Gets the premium amount of a given cover in NXM.
function getCoverPremiumNXM(uint _cid) external view returns (uint _premiumNXM) {
_premiumNXM = allCovers[_cid].premiumNXM;
}
/// @dev Provides the details of a cover Id
/// @param _cid cover Id
/// @return memberAddress cover user address.
/// @return scAddress smart contract Address
/// @return currencyCode currency of cover
/// @return sumAssured sum assured of cover
/// @return premiumNXM premium in NXM
function getCoverDetailsByCoverID1(
uint _cid
)
external
view
returns (
uint cid,
address _memberAddress,
address _scAddress,
bytes4 _currencyCode,
uint _sumAssured,
uint premiumNXM
)
{
return (
_cid,
allCovers[_cid].memberAddress,
allCovers[_cid].scAddress,
allCovers[_cid].currencyCode,
allCovers[_cid].sumAssured,
allCovers[_cid].premiumNXM
);
}
/// @dev Provides details of a cover Id
/// @param _cid cover Id
/// @return status status of cover.
/// @return sumAssured Sum assurance of cover.
/// @return coverPeriod Cover Period of cover (in days).
/// @return validUntil is validity of cover.
function getCoverDetailsByCoverID2(
uint _cid
)
external
view
returns (
uint cid,
uint8 status,
uint sumAssured,
uint16 coverPeriod,
uint validUntil
)
{
return (
_cid,
coverStatus[_cid],
allCovers[_cid].sumAssured,
allCovers[_cid].coverPeriod,
allCovers[_cid].validUntil
);
}
/// @dev Provides details of a holded cover Id
/// @param _hcid holded cover Id
/// @return scAddress SmartCover address of cover.
/// @return coverCurr currency of cover.
/// @return coverPeriod Cover Period of cover (in days).
function getHoldedCoverDetailsByID1(
uint _hcid
)
external
view
returns (
uint hcid,
address scAddress,
bytes4 coverCurr,
uint16 coverPeriod
)
{
return (
_hcid,
allCoverHolded[_hcid].scAddress,
allCoverHolded[_hcid].coverCurr,
allCoverHolded[_hcid].coverPeriod
);
}
/// @dev Gets total number holded covers created till date.
function getUserHoldedCoverLength(address _add) external view returns (uint) {
return userHoldedCover[_add].length;
}
/// @dev Gets holded cover index by index of user holded covers.
function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) {
return userHoldedCover[_add][index];
}
/// @dev Provides the details of a holded cover Id
/// @param _hcid holded cover Id
/// @return memberAddress holded cover user address.
/// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute.
function getHoldedCoverDetailsByID2(
uint _hcid
)
external
view
returns (
uint hcid,
address payable memberAddress,
uint[] memory coverDetails
)
{
return (
_hcid,
allCoverHolded[_hcid].userAddress,
allCoverHolded[_hcid].coverDetails
);
}
/// @dev Gets the Total Sum Assured amount of a given currency and smart contract address.
function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns (uint amount) {
amount = currencyCSAOfSCAdd[_add][_curr];
}
//solhint-disable-next-line
function changeDependentContractAddress() public {}
/// @dev Changes the status of a given cover.
/// @param _cid cover Id.
/// @param _stat New status.
function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal {
coverStatus[_cid] = _stat;
emit CoverStatusEvent(_cid, _stat);
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "STLP") {
_changeSTLP(val);
} else if (code == "STL") {
_changeSTL(val);
} else if (code == "PM") {
_changePM(val);
} else if (code == "QUOMIND") {
_changeMinDays(val);
} else if (code == "QUOTOK") {
_setTokensRetained(val);
} else {
revert("Invalid param code");
}
}
/// @dev Changes the existing Profit Margin value
function _changePM(uint _pm) internal {
pm = _pm;
}
/// @dev Changes the existing Short Term Load Period (STLP) value.
function _changeSTLP(uint _stlp) internal {
stlp = _stlp;
}
/// @dev Changes the existing Short Term Load (STL) value.
function _changeSTL(uint _stl) internal {
stl = _stl;
}
/// @dev Changes the existing Minimum cover period (in days)
function _changeMinDays(uint _days) internal {
minDays = _days;
}
/**
* @dev to set the the amount of tokens retained
* @param val is the amount retained
*/
function _setTokensRetained(uint val) internal {
tokensRetained = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface OZIERC20 {
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value)
external returns (bool);
function transferFrom(address from, address to, uint256 value)
external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender)
external view returns (uint256);
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library OZSafeMath {
/**
* @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;
}
}
pragma solidity ^0.5.0;
import "./INXMMaster.sol";
contract Iupgradable {
INXMMaster public ms;
address public nxMasterAddress;
modifier onlyInternal {
require(ms.isInternal(msg.sender));
_;
}
modifier isMemberAndcheckPause {
require(ms.isPause() == false && ms.isMember(msg.sender) == true);
_;
}
modifier onlyOwner {
require(ms.isOwner(msg.sender));
_;
}
modifier checkPause {
require(ms.isPause() == false);
_;
}
modifier isMember {
require(ms.isMember(msg.sender), "Not member");
_;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public;
/**
* @dev change master address
* @param _masterAddress is the new address
*/
function changeMasterAddress(address _masterAddress) public {
if (address(ms) != address(0)) {
require(address(ms) == msg.sender, "Not master");
}
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
}
pragma solidity ^0.5.0;
interface IPooledStaking {
function accumulateReward(address contractAddress, uint amount) external;
function pushBurn(address contractAddress, uint amount) external;
function hasPendingActions() external view returns (bool);
function processPendingActions(uint maxIterations) external returns (bool finished);
function contractStake(address contractAddress) external view returns (uint);
function stakerReward(address staker) external view returns (uint);
function stakerDeposit(address staker) external view returns (uint);
function stakerContractStake(address staker, address contractAddress) external view returns (uint);
function withdraw(uint amount) external;
function stakerMaxWithdrawable(address stakerAddress) external view returns (uint);
function withdrawReward(address stakerAddress) external;
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/Iupgradable.sol";
contract ClaimsData is Iupgradable {
using SafeMath for uint;
struct Claim {
uint coverId;
uint dateUpd;
}
struct Vote {
address voter;
uint tokens;
uint claimId;
int8 verdict;
bool rewardClaimed;
}
struct ClaimsPause {
uint coverid;
uint dateUpd;
bool submit;
}
struct ClaimPauseVoting {
uint claimid;
uint pendingTime;
bool voting;
}
struct RewardDistributed {
uint lastCAvoteIndex;
uint lastMVvoteIndex;
}
struct ClaimRewardDetails {
uint percCA;
uint percMV;
uint tokenToBeDist;
}
struct ClaimTotalTokens {
uint accept;
uint deny;
}
struct ClaimRewardStatus {
uint percCA;
uint percMV;
}
ClaimRewardStatus[] internal rewardStatus;
Claim[] internal allClaims;
Vote[] internal allvotes;
ClaimsPause[] internal claimPause;
ClaimPauseVoting[] internal claimPauseVotingEP;
mapping(address => RewardDistributed) internal voterVoteRewardReceived;
mapping(uint => ClaimRewardDetails) internal claimRewardDetail;
mapping(uint => ClaimTotalTokens) internal claimTokensCA;
mapping(uint => ClaimTotalTokens) internal claimTokensMV;
mapping(uint => int8) internal claimVote;
mapping(uint => uint) internal claimsStatus;
mapping(uint => uint) internal claimState12Count;
mapping(uint => uint[]) internal claimVoteCA;
mapping(uint => uint[]) internal claimVoteMember;
mapping(address => uint[]) internal voteAddressCA;
mapping(address => uint[]) internal voteAddressMember;
mapping(address => uint[]) internal allClaimsByAddress;
mapping(address => mapping(uint => uint)) internal userClaimVoteCA;
mapping(address => mapping(uint => uint)) internal userClaimVoteMember;
mapping(address => uint) public userClaimVotePausedOn;
uint internal claimPauseLastsubmit;
uint internal claimStartVotingFirstIndex;
uint public pendingClaimStart;
uint public claimDepositTime;
uint public maxVotingTime;
uint public minVotingTime;
uint public payoutRetryTime;
uint public claimRewardPerc;
uint public minVoteThreshold;
uint public maxVoteThreshold;
uint public majorityConsensus;
uint public pauseDaysCA;
event ClaimRaise(
uint indexed coverId,
address indexed userAddress,
uint claimId,
uint dateSubmit
);
event VoteCast(
address indexed userAddress,
uint indexed claimId,
bytes4 indexed typeOf,
uint tokens,
uint submitDate,
int8 verdict
);
constructor() public {
pendingClaimStart = 1;
maxVotingTime = 48 * 1 hours;
minVotingTime = 12 * 1 hours;
payoutRetryTime = 24 * 1 hours;
allvotes.push(Vote(address(0), 0, 0, 0, false));
allClaims.push(Claim(0, 0));
claimDepositTime = 7 days;
claimRewardPerc = 20;
minVoteThreshold = 5;
maxVoteThreshold = 10;
majorityConsensus = 70;
pauseDaysCA = 3 days;
_addRewardIncentive();
}
/**
* @dev Updates the pending claim start variable,
* the lowest claim id with a pending decision/payout.
*/
function setpendingClaimStart(uint _start) external onlyInternal {
require(pendingClaimStart <= _start);
pendingClaimStart = _start;
}
/**
* @dev Updates the max vote index for which claim assessor has received reward
* @param _voter address of the voter.
* @param caIndex last index till which reward was distributed for CA
*/
function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex;
}
/**
* @dev Used to pause claim assessor activity for 3 days
* @param user Member address whose claim voting ability needs to be paused
*/
function setUserClaimVotePausedOn(address user) external {
require(ms.checkIsAuthToGoverned(msg.sender));
userClaimVotePausedOn[user] = now;
}
/**
* @dev Updates the max vote index for which member has received reward
* @param _voter address of the voter.
* @param mvIndex last index till which reward was distributed for member
*/
function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal {
voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex;
}
/**
* @param claimid claim id.
* @param percCA reward Percentage reward for claim assessor
* @param percMV reward Percentage reward for members
* @param tokens total tokens to be rewarded
*/
function setClaimRewardDetail(
uint claimid,
uint percCA,
uint percMV,
uint tokens
)
external
onlyInternal
{
claimRewardDetail[claimid].percCA = percCA;
claimRewardDetail[claimid].percMV = percMV;
claimRewardDetail[claimid].tokenToBeDist = tokens;
}
/**
* @dev Sets the reward claim status against a vote id.
* @param _voteid vote Id.
* @param claimed true if reward for vote is claimed, else false.
*/
function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal {
allvotes[_voteid].rewardClaimed = claimed;
}
/**
* @dev Sets the final vote's result(either accepted or declined)of a claim.
* @param _claimId Claim Id.
* @param _verdict 1 if claim is accepted,-1 if declined.
*/
function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal {
claimVote[_claimId] = _verdict;
}
/**
* @dev Creates a new claim.
*/
function addClaim(
uint _claimId,
uint _coverId,
address _from,
uint _nowtime
)
external
onlyInternal
{
allClaims.push(Claim(_coverId, _nowtime));
allClaimsByAddress[_from].push(_claimId);
}
/**
* @dev Add Vote's details of a given claim.
*/
function addVote(
address _voter,
uint _tokens,
uint claimId,
int8 _verdict
)
external
onlyInternal
{
allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false));
}
/**
* @dev Stores the id of the claim assessor vote given to a claim.
* Maintains record of all votes given by all the CA to a claim.
* @param _claimId Claim Id to which vote has given by the CA.
* @param _voteid Vote Id.
*/
function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal {
claimVoteCA[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Claim assessor's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the CA.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteCA(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteCA[_from][_claimId] = _voteid;
voteAddressCA[_from].push(_voteid);
}
/**
* @dev Stores the tokens locked by the Claim Assessors during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the tokens locked by the Members during voting of a given claim.
* @param _claimId Claim Id.
* @param _vote 1 for accept and increases the tokens of claim as accept,
* -1 for deny and increases the tokens of claim as deny.
* @param _tokens Number of tokens.
*/
function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal {
if (_vote == 1)
claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens);
if (_vote == - 1)
claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens);
}
/**
* @dev Stores the id of the member vote given to a claim.
* Maintains record of all votes given by all the Members to a claim.
* @param _claimId Claim Id to which vote has been given by the Member.
* @param _voteid Vote Id.
*/
function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal {
claimVoteMember[_claimId].push(_voteid);
}
/**
* @dev Sets the id of the vote.
* @param _from Member's address who has given the vote.
* @param _claimId Claim Id for which vote has been given by the Member.
* @param _voteid Vote Id which will be stored against the given _from and claimid.
*/
function setUserClaimVoteMember(
address _from,
uint _claimId,
uint _voteid
)
external
onlyInternal
{
userClaimVoteMember[_from][_claimId] = _voteid;
voteAddressMember[_from].push(_voteid);
}
/**
* @dev Increases the count of failure until payout of a claim is successful.
*/
function updateState12Count(uint _claimId, uint _cnt) external onlyInternal {
claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt);
}
/**
* @dev Sets status of a claim.
* @param _claimId Claim Id.
* @param _stat Status number.
*/
function setClaimStatus(uint _claimId, uint _stat) external onlyInternal {
claimsStatus[_claimId] = _stat;
}
/**
* @dev Sets the timestamp of a given claim at which the Claim's details has been updated.
* @param _claimId Claim Id of claim which has been changed.
* @param _dateUpd timestamp at which claim is updated.
*/
function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal {
allClaims[_claimId].dateUpd = _dateUpd;
}
/**
@dev Queues Claims during Emergency Pause.
*/
function setClaimAtEmergencyPause(
uint _coverId,
uint _dateUpd,
bool _submit
)
external
onlyInternal
{
claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit));
}
/**
* @dev Set submission flag for Claims queued during emergency pause.
* Set to true after EP is turned off and the claim is submitted .
*/
function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal {
claimPause[_index].submit = _submit;
}
/**
* @dev Sets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function setFirstClaimIndexToSubmitAfterEP(
uint _firstClaimIndexToSubmit
)
external
onlyInternal
{
claimPauseLastsubmit = _firstClaimIndexToSubmit;
}
/**
* @dev Sets the pending vote duration for a claim in case of emergency pause.
*/
function setPendingClaimDetails(
uint _claimId,
uint _pendingTime,
bool _voting
)
external
onlyInternal
{
claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting));
}
/**
* @dev Sets voting flag true after claim is reopened for voting after emergency pause.
*/
function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal {
claimPauseVotingEP[_claimId].voting = _vote;
}
/**
* @dev Sets the index from which claim needs to be
* reopened when emergency pause is swithched off.
*/
function setFirstClaimIndexToStartVotingAfterEP(
uint _claimStartVotingFirstIndex
)
external
onlyInternal
{
claimStartVotingFirstIndex = _claimStartVotingFirstIndex;
}
/**
* @dev Calls Vote Event.
*/
function callVoteEvent(
address _userAddress,
uint _claimId,
bytes4 _typeOf,
uint _tokens,
uint _submitDate,
int8 _verdict
)
external
onlyInternal
{
emit VoteCast(
_userAddress,
_claimId,
_typeOf,
_tokens,
_submitDate,
_verdict
);
}
/**
* @dev Calls Claim Event.
*/
function callClaimEvent(
uint _coverId,
address _userAddress,
uint _claimId,
uint _datesubmit
)
external
onlyInternal
{
emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit);
}
/**
* @dev Gets Uint Parameters by parameter code
* @param code whose details we want
* @return string value of the parameter
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "CAMAXVT") {
val = maxVotingTime / (1 hours);
} else if (code == "CAMINVT") {
val = minVotingTime / (1 hours);
} else if (code == "CAPRETRY") {
val = payoutRetryTime / (1 hours);
} else if (code == "CADEPT") {
val = claimDepositTime / (1 days);
} else if (code == "CAREWPER") {
val = claimRewardPerc;
} else if (code == "CAMINTH") {
val = minVoteThreshold;
} else if (code == "CAMAXTH") {
val = maxVoteThreshold;
} else if (code == "CACONPER") {
val = majorityConsensus;
} else if (code == "CAPAUSET") {
val = pauseDaysCA / (1 days);
}
}
/**
* @dev Get claim queued during emergency pause by index.
*/
function getClaimOfEmergencyPauseByIndex(
uint _index
)
external
view
returns (
uint coverId,
uint dateUpd,
bool submit
)
{
coverId = claimPause[_index].coverid;
dateUpd = claimPause[_index].dateUpd;
submit = claimPause[_index].submit;
}
/**
* @dev Gets the Claim's details of given claimid.
*/
function getAllClaimsByIndex(
uint _claimId
)
external
view
returns (
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the vote id of a given claim of a given Claim Assessor.
*/
function getUserClaimVoteCA(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteCA[_add][_claimId];
}
/**
* @dev Gets the vote id of a given claim of a given member.
*/
function getUserClaimVoteMember(
address _add,
uint _claimId
)
external
view
returns (uint idVote)
{
return userClaimVoteMember[_add][_claimId];
}
/**
* @dev Gets the count of all votes.
*/
function getAllVoteLength() external view returns (uint voteCount) {
return allvotes.length.sub(1); // Start Index always from 1.
}
/**
* @dev Gets the status number of a given claim.
* @param _claimId Claim id.
* @return statno Status Number.
*/
function getClaimStatusNumber(uint _claimId) external view returns (uint claimId, uint statno) {
return (_claimId, claimsStatus[_claimId]);
}
/**
* @dev Gets the reward percentage to be distributed for a given status id
* @param statusNumber the number of type of status
* @return percCA reward Percentage for claim assessor
* @return percMV reward Percentage for members
*/
function getRewardStatus(uint statusNumber) external view returns (uint percCA, uint percMV) {
return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV);
}
/**
* @dev Gets the number of tries that have been made for a successful payout of a Claim.
*/
function getClaimState12Count(uint _claimId) external view returns (uint num) {
num = claimState12Count[_claimId];
}
/**
* @dev Gets the last update date of a claim.
*/
function getClaimDateUpd(uint _claimId) external view returns (uint dateupd) {
dateupd = allClaims[_claimId].dateUpd;
}
/**
* @dev Gets all Claims created by a user till date.
* @param _member user's address.
* @return claimarr List of Claims id.
*/
function getAllClaimsByAddress(address _member) external view returns (uint[] memory claimarr) {
return allClaimsByAddress[_member];
}
/**
* @dev Gets the number of tokens that has been locked
* while giving vote to a claim by Claim Assessors.
* @param _claimId Claim Id.
* @return accept Total number of tokens when CA accepts the claim.
* @return deny Total number of tokens when CA declines the claim.
*/
function getClaimsTokenCA(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensCA[_claimId].accept,
claimTokensCA[_claimId].deny
);
}
/**
* @dev Gets the number of tokens that have been
* locked while assessing a claim as a member.
* @param _claimId Claim Id.
* @return accept Total number of tokens in acceptance of the claim.
* @return deny Total number of tokens against the claim.
*/
function getClaimsTokenMV(
uint _claimId
)
external
view
returns (
uint claimId,
uint accept,
uint deny
)
{
return (
_claimId,
claimTokensMV[_claimId].accept,
claimTokensMV[_claimId].deny
);
}
/**
* @dev Gets the total number of votes cast as Claims assessor for/against a given claim
*/
function getCaClaimVotesToken(uint _claimId) external view returns (uint claimId, uint cnt) {
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets the total number of tokens cast as a member for/against a given claim
*/
function getMemberClaimVotesToken(
uint _claimId
)
external
view
returns (uint claimId, uint cnt)
{
claimId = _claimId;
cnt = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @dev Provides information of a vote when given its vote id.
* @param _voteid Vote Id.
*/
function getVoteDetails(uint _voteid)
external view
returns (
uint tokens,
uint claimId,
int8 verdict,
bool rewardClaimed
)
{
return (
allvotes[_voteid].tokens,
allvotes[_voteid].claimId,
allvotes[_voteid].verdict,
allvotes[_voteid].rewardClaimed
);
}
/**
* @dev Gets the voter's address of a given vote id.
*/
function getVoterVote(uint _voteid) external view returns (address voter) {
return allvotes[_voteid].voter;
}
/**
* @dev Provides information of a Claim when given its claim id.
* @param _claimId Claim Id.
*/
function getClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint coverId,
int8 vote,
uint status,
uint dateUpd,
uint state12Count
)
{
return (
_claimId,
allClaims[_claimId].coverId,
claimVote[_claimId],
claimsStatus[_claimId],
allClaims[_claimId].dateUpd,
claimState12Count[_claimId]
);
}
/**
* @dev Gets the total number of votes of a given claim.
* @param _claimId Claim Id.
* @param _ca if 1: votes given by Claim Assessors to a claim,
* else returns the number of votes of given by Members to a claim.
* @return len total number of votes for/against a given claim.
*/
function getClaimVoteLength(
uint _claimId,
uint8 _ca
)
external
view
returns (uint claimId, uint len)
{
claimId = _claimId;
if (_ca == 1)
len = claimVoteCA[_claimId].length;
else
len = claimVoteMember[_claimId].length;
}
/**
* @dev Gets the verdict of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return ver 1 if vote was given in favour,-1 if given in against.
*/
function getVoteVerdict(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (int8 ver)
{
if (_ca == 1)
ver = allvotes[claimVoteCA[_claimId][_index]].verdict;
else
ver = allvotes[claimVoteMember[_claimId][_index]].verdict;
}
/**
* @dev Gets the Number of tokens of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return tok Number of tokens.
*/
function getVoteToken(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (uint tok)
{
if (_ca == 1)
tok = allvotes[claimVoteCA[_claimId][_index]].tokens;
else
tok = allvotes[claimVoteMember[_claimId][_index]].tokens;
}
/**
* @dev Gets the Voter's address of a vote using claim id and index.
* @param _ca 1 for vote given as a CA, else for vote given as a member.
* @return voter Voter's address.
*/
function getVoteVoter(
uint _claimId,
uint _index,
uint8 _ca
)
external
view
returns (address voter)
{
if (_ca == 1)
voter = allvotes[claimVoteCA[_claimId][_index]].voter;
else
voter = allvotes[claimVoteMember[_claimId][_index]].voter;
}
/**
* @dev Gets total number of Claims created by a user till date.
* @param _add User's address.
*/
function getUserClaimCount(address _add) external view returns (uint len) {
len = allClaimsByAddress[_add].length;
}
/**
* @dev Calculates number of Claims that are in pending state.
*/
function getClaimLength() external view returns (uint len) {
len = allClaims.length.sub(pendingClaimStart);
}
/**
* @dev Gets the Number of all the Claims created till date.
*/
function actualClaimLength() external view returns (uint len) {
len = allClaims.length;
}
/**
* @dev Gets details of a claim.
* @param _index claim id = pending claim start + given index
* @param _add User's address.
* @return coverid cover against which claim has been submitted.
* @return claimId Claim Id.
* @return voteCA verdict of vote given as a Claim Assessor.
* @return voteMV verdict of vote given as a Member.
* @return statusnumber Status of claim.
*/
function getClaimFromNewStart(
uint _index,
address _add
)
external
view
returns (
uint coverid,
uint claimId,
int8 voteCA,
int8 voteMV,
uint statusnumber
)
{
uint i = pendingClaimStart.add(_index);
coverid = allClaims[i].coverId;
claimId = i;
if (userClaimVoteCA[_add][i] > 0)
voteCA = allvotes[userClaimVoteCA[_add][i]].verdict;
else
voteCA = 0;
if (userClaimVoteMember[_add][i] > 0)
voteMV = allvotes[userClaimVoteMember[_add][i]].verdict;
else
voteMV = 0;
statusnumber = claimsStatus[i];
}
/**
* @dev Gets details of a claim of a user at a given index.
*/
function getUserClaimByIndex(
uint _index,
address _add
)
external
view
returns (
uint status,
uint coverid,
uint claimId
)
{
claimId = allClaimsByAddress[_add][_index];
status = claimsStatus[claimId];
coverid = allClaims[claimId].coverId;
}
/**
* @dev Gets Id of all the votes given to a claim.
* @param _claimId Claim Id.
* @return ca id of all the votes given by Claim assessors to a claim.
* @return mv id of all the votes given by members to a claim.
*/
function getAllVotesForClaim(
uint _claimId
)
external
view
returns (
uint claimId,
uint[] memory ca,
uint[] memory mv
)
{
return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]);
}
/**
* @dev Gets Number of tokens deposit in a vote using
* Claim assessor's address and claim id.
* @return tokens Number of deposited tokens.
*/
function getTokensClaim(
address _of,
uint _claimId
)
external
view
returns (
uint claimId,
uint tokens
)
{
return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens);
}
/**
* @param _voter address of the voter.
* @return lastCAvoteIndex last index till which reward was distributed for CA
* @return lastMVvoteIndex last index till which reward was distributed for member
*/
function getRewardDistributedIndex(
address _voter
)
external
view
returns (
uint lastCAvoteIndex,
uint lastMVvoteIndex
)
{
return (
voterVoteRewardReceived[_voter].lastCAvoteIndex,
voterVoteRewardReceived[_voter].lastMVvoteIndex
);
}
/**
* @param claimid claim id.
* @return perc_CA reward Percentage for claim assessor
* @return perc_MV reward Percentage for members
* @return tokens total tokens to be rewarded
*/
function getClaimRewardDetail(
uint claimid
)
external
view
returns (
uint percCA,
uint percMV,
uint tokens
)
{
return (
claimRewardDetail[claimid].percCA,
claimRewardDetail[claimid].percMV,
claimRewardDetail[claimid].tokenToBeDist
);
}
/**
* @dev Gets cover id of a claim.
*/
function getClaimCoverId(uint _claimId) external view returns (uint claimId, uint coverid) {
return (_claimId, allClaims[_claimId].coverId);
}
/**
* @dev Gets total number of tokens staked during voting by Claim Assessors.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter).
*/
function getClaimVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteCA[_claimId].length; i++) {
if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens);
}
}
/**
* @dev Gets total number of tokens staked during voting by Members.
* @param _claimId Claim Id.
* @param _verdict 1 to get total number of accept tokens,
* -1 to get total number of deny tokens.
* @return token token Number of tokens(either accept or
* deny on the basis of verdict given as parameter).
*/
function getClaimMVote(uint _claimId, int8 _verdict) external view returns (uint claimId, uint token) {
claimId = _claimId;
token = 0;
for (uint i = 0; i < claimVoteMember[_claimId].length; i++) {
if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict)
token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens);
}
}
/**
* @param _voter address of voteid
* @param index index to get voteid in CA
*/
function getVoteAddressCA(address _voter, uint index) external view returns (uint) {
return voteAddressCA[_voter][index];
}
/**
* @param _voter address of voter
* @param index index to get voteid in member vote
*/
function getVoteAddressMember(address _voter, uint index) external view returns (uint) {
return voteAddressMember[_voter][index];
}
/**
* @param _voter address of voter
*/
function getVoteAddressCALength(address _voter) external view returns (uint) {
return voteAddressCA[_voter].length;
}
/**
* @param _voter address of voter
*/
function getVoteAddressMemberLength(address _voter) external view returns (uint) {
return voteAddressMember[_voter].length;
}
/**
* @dev Gets the Final result of voting of a claim.
* @param _claimId Claim id.
* @return verdict 1 if claim is accepted, -1 if declined.
*/
function getFinalVerdict(uint _claimId) external view returns (int8 verdict) {
return claimVote[_claimId];
}
/**
* @dev Get number of Claims queued for submission during emergency pause.
*/
function getLengthOfClaimSubmittedAtEP() external view returns (uint len) {
len = claimPause.length;
}
/**
* @dev Gets the index from which claim needs to be
* submitted when emergency pause is swithched off.
*/
function getFirstClaimIndexToSubmitAfterEP() external view returns (uint indexToSubmit) {
indexToSubmit = claimPauseLastsubmit;
}
/**
* @dev Gets number of Claims to be reopened for voting post emergency pause period.
*/
function getLengthOfClaimVotingPause() external view returns (uint len) {
len = claimPauseVotingEP.length;
}
/**
* @dev Gets claim details to be reopened for voting after emergency pause.
*/
function getPendingClaimDetailsByIndex(
uint _index
)
external
view
returns (
uint claimId,
uint pendingTime,
bool voting
)
{
claimId = claimPauseVotingEP[_index].claimid;
pendingTime = claimPauseVotingEP[_index].pendingTime;
voting = claimPauseVotingEP[_index].voting;
}
/**
* @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off.
*/
function getFirstClaimIndexToStartVotingAfterEP() external view returns (uint firstindex) {
firstindex = claimStartVotingFirstIndex;
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "CAMAXVT") {
_setMaxVotingTime(val * 1 hours);
} else if (code == "CAMINVT") {
_setMinVotingTime(val * 1 hours);
} else if (code == "CAPRETRY") {
_setPayoutRetryTime(val * 1 hours);
} else if (code == "CADEPT") {
_setClaimDepositTime(val * 1 days);
} else if (code == "CAREWPER") {
_setClaimRewardPerc(val);
} else if (code == "CAMINTH") {
_setMinVoteThreshold(val);
} else if (code == "CAMAXTH") {
_setMaxVoteThreshold(val);
} else if (code == "CACONPER") {
_setMajorityConsensus(val);
} else if (code == "CAPAUSET") {
_setPauseDaysCA(val * 1 days);
} else {
revert("Invalid param code");
}
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {}
/**
* @dev Adds status under which a claim can lie.
* @param percCA reward percentage for claim assessor
* @param percMV reward percentage for members
*/
function _pushStatus(uint percCA, uint percMV) internal {
rewardStatus.push(ClaimRewardStatus(percCA, percMV));
}
/**
* @dev adds reward incentive for all possible claim status for Claim assessors and members
*/
function _addRewardIncentive() internal {
_pushStatus(0, 0); // 0 Pending-Claim Assessor Vote
_pushStatus(0, 0); // 1 Pending-Claim Assessor Vote Denied, Pending Member Vote
_pushStatus(0, 0); // 2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote
_pushStatus(0, 0); // 3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote
_pushStatus(0, 0); // 4 Pending-CA Consensus not reached Accept, Pending Member Vote
_pushStatus(0, 0); // 5 Pending-CA Consensus not reached Deny, Pending Member Vote
_pushStatus(100, 0); // 6 Final-Claim Assessor Vote Denied
_pushStatus(100, 0); // 7 Final-Claim Assessor Vote Accepted
_pushStatus(0, 100); // 8 Final-Claim Assessor Vote Denied, MV Accepted
_pushStatus(0, 100); // 9 Final-Claim Assessor Vote Denied, MV Denied
_pushStatus(0, 0); // 10 Final-Claim Assessor Vote Accept, MV Nodecision
_pushStatus(0, 0); // 11 Final-Claim Assessor Vote Denied, MV Nodecision
_pushStatus(0, 0); // 12 Claim Accepted Payout Pending
_pushStatus(0, 0); // 13 Claim Accepted No Payout
_pushStatus(0, 0); // 14 Claim Accepted Payout Done
}
/**
* @dev Sets Maximum time(in seconds) for which claim assessment voting is open
*/
function _setMaxVotingTime(uint _time) internal {
maxVotingTime = _time;
}
/**
* @dev Sets Minimum time(in seconds) for which claim assessment voting is open
*/
function _setMinVotingTime(uint _time) internal {
minVotingTime = _time;
}
/**
* @dev Sets Minimum vote threshold required
*/
function _setMinVoteThreshold(uint val) internal {
minVoteThreshold = val;
}
/**
* @dev Sets Maximum vote threshold required
*/
function _setMaxVoteThreshold(uint val) internal {
maxVoteThreshold = val;
}
/**
* @dev Sets the value considered as Majority Consenus in voting
*/
function _setMajorityConsensus(uint val) internal {
majorityConsensus = val;
}
/**
* @dev Sets the payout retry time
*/
function _setPayoutRetryTime(uint _time) internal {
payoutRetryTime = _time;
}
/**
* @dev Sets percentage of reward given for claim assessment
*/
function _setClaimRewardPerc(uint _val) internal {
claimRewardPerc = _val;
}
/**
* @dev Sets the time for which claim is deposited.
*/
function _setClaimDepositTime(uint _time) internal {
claimDepositTime = _time;
}
/**
* @dev Sets number of days claim assessment will be paused
*/
function _setPauseDaysCA(uint val) internal {
pauseDaysCA = val;
}
}
pragma solidity ^0.5.0;
/**
* @title ERC1132 interface
* @dev see https://github.com/ethereum/EIPs/issues/1132
*/
contract LockHandler {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => bytes32[]) public lockReason;
/**
* @dev locked token structure
*/
struct LockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(bytes32 => LockToken)) public locked;
}
pragma solidity ^0.5.0;
interface LegacyMCR {
function addMCRData(uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate) external;
function addLastMCRData(uint64 date) external;
function changeDependentContractAddress() external;
function getAllSumAssurance() external view returns (uint amount);
function _calVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function calculateStepTokenPrice(bytes4 curr, uint mcrtp) external view returns (uint tokenPrice);
function calculateTokenPrice(bytes4 curr) external view returns (uint tokenPrice);
function calVtpAndMCRtp() external view returns (uint vtp, uint mcrtp);
function calculateVtpAndMCRtp(uint poolBalance) external view returns (uint vtp, uint mcrtp);
function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) external view returns (uint lowerThreshold, uint upperThreshold);
function getMaxSellTokens() external view returns (uint maxTokens);
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val);
function updateUintParameters(bytes8 code, uint val) external;
function variableMincap() external view returns (uint);
function dynamicMincapThresholdx100() external view returns (uint);
function dynamicMincapIncrementx100() external view returns (uint);
function getLastMCREther() external view returns (uint);
}
// /* Copyright (C) 2017 GovBlocks.io
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../token/TokenController.sol";
import "./MemberRoles.sol";
import "./ProposalCategory.sol";
import "./external/IGovernance.sol";
contract Governance is IGovernance, Iupgradable {
using SafeMath for uint;
enum ProposalStatus {
Draft,
AwaitingSolution,
VotingStarted,
Accepted,
Rejected,
Majority_Not_Reached_But_Accepted,
Denied
}
struct ProposalData {
uint propStatus;
uint finalVerdict;
uint category;
uint commonIncentive;
uint dateUpd;
address owner;
}
struct ProposalVote {
address voter;
uint proposalId;
uint dateAdd;
}
struct VoteTally {
mapping(uint => uint) memberVoteValue;
mapping(uint => uint) abVoteValue;
uint voters;
}
struct DelegateVote {
address follower;
address leader;
uint lastUpd;
}
ProposalVote[] internal allVotes;
DelegateVote[] public allDelegation;
mapping(uint => ProposalData) internal allProposalData;
mapping(uint => bytes[]) internal allProposalSolutions;
mapping(address => uint[]) internal allVotesByMember;
mapping(uint => mapping(address => bool)) public rewardClaimed;
mapping(address => mapping(uint => uint)) public memberProposalVote;
mapping(address => uint) public followerDelegation;
mapping(address => uint) internal followerCount;
mapping(address => uint[]) internal leaderDelegation;
mapping(uint => VoteTally) public proposalVoteTally;
mapping(address => bool) public isOpenForDelegation;
mapping(address => uint) public lastRewardClaimed;
bool internal constructorCheck;
uint public tokenHoldingTime;
uint internal roleIdAllowedToCatgorize;
uint internal maxVoteWeigthPer;
uint internal specialResolutionMajPerc;
uint internal maxFollowers;
uint internal totalProposals;
uint internal maxDraftTime;
MemberRoles internal memberRole;
ProposalCategory internal proposalCategory;
TokenController internal tokenInstance;
mapping(uint => uint) public proposalActionStatus;
mapping(uint => uint) internal proposalExecutionTime;
mapping(uint => mapping(address => bool)) public proposalRejectedByAB;
mapping(uint => uint) internal actionRejectedCount;
bool internal actionParamsInitialised;
uint internal actionWaitingTime;
uint constant internal AB_MAJ_TO_REJECT_ACTION = 3;
enum ActionStatus {
Pending,
Accepted,
Rejected,
Executed,
NoAction
}
/**
* @dev Called whenever an action execution is failed.
*/
event ActionFailed (
uint256 proposalId
);
/**
* @dev Called whenever an AB member rejects the action execution.
*/
event ActionRejected (
uint256 indexed proposalId,
address rejectedBy
);
/**
* @dev Checks if msg.sender is proposal owner
*/
modifier onlyProposalOwner(uint _proposalId) {
require(msg.sender == allProposalData[_proposalId].owner, "Not allowed");
_;
}
/**
* @dev Checks if proposal is opened for voting
*/
modifier voteNotStarted(uint _proposalId) {
require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted));
_;
}
/**
* @dev Checks if msg.sender is allowed to create proposal under given category
*/
modifier isAllowed(uint _categoryId) {
require(allowedToCreateProposal(_categoryId), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender is allowed categorize proposal under given category
*/
modifier isAllowedToCategorize() {
require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed");
_;
}
/**
* @dev Checks if msg.sender had any pending rewards to be claimed
*/
modifier checkPendingRewards {
require(getPendingReward(msg.sender) == 0, "Claim reward");
_;
}
/**
* @dev Event emitted whenever a proposal is categorized
*/
event ProposalCategorized(
uint indexed proposalId,
address indexed categorizedBy,
uint categoryId
);
/**
* @dev Removes delegation of an address.
* @param _add address to undelegate.
*/
function removeDelegation(address _add) external onlyInternal {
_unDelegate(_add);
}
/**
* @dev Creates a new proposal
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
*/
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external isAllowed(_categoryId)
{
require(ms.isMember(msg.sender), "Not Member");
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
}
/**
* @dev Edits the details of an existing proposal
* @param _proposalId Proposal id that details needs to be updated
* @param _proposalDescHash Proposal description hash having long and short description of proposal.
*/
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external onlyProposalOwner(_proposalId)
{
require(
allProposalSolutions[_proposalId].length < 2,
"Not allowed"
);
allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft);
allProposalData[_proposalId].category = 0;
allProposalData[_proposalId].commonIncentive = 0;
emit Proposal(
allProposalData[_proposalId].owner,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
}
/**
* @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
*/
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
external
voteNotStarted(_proposalId) isAllowedToCategorize
{
_categorizeProposal(_proposalId, _categoryId, _incentive);
}
/**
* @dev Submit proposal with solution
* @param _proposalId Proposal id
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external
onlyProposalOwner(_proposalId)
{
require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution));
_proposalSubmission(_proposalId, _solutionHash, _action);
}
/**
* @dev Creates a new proposal with solution
* @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
* @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
* @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
*/
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external isAllowed(_categoryId)
{
uint proposalId = totalProposals;
_createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId);
require(_categoryId > 0);
_proposalSubmission(
proposalId,
_solutionHash,
_action
);
}
/**
* @dev Submit a vote on the proposal.
* @param _proposalId to vote upon.
* @param _solutionChosen is the chosen vote.
*/
function submitVote(uint _proposalId, uint _solutionChosen) external {
require(allProposalData[_proposalId].propStatus ==
uint(Governance.ProposalStatus.VotingStarted), "Not allowed");
require(_solutionChosen < allProposalSolutions[_proposalId].length);
_submitVote(_proposalId, _solutionChosen);
}
/**
* @dev Closes the proposal.
* @param _proposalId of proposal to be closed.
*/
function closeProposal(uint _proposalId) external {
uint category = allProposalData[_proposalId].category;
uint _memberRole;
if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now &&
allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
} else {
require(canCloseProposal(_proposalId) == 1);
(, _memberRole,,,,,) = proposalCategory.category(allProposalData[_proposalId].category);
if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) {
_closeAdvisoryBoardVote(_proposalId, category);
} else {
_closeMemberVote(_proposalId, category);
}
}
}
/**
* @dev Claims reward for member.
* @param _memberAddress to claim reward of.
* @param _maxRecords maximum number of records to claim reward for.
_proposals list of proposals of which reward will be claimed.
* @return amount of pending reward.
*/
function claimReward(address _memberAddress, uint _maxRecords)
external returns (uint pendingDAppReward)
{
uint voteId;
address leader;
uint lastUpd;
require(msg.sender == ms.getLatestAddress("CR"));
uint delegationId = followerDelegation[_memberAddress];
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
uint totalVotes = allVotesByMember[leader].length;
uint lastClaimed = totalVotes;
uint j;
uint i;
for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) {
voteId = allVotesByMember[leader][i];
proposalId = allVotes[voteId].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) {
if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) {
if (!rewardClaimed[voteId][_memberAddress]) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
rewardClaimed[voteId][_memberAddress] = true;
j++;
}
} else {
if (lastClaimed == totalVotes) {
lastClaimed = i;
}
}
}
}
if (lastClaimed == totalVotes) {
lastRewardClaimed[_memberAddress] = i;
} else {
lastRewardClaimed[_memberAddress] = lastClaimed;
}
if (j > 0) {
emit RewardClaimed(
_memberAddress,
pendingDAppReward
);
}
}
/**
* @dev Sets delegation acceptance status of individual user
* @param _status delegation acceptance status
*/
function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards {
isOpenForDelegation[msg.sender] = _status;
}
/**
* @dev Delegates vote to an address.
* @param _add is the address to delegate vote to.
*/
function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards {
require(ms.masterInitialized());
require(allDelegation[followerDelegation[_add]].leader == address(0));
if (followerDelegation[msg.sender] > 0) {
require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now);
}
require(!alreadyDelegated(msg.sender));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner)));
require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)));
require(followerCount[_add] < maxFollowers);
if (allVotesByMember[msg.sender].length > 0) {
require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime)
< now);
}
require(ms.isMember(_add));
require(isOpenForDelegation[_add]);
allDelegation.push(DelegateVote(msg.sender, _add, now));
followerDelegation[msg.sender] = allDelegation.length - 1;
leaderDelegation[_add].push(allDelegation.length - 1);
followerCount[_add]++;
lastRewardClaimed[msg.sender] = allVotesByMember[_add].length;
}
/**
* @dev Undelegates the sender
*/
function unDelegate() external isMemberAndcheckPause checkPendingRewards {
_unDelegate(msg.sender);
}
/**
* @dev Triggers action of accepted proposal after waiting time is finished
*/
function triggerAction(uint _proposalId) external {
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger");
_triggerAction(_proposalId, allProposalData[_proposalId].category);
}
/**
* @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious
*/
function rejectAction(uint _proposalId) external {
require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now);
require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted));
require(!proposalRejectedByAB[_proposalId][msg.sender]);
require(
keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category))
!= keccak256(abi.encodeWithSignature("swapABMember(address,address)"))
);
proposalRejectedByAB[_proposalId][msg.sender] = true;
actionRejectedCount[_proposalId]++;
emit ActionRejected(_proposalId, msg.sender);
if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) {
proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected);
}
}
/**
* @dev Sets intial actionWaitingTime value
* To be called after governance implementation has been updated
*/
function setInitialActionParameters() external onlyOwner {
require(!actionParamsInitialised);
actionParamsInitialised = true;
actionWaitingTime = 24 * 1 hours;
}
/**
* @dev Gets Uint Parameters of a code
* @param code whose details we want
* @return string value of the code
* @return associated amount (time or perc or value) to the code
*/
function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) {
codeVal = code;
if (code == "GOVHOLD") {
val = tokenHoldingTime / (1 days);
} else if (code == "MAXFOL") {
val = maxFollowers;
} else if (code == "MAXDRFT") {
val = maxDraftTime / (1 days);
} else if (code == "EPTIME") {
val = ms.pauseTime() / (1 days);
} else if (code == "ACWT") {
val = actionWaitingTime / (1 hours);
}
}
/**
* @dev Gets all details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return category
* @return status
* @return finalVerdict
* @return totalReward
*/
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalRewar
)
{
return (
_proposalId,
allProposalData[_proposalId].category,
allProposalData[_proposalId].propStatus,
allProposalData[_proposalId].finalVerdict,
allProposalData[_proposalId].commonIncentive
);
}
/**
* @dev Gets some details of a propsal
* @param _proposalId whose details we want
* @return proposalId
* @return number of all proposal solutions
* @return amount of votes
*/
function proposalDetails(uint _proposalId) external view returns (uint, uint, uint) {
return (
_proposalId,
allProposalSolutions[_proposalId].length,
proposalVoteTally[_proposalId].voters
);
}
/**
* @dev Gets solution action on a proposal
* @param _proposalId whose details we want
* @param _solution whose details we want
* @return action of a solution on a proposal
*/
function getSolutionAction(uint _proposalId, uint _solution) external view returns (uint, bytes memory) {
return (
_solution,
allProposalSolutions[_proposalId][_solution]
);
}
/**
* @dev Gets length of propsal
* @return length of propsal
*/
function getProposalLength() external view returns (uint) {
return totalProposals;
}
/**
* @dev Get followers of an address
* @return get followers of an address
*/
function getFollowers(address _add) external view returns (uint[] memory) {
return leaderDelegation[_add];
}
/**
* @dev Gets pending rewards of a member
* @param _memberAddress in concern
* @return amount of pending reward
*/
function getPendingReward(address _memberAddress)
public view returns (uint pendingDAppReward)
{
uint delegationId = followerDelegation[_memberAddress];
address leader;
uint lastUpd;
DelegateVote memory delegationData = allDelegation[delegationId];
if (delegationId > 0 && delegationData.leader != address(0)) {
leader = delegationData.leader;
lastUpd = delegationData.lastUpd;
} else
leader = _memberAddress;
uint proposalId;
for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) {
if (allVotes[allVotesByMember[leader][i]].dateAdd > (
lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) {
if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) {
proposalId = allVotes[allVotesByMember[leader][i]].proposalId;
if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus
> uint(ProposalStatus.VotingStarted)) {
pendingDAppReward = pendingDAppReward.add(
allProposalData[proposalId].commonIncentive.div(
proposalVoteTally[proposalId].voters
)
);
}
}
}
}
}
/**
* @dev Updates Uint Parameters of a code
* @param code whose details we want to update
* @param val value to set
*/
function updateUintParameters(bytes8 code, uint val) public {
require(ms.checkIsAuthToGoverned(msg.sender));
if (code == "GOVHOLD") {
tokenHoldingTime = val * 1 days;
} else if (code == "MAXFOL") {
maxFollowers = val;
} else if (code == "MAXDRFT") {
maxDraftTime = val * 1 days;
} else if (code == "EPTIME") {
ms.updatePauseTime(val * 1 days);
} else if (code == "ACWT") {
actionWaitingTime = val * 1 hours;
} else {
revert("Invalid code");
}
}
/**
* @dev Updates all dependency addresses to latest ones from Master
*/
function changeDependentContractAddress() public {
tokenInstance = TokenController(ms.dAppLocker());
memberRole = MemberRoles(ms.getLatestAddress("MR"));
proposalCategory = ProposalCategory(ms.getLatestAddress("PC"));
}
/**
* @dev Checks if msg.sender is allowed to create a proposal under given category
*/
function allowedToCreateProposal(uint category) public view returns (bool check) {
if (category == 0)
return true;
uint[] memory mrAllowed;
(,,,, mrAllowed,,) = proposalCategory.category(category);
for (uint i = 0; i < mrAllowed.length; i++) {
if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i]))
return true;
}
}
/**
* @dev Checks if an address is already delegated
* @param _add in concern
* @return bool value if the address is delegated or not
*/
function alreadyDelegated(address _add) public view returns (bool delegated) {
for (uint i = 0; i < leaderDelegation[_add].length; i++) {
if (allDelegation[leaderDelegation[_add][i]].leader == _add) {
return true;
}
}
}
/**
* @dev Checks If the proposal voting time is up and it's ready to close
* i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise!
* @param _proposalId Proposal id to which closing value is being checked
*/
function canCloseProposal(uint _proposalId)
public
view
returns (uint)
{
uint dateUpdate;
uint pStatus;
uint _closingTime;
uint _roleId;
uint majority;
pStatus = allProposalData[_proposalId].propStatus;
dateUpdate = allProposalData[_proposalId].dateUpd;
(, _roleId, majority, , , _closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
if (
pStatus == uint(ProposalStatus.VotingStarted)
) {
uint numberOfMembers = memberRole.numberOfMembers(_roleId);
if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority
|| proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers
|| dateUpdate.add(_closingTime) <= now) {
return 1;
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters
|| dateUpdate.add(_closingTime) <= now)
return 1;
}
} else if (pStatus > uint(ProposalStatus.VotingStarted)) {
return 2;
} else {
return 0;
}
}
/**
* @dev Gets Id of member role allowed to categorize the proposal
* @return roleId allowed to categorize the proposal
*/
function allowedToCatgorize() public view returns (uint roleId) {
return roleIdAllowedToCatgorize;
}
/**
* @dev Gets vote tally data
* @param _proposalId in concern
* @param _solution of a proposal id
* @return member vote value
* @return advisory board vote value
* @return amount of votes
*/
function voteTallyData(uint _proposalId, uint _solution) public view returns (uint, uint, uint) {
return (proposalVoteTally[_proposalId].memberVoteValue[_solution],
proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters);
}
/**
* @dev Internal call to create proposal
* @param _proposalTitle of proposal
* @param _proposalSD is short description of proposal
* @param _proposalDescHash IPFS hash value of propsal
* @param _categoryId of proposal
*/
function _createProposal(
string memory _proposalTitle,
string memory _proposalSD,
string memory _proposalDescHash,
uint _categoryId
)
internal
{
require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0);
uint _proposalId = totalProposals;
allProposalData[_proposalId].owner = msg.sender;
allProposalData[_proposalId].dateUpd = now;
allProposalSolutions[_proposalId].push("");
totalProposals++;
emit Proposal(
msg.sender,
_proposalId,
now,
_proposalTitle,
_proposalSD,
_proposalDescHash
);
if (_categoryId > 0)
_categorizeProposal(_proposalId, _categoryId, 0);
}
/**
* @dev Internal call to categorize a proposal
* @param _proposalId of proposal
* @param _categoryId of proposal
* @param _incentive is commonIncentive
*/
function _categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentive
)
internal
{
require(
_categoryId > 0 && _categoryId < proposalCategory.totalCategories(),
"Invalid category"
);
allProposalData[_proposalId].category = _categoryId;
allProposalData[_proposalId].commonIncentive = _incentive;
allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution);
emit ProposalCategorized(_proposalId, msg.sender, _categoryId);
}
/**
* @dev Internal call to add solution to a proposal
* @param _proposalId in concern
* @param _action on that solution
* @param _solutionHash string value
*/
function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash)
internal
{
allProposalSolutions[_proposalId].push(_action);
emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now);
}
/**
* @dev Internal call to add solution and open proposal for voting
*/
function _proposalSubmission(
uint _proposalId,
string memory _solutionHash,
bytes memory _action
)
internal
{
uint _categoryId = allProposalData[_proposalId].category;
if (proposalCategory.categoryActionHashes(_categoryId).length == 0) {
require(keccak256(_action) == keccak256(""));
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
_addSolution(
_proposalId,
_action,
_solutionHash
);
_updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted));
(, , , , , uint closingTime,) = proposalCategory.category(_categoryId);
emit CloseProposalOnTime(_proposalId, closingTime.add(now));
}
/**
* @dev Internal call to submit vote
* @param _proposalId of proposal in concern
* @param _solution for that proposal
*/
function _submitVote(uint _proposalId, uint _solution) internal {
uint delegationId = followerDelegation[msg.sender];
uint mrSequence;
uint majority;
uint closingTime;
(, mrSequence, majority, , , closingTime,) = proposalCategory.category(allProposalData[_proposalId].category);
require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed");
require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed");
require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) &&
_checkLastUpd(allDelegation[delegationId].lastUpd)));
require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized");
uint totalVotes = allVotes.length;
allVotesByMember[msg.sender].push(totalVotes);
memberProposalVote[msg.sender][_proposalId] = totalVotes;
allVotes.push(ProposalVote(msg.sender, _proposalId, now));
emit Vote(msg.sender, _proposalId, totalVotes, now, _solution);
if (mrSequence == uint(MemberRoles.Role.Owner)) {
if (_solution == 1)
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner);
else
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
} else {
uint numberOfMembers = memberRole.numberOfMembers(mrSequence);
_setVoteTally(_proposalId, _solution, mrSequence);
if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers)
>= majority
|| (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) {
emit VoteCast(_proposalId);
}
} else {
if (numberOfMembers == proposalVoteTally[_proposalId].voters)
emit VoteCast(_proposalId);
}
}
}
/**
* @dev Internal call to set vote tally of a proposal
* @param _proposalId of proposal in concern
* @param _solution of proposal in concern
* @param mrSequence number of members for a role
*/
function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal
{
uint categoryABReq;
uint isSpecialResolution;
(, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category);
if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) ||
mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) {
proposalVoteTally[_proposalId].abVoteValue[_solution]++;
}
tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime);
if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) {
uint voteWeight;
uint voters = 1;
uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender);
uint totalSupply = tokenInstance.totalSupply();
if (isSpecialResolution == 1) {
voteWeight = tokenBalance.add(10 ** 18);
} else {
voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18);
}
DelegateVote memory delegationData;
for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) {
delegationData = allDelegation[leaderDelegation[msg.sender][i]];
if (delegationData.leader == msg.sender &&
_checkLastUpd(delegationData.lastUpd)) {
if (memberRole.checkRole(delegationData.follower, mrSequence)) {
tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower);
tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime);
voters++;
if (isSpecialResolution == 1) {
voteWeight = voteWeight.add(tokenBalance.add(10 ** 18));
} else {
voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10 ** 18));
}
}
}
}
proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight);
proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters;
}
}
/**
* @dev Gets minimum of two numbers
* @param a one of the two numbers
* @param b one of the two numbers
* @return minimum number out of the two
*/
function _minOf(uint a, uint b) internal pure returns (uint res) {
res = a;
if (res > b)
res = b;
}
/**
* @dev Check the time since last update has exceeded token holding time or not
* @param _lastUpd is last update time
* @return the bool which tells if the time since last update has exceeded token holding time or not
*/
function _checkLastUpd(uint _lastUpd) internal view returns (bool) {
return (now - _lastUpd) > tokenHoldingTime;
}
/**
* @dev Checks if the vote count against any solution passes the threshold value or not.
*/
function _checkForThreshold(uint _proposalId, uint _category) internal view returns (bool check) {
uint categoryQuorumPerc;
uint roleAuthorized;
(, roleAuthorized, , categoryQuorumPerc, , ,) = proposalCategory.category(_category);
check = ((proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1]))
.mul(100))
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18)
)
) >= categoryQuorumPerc;
}
/**
* @dev Called when vote majority is reached
* @param _proposalId of proposal in concern
* @param _status of proposal in concern
* @param category of proposal in concern
* @param max vote value of proposal in concern
*/
function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal {
allProposalData[_proposalId].finalVerdict = max;
_updateProposalStatus(_proposalId, _status);
emit ProposalAccepted(_proposalId);
if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) {
if (role == MemberRoles.Role.AdvisoryBoard) {
_triggerAction(_proposalId, category);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
proposalExecutionTime[_proposalId] = actionWaitingTime.add(now);
}
}
}
/**
* @dev Internal function to trigger action of accepted proposal
*/
function _triggerAction(uint _proposalId, uint _categoryId) internal {
proposalActionStatus[_proposalId] = uint(ActionStatus.Executed);
bytes2 contractName;
address actionAddress;
bytes memory _functionHash;
(, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId);
if (contractName == "MS") {
actionAddress = address(ms);
} else if (contractName != "EX") {
actionAddress = ms.getLatestAddress(contractName);
}
// solhint-disable-next-line avoid-low-level-calls
(bool actionStatus,) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1]));
if (actionStatus) {
emit ActionSuccess(_proposalId);
} else {
proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted);
emit ActionFailed(_proposalId);
}
}
/**
* @dev Internal call to update proposal status
* @param _proposalId of proposal in concern
* @param _status of proposal to set
*/
function _updateProposalStatus(uint _proposalId, uint _status) internal {
if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) {
proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction);
}
allProposalData[_proposalId].dateUpd = now;
allProposalData[_proposalId].propStatus = _status;
}
/**
* @dev Internal call to undelegate a follower
* @param _follower is address of follower to undelegate
*/
function _unDelegate(address _follower) internal {
uint followerId = followerDelegation[_follower];
if (followerId > 0) {
followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1);
allDelegation[followerId].leader = address(0);
allDelegation[followerId].lastUpd = now;
lastRewardClaimed[_follower] = allVotesByMember[_follower].length;
}
}
/**
* @dev Internal call to close member voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeMemberVote(uint _proposalId, uint category) internal {
uint isSpecialResolution;
uint abMaj;
(, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category);
if (isSpecialResolution == 1) {
uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)
.div(
tokenInstance.totalSupply().add(
memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10 ** 18)
));
if (acceptedVotePerc >= specialResolutionMajPerc) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
} else {
if (_checkForThreshold(_proposalId, category)) {
uint majorityVote;
(,, majorityVote,,,,) = proposalCategory.category(category);
if (
((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100))
.div(proposalVoteTally[_proposalId].memberVoteValue[0]
.add(proposalVoteTally[_proposalId].memberVoteValue[1])
))
>= majorityVote
) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected));
}
} else {
if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
if (proposalVoteTally[_proposalId].voters > 0) {
tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive);
}
}
/**
* @dev Internal call to close advisory board voting
* @param _proposalId of proposal in concern
* @param category of proposal in concern
*/
function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal {
uint _majorityVote;
MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard;
(,, _majorityVote,,,,) = proposalCategory.category(category);
if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100)
.div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) {
_callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId);
} else {
_updateProposalStatus(_proposalId, uint(ProposalStatus.Denied));
}
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../../abstract/MasterAware.sol";
import "../cover/QuotationData.sol";
import "./NXMToken.sol";
import "./TokenController.sol";
import "./TokenData.sol";
contract TokenFunctions is MasterAware {
using SafeMath for uint;
TokenController public tc;
NXMToken public tk;
QuotationData public qd;
event BurnCATokens(uint claimId, address addr, uint amount);
/**
* @dev to get the all the cover locked tokens of a user
* @param _of is the user address in concern
* @return amount locked
*/
function getUserAllLockedCNTokens(address _of) external view returns (uint) {
uint[] memory coverIds = qd.getAllCoversOfUser(_of);
uint total;
for (uint i = 0; i < coverIds.length; i++) {
bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverIds[i]));
uint coverNote = tc.tokensLocked(_of, reason);
total = total.add(coverNote);
}
return total;
}
/**
* @dev Change Dependent Contract Address
*/
function changeDependentContractAddress() public {
tc = TokenController(master.getLatestAddress("TC"));
tk = NXMToken(master.tokenAddress());
qd = QuotationData(master.getLatestAddress("QD"));
}
/**
* @dev Burns tokens used for fraudulent voting against a claim
* @param claimid Claim Id.
* @param _value number of tokens to be burned
* @param _of Claim Assessor's address.
*/
function burnCAToken(uint claimid, uint _value, address _of) external onlyGovernance {
tc.burnLockedTokens(_of, "CLA", _value);
emit BurnCATokens(claimid, _of, _value);
}
/**
* @dev to check if a member is locked for member vote
* @param _of is the member address in concern
* @return the boolean status
*/
function isLockedForMemberVote(address _of) public view returns (bool) {
return now < tk.isLockedForMV(_of);
}
}
/* Copyright (C) 2020 NexusMutual.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../capital/Pool.sol";
import "../claims/ClaimsReward.sol";
import "../token/NXMToken.sol";
import "../token/TokenController.sol";
import "../token/TokenFunctions.sol";
import "./ClaimsData.sol";
import "./Incidents.sol";
contract Claims is Iupgradable {
using SafeMath for uint;
TokenController internal tc;
ClaimsReward internal cr;
Pool internal p1;
ClaimsData internal cd;
TokenData internal td;
QuotationData internal qd;
Incidents internal incidents;
uint private constant DECIMAL1E18 = uint(10) ** 18;
/**
* @dev Sets the status of claim using claim id.
* @param claimId claim id.
* @param stat status to be set.
*/
function setClaimStatus(uint claimId, uint stat) external onlyInternal {
_setClaimStatus(claimId, stat);
}
/**
* @dev Calculates total amount that has been used to assess a claim.
* Computaion:Adds acceptCA(tokens used for voting in favor of a claim)
* denyCA(tokens used for voting against a claim) * current token price.
* @param claimId Claim Id.
* @param member Member type 0 -> Claim Assessors, else members.
* @return tokens Total Amount used in Claims assessment.
*/
function getCATokens(uint claimId, uint member) external view returns (uint tokens) {
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
if (member == 0) {
(, accept, deny) = cd.getClaimsTokenCA(claimId);
} else {
(, accept, deny) = cd.getClaimsTokenMV(claimId);
}
tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens)
}
/**
* Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public onlyInternal {
td = TokenData(ms.getLatestAddress("TD"));
tc = TokenController(ms.getLatestAddress("TC"));
p1 = Pool(ms.getLatestAddress("P1"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
cd = ClaimsData(ms.getLatestAddress("CD"));
qd = QuotationData(ms.getLatestAddress("QD"));
incidents = Incidents(ms.getLatestAddress("IC"));
}
/**
* @dev Submits a claim for a given cover note.
* Adds claim to queue incase of emergency pause else directly submits the claim.
* @param coverId Cover Id.
*/
function submitClaim(uint coverId) external {
_submitClaim(coverId, msg.sender);
}
function submitClaimForMember(uint coverId, address member) external onlyInternal {
_submitClaim(coverId, member);
}
function _submitClaim(uint coverId, address member) internal {
require(!ms.isPause(), "Claims: System is paused");
(/* id */, address contractAddress) = qd.getscAddressOfCover(coverId);
address token = incidents.coveredToken(contractAddress);
require(token == address(0), "Claims: Product type does not allow claims");
address coverOwner = qd.getCoverMemberAddress(coverId);
require(coverOwner == member, "Claims: Not cover owner");
uint expirationDate = qd.getValidityOfCover(coverId);
uint gracePeriod = tc.claimSubmissionGracePeriod();
require(expirationDate.add(gracePeriod) > now, "Claims: Grace period has expired");
tc.markCoverClaimOpen(coverId);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted));
uint claimId = cd.actualClaimLength();
cd.addClaim(claimId, coverId, coverOwner, now);
cd.callClaimEvent(coverId, coverOwner, claimId, now);
}
// solhint-disable-next-line no-empty-blocks
function submitClaimAfterEPOff() external pure {}
/**
* @dev Castes vote for members who have tokens locked under Claims Assessment
* @param claimId claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now);
uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime()));
require(tokens > 0);
uint stat;
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat == 0);
require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0);
td.bookCATokens(msg.sender);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict);
uint voteLength = cd.getAllVoteLength();
cd.addClaimVoteCA(claimId, voteLength);
cd.setUserClaimVoteCA(msg.sender, claimId, voteLength);
cd.setClaimTokensCA(claimId, verdict, tokens);
tc.extendLockOf(msg.sender, "CLA", td.lockCADays());
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
/**
* @dev Submits a member vote for assessing a claim.
* Tokens other than those locked under Claims
* Assessment can be used to cast a vote for a given claim id.
* @param claimId Selected claim id.
* @param verdict 1 for Accept,-1 for Deny.
*/
function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause {
require(checkVoteClosing(claimId) != 1);
uint stat;
uint tokens = tc.totalBalanceOf(msg.sender);
(, stat) = cd.getClaimStatusNumber(claimId);
require(stat >= 1 && stat <= 5);
require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0);
cd.addVote(msg.sender, tokens, claimId, verdict);
cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict);
tc.lockForMemberVote(msg.sender, td.lockMVDays());
uint voteLength = cd.getAllVoteLength();
cd.addClaimVotemember(claimId, voteLength);
cd.setUserClaimVoteMember(msg.sender, claimId, voteLength);
cd.setClaimTokensMV(claimId, verdict, tokens);
int close = checkVoteClosing(claimId);
if (close == 1) {
cr.changeClaimStatus(claimId);
}
}
// solhint-disable-next-line no-empty-blocks
function pauseAllPendingClaimsVoting() external pure {}
// solhint-disable-next-line no-empty-blocks
function startAllPendingClaimsVoting() external pure {}
/**
* @dev Checks if voting of a claim should be closed or not.
* @param claimId Claim Id.
* @return close 1 -> voting should be closed, 0 -> if voting should not be closed,
* -1 -> voting has already been closed.
*/
function checkVoteClosing(uint claimId) public view returns (int8 close) {
close = 0;
uint status;
(, status) = cd.getClaimStatusNumber(claimId);
uint dateUpd = cd.getClaimDateUpd(claimId);
if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) {
if (cd.getClaimState12Count(claimId) < 60)
close = 1;
}
if (status > 5 && status != 12) {
close = - 1;
} else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) {
close = 1;
} else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) {
close = 0;
} else if (status == 0 || (status >= 1 && status <= 5)) {
close = _checkVoteClosingFinal(claimId, status);
}
}
/**
* @dev Checks if voting of a claim should be closed or not.
* Internally called by checkVoteClosing method
* for Claims whose status number is 0 or status number lie between 2 and 6.
* @param claimId Claim Id.
* @param status Current status of claim.
* @return close 1 if voting should be closed,0 in case voting should not be closed,
* -1 if voting has already been closed.
*/
function _checkVoteClosingFinal(uint claimId, uint status) internal view returns (int8 close) {
close = 0;
uint coverId;
(, coverId) = cd.getClaimCoverId(claimId);
bytes4 currency = qd.getCurrencyOfCover(coverId);
address asset = cr.getCurrencyAssetAddress(currency);
uint tokenx1e18 = p1.getTokenPrice(asset);
uint accept;
uint deny;
(, accept, deny) = cd.getClaimsTokenCA(claimId);
uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
(, accept, deny) = cd.getClaimsTokenMV(claimId);
uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18);
uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18);
if (status == 0 && caTokens >= sumassured.mul(10)) {
close = 1;
} else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) {
close = 1;
}
}
/**
* @dev Changes the status of an existing claim id, based on current
* status and current conditions of the system
* @param claimId Claim Id.
* @param stat status number.
*/
function _setClaimStatus(uint claimId, uint stat) internal {
uint origstat;
uint state12Count;
uint dateUpd;
uint coverId;
(, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId);
(, origstat) = cd.getClaimStatusNumber(claimId);
if (stat == 12 && origstat == 12) {
cd.updateState12Count(claimId, 1);
}
cd.setClaimStatus(claimId, stat);
if (state12Count >= 60 && stat == 12) {
cd.setClaimStatus(claimId, 13);
qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied));
}
cd.setClaimdateUpd(claimId, now);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../claims/ClaimsReward.sol";
import "../cover/QuotationData.sol";
import "../token/TokenController.sol";
import "../token/TokenData.sol";
import "../token/TokenFunctions.sol";
import "./Governance.sol";
import "./external/Governed.sol";
contract MemberRoles is Governed, Iupgradable {
TokenController public tc;
TokenData internal td;
QuotationData internal qd;
ClaimsReward internal cr;
Governance internal gv;
TokenFunctions internal tf;
NXMToken public tk;
struct MemberRoleDetails {
uint memberCounter;
mapping(address => bool) memberActive;
address[] memberAddress;
address authorized;
}
enum Role {UnAssigned, AdvisoryBoard, Member, Owner}
event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription);
event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp);
event ClaimPayoutAddressSet(address indexed member, address indexed payoutAddress);
MemberRoleDetails[] internal memberRoleData;
bool internal constructorCheck;
uint public maxABCount;
bool public launched;
uint public launchedOn;
mapping (address => address payable) internal claimPayoutAddress;
modifier checkRoleAuthority(uint _memberRoleId) {
if (memberRoleData[_memberRoleId].authorized != address(0))
require(msg.sender == memberRoleData[_memberRoleId].authorized);
else
require(isAuthorizedToGovern(msg.sender), "Not Authorized");
_;
}
/**
* @dev to swap advisory board member
* @param _newABAddress is address of new AB member
* @param _removeAB is advisory board member to be removed
*/
function swapABMember(
address _newABAddress,
address _removeAB
)
external
checkRoleAuthority(uint(Role.AdvisoryBoard)) {
_updateRole(_newABAddress, uint(Role.AdvisoryBoard), true);
_updateRole(_removeAB, uint(Role.AdvisoryBoard), false);
}
/**
* @dev to swap the owner address
* @param _newOwnerAddress is the new owner address
*/
function swapOwner(
address _newOwnerAddress
)
external {
require(msg.sender == address(ms));
_updateRole(ms.owner(), uint(Role.Owner), false);
_updateRole(_newOwnerAddress, uint(Role.Owner), true);
}
/**
* @dev is used to add initital advisory board members
* @param abArray is the list of initial advisory board members
*/
function addInitialABMembers(address[] calldata abArray) external onlyOwner {
//Ensure that NXMaster has initialized.
require(ms.masterInitialized());
require(maxABCount >=
SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length)
);
//AB count can't exceed maxABCount
for (uint i = 0; i < abArray.length; i++) {
require(checkRole(abArray[i], uint(MemberRoles.Role.Member)));
_updateRole(abArray[i], uint(Role.AdvisoryBoard), true);
}
}
/**
* @dev to change max number of AB members allowed
* @param _val is the new value to be set
*/
function changeMaxABCount(uint _val) external onlyInternal {
maxABCount = _val;
}
/**
* @dev Iupgradable Interface to update dependent contract address
*/
function changeDependentContractAddress() public {
td = TokenData(ms.getLatestAddress("TD"));
cr = ClaimsReward(ms.getLatestAddress("CR"));
qd = QuotationData(ms.getLatestAddress("QD"));
gv = Governance(ms.getLatestAddress("GV"));
tf = TokenFunctions(ms.getLatestAddress("TF"));
tk = NXMToken(ms.tokenAddress());
tc = TokenController(ms.getLatestAddress("TC"));
}
/**
* @dev to change the master address
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0)) {
require(masterAddress == msg.sender);
}
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev to initiate the member roles
* @param _firstAB is the address of the first AB member
* @param memberAuthority is the authority (role) of the member
*/
function memberRolesInitiate(address _firstAB, address memberAuthority) public {
require(!constructorCheck);
_addInitialMemberRoles(_firstAB, memberAuthority);
constructorCheck = true;
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function addRole(//solhint-disable-line
bytes32 _roleName,
string memory _roleDescription,
address _authorized
)
public
onlyAuthorizedToGovern {
_addRole(_roleName, _roleDescription, _authorized);
}
/// @dev Assign or Delete a member from specific role.
/// @param _memberAddress Address of Member
/// @param _roleId RoleId to update
/// @param _active active is set to be True if we want to assign this role to member, False otherwise!
function updateRole(//solhint-disable-line
address _memberAddress,
uint _roleId,
bool _active
)
public
checkRoleAuthority(_roleId) {
_updateRole(_memberAddress, _roleId, _active);
}
/**
* @dev to add members before launch
* @param userArray is list of addresses of members
* @param tokens is list of tokens minted for each array element
*/
function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner {
require(!launched);
for (uint i = 0; i < userArray.length; i++) {
require(!ms.isMember(userArray[i]));
tc.addToWhitelist(userArray[i]);
_updateRole(userArray[i], uint(Role.Member), true);
tc.mint(userArray[i], tokens[i]);
}
launched = true;
launchedOn = now;
}
/**
* @dev Called by user to pay joining membership fee
*/
function payJoiningFee(address _userAddress) public payable {
require(_userAddress != address(0));
require(!ms.isPause(), "Emergency Pause Applied");
if (msg.sender == address(ms.getLatestAddress("QT"))) {
require(td.walletAddress() != address(0), "No walletAddress present");
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(msg.value);
} else {
require(!qd.refundEligible(_userAddress));
require(!ms.isMember(_userAddress));
require(msg.value == td.joiningFee());
qd.setRefundEligible(_userAddress, true);
}
}
/**
* @dev to perform kyc verdict
* @param _userAddress whose kyc is being performed
* @param verdict of kyc process
*/
function kycVerdict(address payable _userAddress, bool verdict) public {
require(msg.sender == qd.kycAuthAddress());
require(!ms.isPause());
require(_userAddress != address(0));
require(!ms.isMember(_userAddress));
require(qd.refundEligible(_userAddress));
if (verdict) {
qd.setRefundEligible(_userAddress, false);
uint fee = td.joiningFee();
tc.addToWhitelist(_userAddress);
_updateRole(_userAddress, uint(Role.Member), true);
td.walletAddress().transfer(fee); // solhint-disable-line
} else {
qd.setRefundEligible(_userAddress, false);
_userAddress.transfer(td.joiningFee()); // solhint-disable-line
}
}
/**
* @dev withdraws membership for msg.sender if currently a member.
*/
function withdrawMembership() public {
require(!ms.isPause() && ms.isMember(msg.sender));
require(tc.totalLockedBalance(msg.sender) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(msg.sender);
tc.burnFrom(msg.sender, tk.balanceOf(msg.sender));
_updateRole(msg.sender, uint(Role.Member), false);
tc.removeFromWhitelist(msg.sender); // need clarification on whitelist
if (claimPayoutAddress[msg.sender] != address(0)) {
claimPayoutAddress[msg.sender] = address(0);
emit ClaimPayoutAddressSet(msg.sender, address(0));
}
}
/**
* @dev switches membership for msg.sender to the specified address.
* @param newAddress address of user to forward membership.
*/
function switchMembership(address newAddress) external {
_switchMembership(msg.sender, newAddress);
tk.transferFrom(msg.sender, newAddress, tk.balanceOf(msg.sender));
}
function switchMembershipOf(address member, address newAddress) external onlyInternal {
_switchMembership(member, newAddress);
}
/**
* @dev switches membership for member to the specified address.
* @param newAddress address of user to forward membership.
*/
function _switchMembership(address member, address newAddress) internal {
require(!ms.isPause() && ms.isMember(member) && !ms.isMember(newAddress));
require(tc.totalLockedBalance(member) == 0); // solhint-disable-line
require(!tf.isLockedForMemberVote(member)); // No locked tokens for Member/Governance voting
require(cr.getAllPendingRewardOfUser(member) == 0); // No pending reward to be claimed(claim assesment).
gv.removeDelegation(member);
tc.addToWhitelist(newAddress);
_updateRole(newAddress, uint(Role.Member), true);
_updateRole(member, uint(Role.Member), false);
tc.removeFromWhitelist(member);
address payable previousPayoutAddress = claimPayoutAddress[member];
if (previousPayoutAddress != address(0)) {
address payable storedAddress = previousPayoutAddress == newAddress ? address(0) : previousPayoutAddress;
claimPayoutAddress[member] = address(0);
claimPayoutAddress[newAddress] = storedAddress;
// emit event for old address reset
emit ClaimPayoutAddressSet(member, address(0));
if (storedAddress != address(0)) {
// emit event for setting the payout address on the new member address if it's non zero
emit ClaimPayoutAddressSet(newAddress, storedAddress);
}
}
emit switchedMembership(member, newAddress, now);
}
function getClaimPayoutAddress(address payable _member) external view returns (address payable) {
address payable payoutAddress = claimPayoutAddress[_member];
return payoutAddress != address(0) ? payoutAddress : _member;
}
function setClaimPayoutAddress(address payable _address) external {
require(!ms.isPause(), "system is paused");
require(ms.isMember(msg.sender), "sender is not a member");
require(_address != msg.sender, "should be different than the member address");
claimPayoutAddress[msg.sender] = _address;
emit ClaimPayoutAddressSet(msg.sender, _address);
}
/// @dev Return number of member roles
function totalRoles() public view returns (uint256) {//solhint-disable-line
return memberRoleData.length;
}
/// @dev Change Member Address who holds the authority to Add/Delete any member from specific role.
/// @param _roleId roleId to update its Authorized Address
/// @param _newAuthorized New authorized address against role id
function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) {//solhint-disable-line
memberRoleData[_roleId].authorized = _newAuthorized;
}
/// @dev Gets the member addresses assigned by a specific role
/// @param _memberRoleId Member role id
/// @return roleId Role id
/// @return allMemberAddress Member addresses of specified role id
function members(uint _memberRoleId) public view returns (uint, address[] memory memberArray) {//solhint-disable-line
uint length = memberRoleData[_memberRoleId].memberAddress.length;
uint i;
uint j = 0;
memberArray = new address[](memberRoleData[_memberRoleId].memberCounter);
for (i = 0; i < length; i++) {
address member = memberRoleData[_memberRoleId].memberAddress[i];
if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) {//solhint-disable-line
memberArray[j] = member;
j++;
}
}
return (_memberRoleId, memberArray);
}
/// @dev Gets all members' length
/// @param _memberRoleId Member role id
/// @return memberRoleData[_memberRoleId].memberCounter Member length
function numberOfMembers(uint _memberRoleId) public view returns (uint) {//solhint-disable-line
return memberRoleData[_memberRoleId].memberCounter;
}
/// @dev Return member address who holds the right to add/remove any member from specific role.
function authorized(uint _memberRoleId) public view returns (address) {//solhint-disable-line
return memberRoleData[_memberRoleId].authorized;
}
/// @dev Get All role ids array that has been assigned to a member so far.
function roles(address _memberAddress) public view returns (uint[] memory) {//solhint-disable-line
uint length = memberRoleData.length;
uint[] memory assignedRoles = new uint[](length);
uint counter = 0;
for (uint i = 1; i < length; i++) {
if (memberRoleData[i].memberActive[_memberAddress]) {
assignedRoles[counter] = i;
counter++;
}
}
return assignedRoles;
}
/// @dev Returns true if the given role id is assigned to a member.
/// @param _memberAddress Address of member
/// @param _roleId Checks member's authenticity with the roleId.
/// i.e. Returns true if this roleId is assigned to member
function checkRole(address _memberAddress, uint _roleId) public view returns (bool) {//solhint-disable-line
if (_roleId == uint(Role.UnAssigned))
return true;
else
if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line
return true;
else
return false;
}
/// @dev Return total number of members assigned against each role id.
/// @return totalMembers Total members in particular role id
function getMemberLengthForAllRoles() public view returns (uint[] memory totalMembers) {//solhint-disable-line
totalMembers = new uint[](memberRoleData.length);
for (uint i = 0; i < memberRoleData.length; i++) {
totalMembers[i] = numberOfMembers(i);
}
}
/**
* @dev to update the member roles
* @param _memberAddress in concern
* @param _roleId the id of role
* @param _active if active is true, add the member, else remove it
*/
function _updateRole(address _memberAddress,
uint _roleId,
bool _active) internal {
// require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically");
if (_active) {
require(!memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1);
memberRoleData[_roleId].memberActive[_memberAddress] = true;
memberRoleData[_roleId].memberAddress.push(_memberAddress);
} else {
require(memberRoleData[_roleId].memberActive[_memberAddress]);
memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1);
delete memberRoleData[_roleId].memberActive[_memberAddress];
}
}
/// @dev Adds new member role
/// @param _roleName New role name
/// @param _roleDescription New description hash
/// @param _authorized Authorized member against every role id
function _addRole(
bytes32 _roleName,
string memory _roleDescription,
address _authorized
) internal {
emit MemberRole(memberRoleData.length, _roleName, _roleDescription);
memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized));
}
/**
* @dev to check if member is in the given member array
* @param _memberAddress in concern
* @param memberArray in concern
* @return boolean to represent the presence
*/
function _checkMemberInArray(
address _memberAddress,
address[] memory memberArray
)
internal
pure
returns (bool memberExists)
{
uint i;
for (i = 0; i < memberArray.length; i++) {
if (memberArray[i] == _memberAddress) {
memberExists = true;
break;
}
}
}
/**
* @dev to add initial member roles
* @param _firstAB is the member address to be added
* @param memberAuthority is the member authority(role) to be added for
*/
function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal {
maxABCount = 5;
_addRole("Unassigned", "Unassigned", address(0));
_addRole(
"Advisory Board",
"Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line
address(0)
);
_addRole(
"Member",
"Represents all users of Mutual.", //solhint-disable-line
memberAuthority
);
_addRole(
"Owner",
"Represents Owner of Mutual.", //solhint-disable-line
address(0)
);
// _updateRole(_firstAB, uint(Role.AdvisoryBoard), true);
_updateRole(_firstAB, uint(Role.Owner), true);
// _updateRole(_firstAB, uint(Role.Member), true);
launchedOn = 0;
}
function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) {
address memberAddress = memberRoleData[_memberRoleId].memberAddress[index];
return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]);
}
function membersLength(uint _memberRoleId) external view returns (uint) {
return memberRoleData[_memberRoleId].memberAddress.length;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
import "../../abstract/Iupgradable.sol";
import "./MemberRoles.sol";
import "./external/Governed.sol";
import "./external/IProposalCategory.sol";
contract ProposalCategory is Governed, IProposalCategory, Iupgradable {
bool public constructorCheck;
MemberRoles internal mr;
struct CategoryStruct {
uint memberRoleToVote;
uint majorityVotePerc;
uint quorumPerc;
uint[] allowedToCreateProposal;
uint closingTime;
uint minStake;
}
struct CategoryAction {
uint defaultIncentive;
address contractAddress;
bytes2 contractName;
}
CategoryStruct[] internal allCategory;
mapping(uint => CategoryAction) internal categoryActionData;
mapping(uint => uint) public categoryABReq;
mapping(uint => uint) public isSpecialResolution;
mapping(uint => bytes) public categoryActionHashes;
bool public categoryActionHashUpdated;
/**
* @dev Adds new category (Discontinued, moved functionality to newCategory)
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
) external {}
/**
* @dev Initiates Default settings for Proposal Category contract (Adding default categories)
*/
function proposalCategoryInitiate() external {}
/**
* @dev Initiates Default action function hashes for existing categories
* To be called after the contract has been upgraded by governance
*/
function updateCategoryActionHashes() external onlyOwner {
require(!categoryActionHashUpdated, "Category action hashes already updated");
categoryActionHashUpdated = true;
categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)");
categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)");
categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)"); // solhint-disable-line
categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)");
categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()");
categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)");
categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)");
categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)");
categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)");
categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)"); // solhint-disable-line
categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)");
categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)");
categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)");
categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)");
categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)");
categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)");
categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)");
categoryActionHashes[29] = abi.encodeWithSignature("upgradeMultipleContracts(bytes2[],address[])");
categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)");
categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)");
categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)"); // solhint-disable-line
categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()");
}
/**
* @dev Gets Total number of categories added till now
*/
function totalCategories() external view returns (uint) {
return allCategory.length;
}
/**
* @dev Gets category details
*/
function category(uint _categoryId) external view returns (uint, uint, uint, uint, uint[] memory, uint, uint) {
return (
_categoryId,
allCategory[_categoryId].memberRoleToVote,
allCategory[_categoryId].majorityVotePerc,
allCategory[_categoryId].quorumPerc,
allCategory[_categoryId].allowedToCreateProposal,
allCategory[_categoryId].closingTime,
allCategory[_categoryId].minStake
);
}
/**
* @dev Gets category ab required and isSpecialResolution
* @return the category id
* @return if AB voting is required
* @return is category a special resolution
*/
function categoryExtendedData(uint _categoryId) external view returns (uint, uint, uint) {
return (
_categoryId,
categoryABReq[_categoryId],
isSpecialResolution[_categoryId]
);
}
/**
* @dev Gets the category acion details
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
*/
function categoryAction(uint _categoryId) external view returns (uint, address, bytes2, uint) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive
);
}
/**
* @dev Gets the category acion details of a category id
* @param _categoryId is the category id in concern
* @return the category id
* @return the contract address
* @return the contract name
* @return the default incentive
* @return action function hash
*/
function categoryActionDetails(uint _categoryId) external view returns (uint, address, bytes2, uint, bytes memory) {
return (
_categoryId,
categoryActionData[_categoryId].contractAddress,
categoryActionData[_categoryId].contractName,
categoryActionData[_categoryId].defaultIncentive,
categoryActionHashes[_categoryId]
);
}
/**
* @dev Updates dependant contract addresses
*/
function changeDependentContractAddress() public {
mr = MemberRoles(ms.getLatestAddress("MR"));
}
/**
* @dev Adds new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function newCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
_addCategory(
_name,
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_actionHash,
_contractAddress,
_contractName,
_incentives
);
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash);
}
}
/**
* @dev Changes the master address and update it's instance
* @param _masterAddress is the new master address
*/
function changeMasterAddress(address _masterAddress) public {
if (masterAddress != address(0))
require(masterAddress == msg.sender);
masterAddress = _masterAddress;
ms = INXMMaster(_masterAddress);
nxMasterAddress = _masterAddress;
}
/**
* @dev Updates category details (Discontinued, moved functionality to editCategory)
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
) public {}
/**
* @dev Updates category details
* @param _categoryId Category id that needs to be updated
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
* @param _functionHash function signature to be executed
*/
function editCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives,
string memory _functionHash
)
public
onlyAuthorizedToGovern
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage");
require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0);
require(_incentives[3] <= 1, "Invalid special resolution flag");
//If category is special resolution role authorized should be member
if (_incentives[3] == 1) {
require(_memberRoleToVote == uint(MemberRoles.Role.Member));
_majorityVotePerc = 0;
_quorumPerc = 0;
}
delete categoryActionHashes[_categoryId];
if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) {
categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash);
}
allCategory[_categoryId].memberRoleToVote = _memberRoleToVote;
allCategory[_categoryId].majorityVotePerc = _majorityVotePerc;
allCategory[_categoryId].closingTime = _closingTime;
allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal;
allCategory[_categoryId].minStake = _incentives[0];
allCategory[_categoryId].quorumPerc = _quorumPerc;
categoryActionData[_categoryId].defaultIncentive = _incentives[1];
categoryActionData[_categoryId].contractName = _contractName;
categoryActionData[_categoryId].contractAddress = _contractAddress;
categoryABReq[_categoryId] = _incentives[2];
isSpecialResolution[_categoryId] = _incentives[3];
emit Category(_categoryId, _name, _actionHash);
}
/**
* @dev Internal call to add new category
* @param _name Category name
* @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
* @param _majorityVotePerc Majority Vote threshold for Each voting layer
* @param _quorumPerc minimum threshold percentage required in voting to calculate result
* @param _allowedToCreateProposal Member roles allowed to create the proposal
* @param _closingTime Vote closing time for Each voting layer
* @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
* @param _contractAddress address of contract to call after proposal is accepted
* @param _contractName name of contract to be called after proposal is accepted
* @param _incentives rewards to distributed after proposal is accepted
*/
function _addCategory(
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
internal
{
require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role");
allCategory.push(
CategoryStruct(
_memberRoleToVote,
_majorityVotePerc,
_quorumPerc,
_allowedToCreateProposal,
_closingTime,
_incentives[0]
)
);
uint categoryId = allCategory.length - 1;
categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName);
categoryABReq[categoryId] = _incentives[2];
isSpecialResolution[categoryId] = _incentives[3];
emit Category(categoryId, _name, _actionHash);
}
/**
* @dev Internal call to check if given roles are valid or not
*/
function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal)
internal view returns (uint) {
uint totalRoles = mr.totalRoles();
if (_memberRoleToVote >= totalRoles) {
return 0;
}
for (uint i = 0; i < _allowedToCreateProposal.length; i++) {
if (_allowedToCreateProposal[i] >= totalRoles) {
return 0;
}
}
return 1;
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IGovernance {
event Proposal(
address indexed proposalOwner,
uint256 indexed proposalId,
uint256 dateAdd,
string proposalTitle,
string proposalSD,
string proposalDescHash
);
event Solution(
uint256 indexed proposalId,
address indexed solutionOwner,
uint256 indexed solutionId,
string solutionDescHash,
uint256 dateAdd
);
event Vote(
address indexed from,
uint256 indexed proposalId,
uint256 indexed voteId,
uint256 dateAdd,
uint256 solutionChosen
);
event RewardClaimed(
address indexed member,
uint gbtReward
);
/// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal.
event VoteCast (uint256 proposalId);
/// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can
/// call any offchain actions
event ProposalAccepted (uint256 proposalId);
/// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time.
event CloseProposalOnTime (
uint256 indexed proposalId,
uint256 time
);
/// @dev ActionSuccess event is called whenever an onchain action is executed.
event ActionSuccess (
uint256 proposalId
);
/// @dev Creates a new proposal
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
function createProposal(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId
)
external;
/// @dev Edits the details of an existing proposal and creates new version
/// @param _proposalId Proposal id that details needs to be updated
/// @param _proposalDescHash Proposal description hash having long and short description of proposal.
function updateProposal(
uint _proposalId,
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash
)
external;
/// @dev Categorizes proposal to proceed further. Categories shows the proposal objective.
function categorizeProposal(
uint _proposalId,
uint _categoryId,
uint _incentives
)
external;
/// @dev Submit proposal with solution
/// @param _proposalId Proposal id
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function submitProposalWithSolution(
uint _proposalId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Creates a new proposal with solution and votes for the solution
/// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal
/// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective
/// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal
function createProposalwithSolution(
string calldata _proposalTitle,
string calldata _proposalSD,
string calldata _proposalDescHash,
uint _categoryId,
string calldata _solutionHash,
bytes calldata _action
)
external;
/// @dev Casts vote
/// @param _proposalId Proposal id
/// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution
function submitVote(uint _proposalId, uint _solutionChosen) external;
function closeProposal(uint _proposalId) external;
function claimReward(address _memberAddress, uint _maxRecords) external returns (uint pendingDAppReward);
function proposal(uint _proposalId)
external
view
returns (
uint proposalId,
uint category,
uint status,
uint finalVerdict,
uint totalReward
);
function canCloseProposal(uint _proposalId) public view returns (uint closeValue);
function allowedToCatgorize() public view returns (uint roleId);
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
interface IMaster {
function getLatestAddress(bytes2 _module) external view returns (address);
}
contract Governed {
address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract
/// @dev modifier that allows only the authorized addresses to execute the function
modifier onlyAuthorizedToGovern() {
IMaster ms = IMaster(masterAddress);
require(ms.getLatestAddress("GV") == msg.sender, "Not authorized");
_;
}
/// @dev checks if an address is authorized to govern
function isAuthorizedToGovern(address _toCheck) public view returns (bool) {
IMaster ms = IMaster(masterAddress);
return (ms.getLatestAddress("GV") == _toCheck);
}
}
/* Copyright (C) 2017 GovBlocks.io
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see http://www.gnu.org/licenses/ */
pragma solidity ^0.5.0;
contract IProposalCategory {
event Category(
uint indexed categoryId,
string categoryName,
string actionHash
);
/// @dev Adds new category
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function addCategory(
string calldata _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] calldata _allowedToCreateProposal,
uint _closingTime,
string calldata _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] calldata _incentives
)
external;
/// @dev gets category details
function category(uint _categoryId)
external
view
returns (
uint categoryId,
uint memberRoleToVote,
uint majorityVotePerc,
uint quorumPerc,
uint[] memory allowedToCreateProposal,
uint closingTime,
uint minStake
);
///@dev gets category action details
function categoryAction(uint _categoryId)
external
view
returns (
uint categoryId,
address contractAddress,
bytes2 contractName,
uint defaultIncentive
);
/// @dev Gets Total number of categories added till now
function totalCategories() external view returns (uint numberOfCategories);
/// @dev Updates category details
/// @param _categoryId Category id that needs to be updated
/// @param _name Category name
/// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed.
/// @param _allowedToCreateProposal Member roles allowed to create the proposal
/// @param _majorityVotePerc Majority Vote threshold for Each voting layer
/// @param _quorumPerc minimum threshold percentage required in voting to calculate result
/// @param _closingTime Vote closing time for Each voting layer
/// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted
/// @param _contractAddress address of contract to call after proposal is accepted
/// @param _contractName name of contract to be called after proposal is accepted
/// @param _incentives rewards to distributed after proposal is accepted
function updateCategory(
uint _categoryId,
string memory _name,
uint _memberRoleToVote,
uint _majorityVotePerc,
uint _quorumPerc,
uint[] memory _allowedToCreateProposal,
uint _closingTime,
string memory _actionHash,
address _contractAddress,
bytes2 _contractName,
uint[] memory _incentives
)
public;
}
| Computes token sell value for a tokenAmount in ETH with a sell spread of 2.5%. for values in ETH of the sale <= 1% MCReth the sell spread is very close to the exact value of 2.5%. for values higher than that sell spread may exceed 2.5% (The higher amount being sold at any given time the higher the spread)/ Step 1. Calculate spot price at current values and amount of ETH if tokens are sold at that price Step 2. Calculate spot price using V = currentTotalAssetValue - spotEthAmount from step 1 Step 3. Min [average[Price(0), Price(1)] x ( 1 - Sell Spread), Price(1) ] Sell Spread = 2.5% | function calculateEthForNXM(
uint nxmAmount,
uint currentTotalAssetValue,
uint mcrEth
) public pure returns (uint) {
uint spotPrice0 = calculateTokenSpotPrice(currentTotalAssetValue, mcrEth);
uint spotEthAmount = nxmAmount.mul(spotPrice0).div(1e18);
uint totalValuePostSpotPriceSell = currentTotalAssetValue.sub(spotEthAmount);
uint spotPrice1 = calculateTokenSpotPrice(totalValuePostSpotPriceSell, mcrEth);
uint averagePriceWithSpread = spotPrice0.add(spotPrice1).div(2).mul(975).div(1000);
uint finalPrice = averagePriceWithSpread < spotPrice1 ? averagePriceWithSpread : spotPrice1;
uint ethAmount = finalPrice.mul(nxmAmount).div(1e18);
require(
ethAmount <= mcrEth.mul(MAX_BUY_SELL_MCR_ETH_FRACTION).div(10 ** MCR_RATIO_DECIMALS),
"Pool: Sales worth more than 5% of MCReth are not allowed"
);
return ethAmount;
}
| 2,577,850 |
./full_match/5/0x93EA5c5f0961E9912E77211ef5888618E4DC7e7e/sources/src/token/ERC1155/extensions/mintable/ERC1155Mintable.sol | @inheritdoc IERC1155Mintable/ | function mintByFacet(
address[] calldata tos,
uint256[] calldata ids,
uint256[] calldata amounts,
bytes[] calldata datas
) public virtual {
if (address(this) != msg.sender) {
revert SenderIsNotSelf();
}
_mintBatch(tos, ids, amounts, datas);
}
| 1,890,686 |
./full_match/56/0xcBD57e01a6e46A53617215B968d2182FdA0Ec6F5/sources/usertoken_flattened.sol | generate the uniswap pair path of token -> weth make the swap | function swapThisForTokens(uint256 thisTokenAmount, address outToken) private {
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = outToken;
_approve(address(this), address(router), thisTokenAmount);
router.swapExactTokensForTokensSupportingFeeOnTransferTokens(
thisTokenAmount,
path,
_msgSender(),
block.timestamp
);
}
| 3,242,333 |
./full_match/1/0x578Bc817d19e4EBEb47F57824F9871C4858b1C94/sources/deploy/Contract.sol | 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 {
have(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
| 3,175,655 |
./full_match/1/0xFb6B7C11a55C57767643F1FF65c34C8693a11A70/sources/contracts/DivaGovernor.sol | Voting power need to be able to create a proposal/ | function proposalThreshold()
public
view
override(Governor, GovernorSettings)
returns (uint256)
{
return super.proposalThreshold();
}
| 4,892,190 |
./partial_match/1/0x828a7f1802eDe207C36D156c62C9600bb4D79E63/sources/LydianLionCoin.sol | exclude from paying fees or having max transaction amount | function _beforeTokenTransfer(
address from,
address to,
uint256 amount
function _afterTokenTransfer(
address from,
address to,
uint256 amount
}
}
constructor() ERC20("Lydian Lion Coin", "LLC") {
uint256 _buyRevShareFee = 0;
uint256 _buyLiquidityFee = 0;
uint256 _buyTeamFee = 1;
uint256 _sellRevShareFee = 0;
uint256 _sellLiquidityFee = 0;
uint256 _sellTeamFee = 1;
uint256 totalSupply = 1_000_000 * 1e18;
buyRevShareFee = _buyRevShareFee;
buyLiquidityFee = _buyLiquidityFee;
buyTeamFee = _buyTeamFee;
buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee;
sellRevShareFee = _sellRevShareFee;
sellLiquidityFee = _sellLiquidityFee;
sellTeamFee = _sellTeamFee;
sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee;
excludeFromFees(owner(), true);
excludeFromFees(teamWallet, true);
excludeFromFees(address(this), true);
excludeFromFees(address(0xdead), true);
excludeFromMaxTransaction(owner(), true);
excludeFromMaxTransaction(teamWallet, 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);
| 15,548,309 |
pragma solidity ^0.5.17;
import "../../interfaces/IERC20.sol";
import "../../utils/AdminRole.sol";
import "./VestingRegistryLogic.sol";
import "./VestingLogic.sol";
import "../../openzeppelin/SafeMath.sol";
contract VestingCreator is AdminRole {
using SafeMath for uint256;
///@notice Boolean to check both vesting creation and staking is completed for a record
bool vestingCreated;
/// @notice 2 weeks in seconds.
uint256 public constant TWO_WEEKS = 1209600;
///@notice the SOV token contract
IERC20 public SOV;
///@notice the vesting registry contract
VestingRegistryLogic public vestingRegistryLogic;
///@notice Holds Vesting Data
struct VestingData {
uint256 amount;
uint256 cliff;
uint256 duration;
bool governanceControl; ///@dev true - tokens can be withdrawn by governance
address tokenOwner;
uint256 vestingCreationType;
}
///@notice list of vesting to be processed
VestingData[] public vestingDataList;
event SOVTransferred(address indexed receiver, uint256 amount);
event TokensStaked(address indexed vesting, address indexed tokenOwner, uint256 amount);
event VestingDataRemoved(address indexed caller, address indexed tokenOwner);
event DataCleared(address indexed caller);
constructor(address _SOV, address _vestingRegistryProxy) public {
require(_SOV != address(0), "SOV address invalid");
require(_vestingRegistryProxy != address(0), "Vesting registry address invalid");
SOV = IERC20(_SOV);
vestingRegistryLogic = VestingRegistryLogic(_vestingRegistryProxy);
}
/**
* @notice transfers SOV tokens to given address
* @param _receiver the address of the SOV receiver
* @param _amount the amount to be transferred
*/
function transferSOV(address _receiver, uint256 _amount) external onlyOwner {
require(_amount != 0, "amount invalid");
require(SOV.transfer(_receiver, _amount), "transfer failed");
emit SOVTransferred(_receiver, _amount);
}
/**
* @notice adds vestings to be processed to the list
*/
function addVestings(
address[] calldata _tokenOwners,
uint256[] calldata _amounts,
uint256[] calldata _cliffs,
uint256[] calldata _durations,
bool[] calldata _governanceControls,
uint256[] calldata _vestingCreationTypes
) external onlyAuthorized {
require(
_tokenOwners.length == _amounts.length &&
_tokenOwners.length == _cliffs.length &&
_tokenOwners.length == _durations.length &&
_tokenOwners.length == _governanceControls.length,
"arrays mismatch"
);
for (uint256 i = 0; i < _tokenOwners.length; i++) {
require(_durations[i] >= _cliffs[i], "duration must be bigger than or equal to the cliff");
require(_amounts[i] > 0, "vesting amount cannot be 0");
require(_tokenOwners[i] != address(0), "token owner cannot be 0 address");
require(_cliffs[i].mod(TWO_WEEKS) == 0, "cliffs should have intervals of two weeks");
require(_durations[i].mod(TWO_WEEKS) == 0, "durations should have intervals of two weeks");
VestingData memory vestingData =
VestingData({
amount: _amounts[i],
cliff: _cliffs[i],
duration: _durations[i],
governanceControl: _governanceControls[i],
tokenOwner: _tokenOwners[i],
vestingCreationType: _vestingCreationTypes[i]
});
vestingDataList.push(vestingData);
}
}
/**
* @notice Creates vesting contract and stakes tokens
* @dev Vesting and Staking are merged for calls that fits the gas limit
*/
function processNextVesting() external {
processVestingCreation();
processStaking();
}
/**
* @notice Creates vesting contract without staking any tokens
* @dev Separating the Vesting and Staking to tackle Block Gas Limit
*/
function processVestingCreation() public {
require(!vestingCreated, "staking not done for the previous vesting");
if (vestingDataList.length > 0) {
VestingData storage vestingData = vestingDataList[vestingDataList.length - 1];
_createAndGetVesting(vestingData);
vestingCreated = true;
}
}
/**
* @notice Staking vested tokens
* @dev it can be the case when vesting creation and tokens staking can't be done in one transaction because of block gas limit
*/
function processStaking() public {
require(vestingCreated, "cannot stake without vesting creation");
if (vestingDataList.length > 0) {
VestingData storage vestingData = vestingDataList[vestingDataList.length - 1];
address vestingAddress =
_getVesting(
vestingData.tokenOwner,
vestingData.cliff,
vestingData.duration,
vestingData.governanceControl,
vestingData.vestingCreationType
);
if (vestingAddress != address(0)) {
VestingLogic vesting = VestingLogic(vestingAddress);
require(SOV.approve(address(vesting), vestingData.amount), "Approve failed");
vesting.stakeTokens(vestingData.amount);
emit TokensStaked(vestingAddress, vestingData.tokenOwner, vestingData.amount);
address tokenOwnerDetails = vestingData.tokenOwner;
delete vestingDataList[vestingDataList.length - 1];
vestingDataList.length--;
emit VestingDataRemoved(msg.sender, tokenOwnerDetails);
}
}
vestingCreated = false;
}
/**
* @notice removes next vesting data from the list
* @dev we process inverted list
* @dev we should be able to remove incorrect vesting data that can't be processed
*/
function removeNextVesting() external onlyAuthorized {
address tokenOwnerDetails;
if (vestingDataList.length > 0) {
VestingData storage vestingData = vestingDataList[vestingDataList.length - 1];
tokenOwnerDetails = vestingData.tokenOwner;
delete vestingDataList[vestingDataList.length - 1];
vestingDataList.length--;
emit VestingDataRemoved(msg.sender, tokenOwnerDetails);
}
}
/**
* @notice removes all data about unprocessed vestings to be processed
*/
function clearVestingDataList() public onlyAuthorized {
delete vestingDataList;
emit DataCleared(msg.sender);
}
/**
* @notice returns address after vesting creation
*/
function getVestingAddress() external view returns (address) {
return
_getVesting(
vestingDataList[vestingDataList.length - 1].tokenOwner,
vestingDataList[vestingDataList.length - 1].cliff,
vestingDataList[vestingDataList.length - 1].duration,
vestingDataList[vestingDataList.length - 1].governanceControl,
vestingDataList[vestingDataList.length - 1].vestingCreationType
);
}
/**
* @notice returns period i.e. ((duration - cliff) / 4 WEEKS)
* @dev will be used for deciding if vesting and staking needs to be processed
* in a single transaction or separate transactions
*/
function getVestingPeriod() external view returns (uint256) {
uint256 duration = vestingDataList[vestingDataList.length - 1].duration;
uint256 cliff = vestingDataList[vestingDataList.length - 1].cliff;
uint256 fourWeeks = TWO_WEEKS.mul(2);
uint256 period = duration.sub(cliff).div(fourWeeks);
return period;
}
/**
* @notice returns count of vestings to be processed
*/
function getUnprocessedCount() external view returns (uint256) {
return vestingDataList.length;
}
/**
* @notice returns total amount of vestings to be processed
*/
function getUnprocessedAmount() public view returns (uint256) {
uint256 amount = 0;
uint256 length = vestingDataList.length;
for (uint256 i = 0; i < length; i++) {
amount = amount.add(vestingDataList[i].amount);
}
return amount;
}
/**
* @notice checks if contract balance is enough to process all vestings
*/
function isEnoughBalance() public view returns (bool) {
return SOV.balanceOf(address(this)) >= getUnprocessedAmount();
}
/**
* @notice returns missed balance to process all vestings
*/
function getMissingBalance() external view returns (uint256) {
if (isEnoughBalance()) {
return 0;
}
return getUnprocessedAmount() - SOV.balanceOf(address(this));
}
/**
* @notice creates TeamVesting or Vesting contract
* @dev new contract won't be created if account already has contract of the same type
*/
function _createAndGetVesting(VestingData memory vestingData) internal returns (address vesting) {
if (vestingData.governanceControl) {
vestingRegistryLogic.createTeamVesting(
vestingData.tokenOwner,
vestingData.amount,
vestingData.cliff,
vestingData.duration,
vestingData.vestingCreationType
);
} else {
vestingRegistryLogic.createVestingAddr(
vestingData.tokenOwner,
vestingData.amount,
vestingData.cliff,
vestingData.duration,
vestingData.vestingCreationType
);
}
return
_getVesting(
vestingData.tokenOwner,
vestingData.cliff,
vestingData.duration,
vestingData.governanceControl,
vestingData.vestingCreationType
);
}
/**
* @notice returns an address of TeamVesting or Vesting contract (depends on a governance control)
*/
function _getVesting(
address _tokenOwner,
uint256 _cliff,
uint256 _duration,
bool _governanceControl,
uint256 _vestingCreationType
) internal view returns (address vestingAddress) {
if (_governanceControl) {
vestingAddress = vestingRegistryLogic.getTeamVesting(_tokenOwner, _cliff, _duration, _vestingCreationType);
} else {
vestingAddress = vestingRegistryLogic.getVestingAddr(_tokenOwner, _cliff, _duration, _vestingCreationType);
}
}
}
| Staking vested tokens it can be the case when vesting creation and tokens staking can't be done in one transaction because of block gas limit/ | function processStaking() public {
require(vestingCreated, "cannot stake without vesting creation");
if (vestingDataList.length > 0) {
VestingData storage vestingData = vestingDataList[vestingDataList.length - 1];
address vestingAddress =
_getVesting(
vestingData.tokenOwner,
vestingData.cliff,
vestingData.duration,
vestingData.governanceControl,
vestingData.vestingCreationType
);
if (vestingAddress != address(0)) {
VestingLogic vesting = VestingLogic(vestingAddress);
require(SOV.approve(address(vesting), vestingData.amount), "Approve failed");
vesting.stakeTokens(vestingData.amount);
emit TokensStaked(vestingAddress, vestingData.tokenOwner, vestingData.amount);
address tokenOwnerDetails = vestingData.tokenOwner;
delete vestingDataList[vestingDataList.length - 1];
vestingDataList.length--;
emit VestingDataRemoved(msg.sender, tokenOwnerDetails);
}
}
vestingCreated = false;
}
| 996,844 |
/*
____ __ __ __ _
/ __/__ __ ___ / /_ / / ___ / /_ (_)__ __
_\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ /
/___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\
/___/
* Synthetix: SystemSettings.sol
*
* Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/SystemSettings.sol
* Docs: https://docs.synthetix.io/contracts/SystemSettings
*
* Contract Dependencies:
* - IAddressResolver
* - ISystemSettings
* - MixinResolver
* - MixinSystemSettings
* - Owned
* Libraries:
* - SafeDecimalMath
* - SafeMath
*
* MIT License
* ===========
*
* Copyright (c) 2021 Synthetix
*
* 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
*/
pragma solidity ^0.5.16;
// https://docs.synthetix.io/contracts/source/contracts/owned
contract Owned {
address public owner;
address public nominatedOwner;
constructor(address _owner) public {
require(_owner != address(0), "Owner address cannot be 0");
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
function nominateNewOwner(address _owner) external onlyOwner {
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
function acceptOwnership() external {
require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership");
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner {
_onlyOwner();
_;
}
function _onlyOwner() private view {
require(msg.sender == owner, "Only the contract owner may perform this action");
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
// https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver
interface IAddressResolver {
function getAddress(bytes32 name) external view returns (address);
function getSynth(bytes32 key) external view returns (address);
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address);
}
// https://docs.synthetix.io/contracts/source/interfaces/isynth
interface ISynth {
// Views
function currencyKey() external view returns (bytes32);
function transferableSynths(address account) external view returns (uint);
// Mutative functions
function transferAndSettle(address to, uint value) external returns (bool);
function transferFromAndSettle(
address from,
address to,
uint value
) external returns (bool);
// Restricted: used internally to Synthetix
function burn(address account, uint amount) external;
function issue(address account, uint amount) external;
}
// https://docs.synthetix.io/contracts/source/interfaces/iissuer
interface IIssuer {
// Views
function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid);
function availableCurrencyKeys() external view returns (bytes32[] memory);
function availableSynthCount() external view returns (uint);
function availableSynths(uint index) external view returns (ISynth);
function canBurnSynths(address account) external view returns (bool);
function collateral(address account) external view returns (uint);
function collateralisationRatio(address issuer) external view returns (uint);
function collateralisationRatioAndAnyRatesInvalid(address _issuer)
external
view
returns (uint cratio, bool anyRateIsInvalid);
function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance);
function issuanceRatio() external view returns (uint);
function lastIssueEvent(address account) external view returns (uint);
function maxIssuableSynths(address issuer) external view returns (uint maxIssuable);
function minimumStakeTime() external view returns (uint);
function remainingIssuableSynths(address issuer)
external
view
returns (
uint maxIssuable,
uint alreadyIssued,
uint totalSystemDebt
);
function synths(bytes32 currencyKey) external view returns (ISynth);
function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory);
function synthsByAddress(address synthAddress) external view returns (bytes32);
function totalIssuedSynths(bytes32 currencyKey, bool excludeOtherCollateral) external view returns (uint);
function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance)
external
view
returns (uint transferable, bool anyRateIsInvalid);
// Restricted: used internally to Synthetix
function issueSynths(address from, uint amount) external;
function issueSynthsOnBehalf(
address issueFor,
address from,
uint amount
) external;
function issueMaxSynths(address from) external;
function issueMaxSynthsOnBehalf(address issueFor, address from) external;
function burnSynths(address from, uint amount) external;
function burnSynthsOnBehalf(
address burnForAddress,
address from,
uint amount
) external;
function burnSynthsToTarget(address from) external;
function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external;
function burnForRedemption(
address deprecatedSynthProxy,
address account,
uint balance
) external;
function liquidateDelinquentAccount(
address account,
uint susdAmount,
address liquidator
) external returns (uint totalRedeemed, uint amountToLiquidate);
}
// Inheritance
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/addressresolver
contract AddressResolver is Owned, IAddressResolver {
mapping(bytes32 => address) public repository;
constructor(address _owner) public Owned(_owner) {}
/* ========== RESTRICTED FUNCTIONS ========== */
function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner {
require(names.length == destinations.length, "Input lengths must match");
for (uint i = 0; i < names.length; i++) {
bytes32 name = names[i];
address destination = destinations[i];
repository[name] = destination;
emit AddressImported(name, destination);
}
}
/* ========= PUBLIC FUNCTIONS ========== */
function rebuildCaches(MixinResolver[] calldata destinations) external {
for (uint i = 0; i < destinations.length; i++) {
destinations[i].rebuildCache();
}
}
/* ========== VIEWS ========== */
function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) {
for (uint i = 0; i < names.length; i++) {
if (repository[names[i]] != destinations[i]) {
return false;
}
}
return true;
}
function getAddress(bytes32 name) external view returns (address) {
return repository[name];
}
function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) {
address _foundAddress = repository[name];
require(_foundAddress != address(0), reason);
return _foundAddress;
}
function getSynth(bytes32 key) external view returns (address) {
IIssuer issuer = IIssuer(repository["Issuer"]);
require(address(issuer) != address(0), "Cannot find Issuer address");
return address(issuer.synths(key));
}
/* ========== EVENTS ========== */
event AddressImported(bytes32 name, address destination);
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinresolver
contract MixinResolver {
AddressResolver public resolver;
mapping(bytes32 => address) private addressCache;
constructor(address _resolver) internal {
resolver = AddressResolver(_resolver);
}
/* ========== INTERNAL FUNCTIONS ========== */
function combineArrays(bytes32[] memory first, bytes32[] memory second)
internal
pure
returns (bytes32[] memory combination)
{
combination = new bytes32[](first.length + second.length);
for (uint i = 0; i < first.length; i++) {
combination[i] = first[i];
}
for (uint j = 0; j < second.length; j++) {
combination[first.length + j] = second[j];
}
}
/* ========== PUBLIC FUNCTIONS ========== */
// Note: this function is public not external in order for it to be overridden and invoked via super in subclasses
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {}
function rebuildCache() public {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
// The resolver must call this function whenver it updates its state
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// Note: can only be invoked once the resolver has all the targets needed added
address destination =
resolver.requireAndGetAddress(name, string(abi.encodePacked("Resolver missing target: ", name)));
addressCache[name] = destination;
emit CacheUpdated(name, destination);
}
}
/* ========== VIEWS ========== */
function isResolverCached() external view returns (bool) {
bytes32[] memory requiredAddresses = resolverAddressesRequired();
for (uint i = 0; i < requiredAddresses.length; i++) {
bytes32 name = requiredAddresses[i];
// false if our cache is invalid or if the resolver doesn't have the required address
if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) {
return false;
}
}
return true;
}
/* ========== INTERNAL FUNCTIONS ========== */
function requireAndGetAddress(bytes32 name) internal view returns (address) {
address _foundAddress = addressCache[name];
require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name)));
return _foundAddress;
}
/* ========== EVENTS ========== */
event CacheUpdated(bytes32 name, address destination);
}
// https://docs.synthetix.io/contracts/source/interfaces/iflexiblestorage
interface IFlexibleStorage {
// Views
function getUIntValue(bytes32 contractName, bytes32 record) external view returns (uint);
function getUIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (uint[] memory);
function getIntValue(bytes32 contractName, bytes32 record) external view returns (int);
function getIntValues(bytes32 contractName, bytes32[] calldata records) external view returns (int[] memory);
function getAddressValue(bytes32 contractName, bytes32 record) external view returns (address);
function getAddressValues(bytes32 contractName, bytes32[] calldata records) external view returns (address[] memory);
function getBoolValue(bytes32 contractName, bytes32 record) external view returns (bool);
function getBoolValues(bytes32 contractName, bytes32[] calldata records) external view returns (bool[] memory);
function getBytes32Value(bytes32 contractName, bytes32 record) external view returns (bytes32);
function getBytes32Values(bytes32 contractName, bytes32[] calldata records) external view returns (bytes32[] memory);
// Mutative functions
function deleteUIntValue(bytes32 contractName, bytes32 record) external;
function deleteIntValue(bytes32 contractName, bytes32 record) external;
function deleteAddressValue(bytes32 contractName, bytes32 record) external;
function deleteBoolValue(bytes32 contractName, bytes32 record) external;
function deleteBytes32Value(bytes32 contractName, bytes32 record) external;
function setUIntValue(
bytes32 contractName,
bytes32 record,
uint value
) external;
function setUIntValues(
bytes32 contractName,
bytes32[] calldata records,
uint[] calldata values
) external;
function setIntValue(
bytes32 contractName,
bytes32 record,
int value
) external;
function setIntValues(
bytes32 contractName,
bytes32[] calldata records,
int[] calldata values
) external;
function setAddressValue(
bytes32 contractName,
bytes32 record,
address value
) external;
function setAddressValues(
bytes32 contractName,
bytes32[] calldata records,
address[] calldata values
) external;
function setBoolValue(
bytes32 contractName,
bytes32 record,
bool value
) external;
function setBoolValues(
bytes32 contractName,
bytes32[] calldata records,
bool[] calldata values
) external;
function setBytes32Value(
bytes32 contractName,
bytes32 record,
bytes32 value
) external;
function setBytes32Values(
bytes32 contractName,
bytes32[] calldata records,
bytes32[] calldata values
) external;
}
// Internal references
// https://docs.synthetix.io/contracts/source/contracts/mixinsystemsettings
contract MixinSystemSettings is MixinResolver {
bytes32 internal constant SETTING_CONTRACT_NAME = "SystemSettings";
bytes32 internal constant SETTING_WAITING_PERIOD_SECS = "waitingPeriodSecs";
bytes32 internal constant SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR = "priceDeviationThresholdFactor";
bytes32 internal constant SETTING_ISSUANCE_RATIO = "issuanceRatio";
bytes32 internal constant SETTING_FEE_PERIOD_DURATION = "feePeriodDuration";
bytes32 internal constant SETTING_TARGET_THRESHOLD = "targetThreshold";
bytes32 internal constant SETTING_LIQUIDATION_DELAY = "liquidationDelay";
bytes32 internal constant SETTING_LIQUIDATION_RATIO = "liquidationRatio";
bytes32 internal constant SETTING_LIQUIDATION_PENALTY = "liquidationPenalty";
bytes32 internal constant SETTING_RATE_STALE_PERIOD = "rateStalePeriod";
bytes32 internal constant SETTING_EXCHANGE_FEE_RATE = "exchangeFeeRate";
bytes32 internal constant SETTING_MINIMUM_STAKE_TIME = "minimumStakeTime";
bytes32 internal constant SETTING_AGGREGATOR_WARNING_FLAGS = "aggregatorWarningFlags";
bytes32 internal constant SETTING_TRADING_REWARDS_ENABLED = "tradingRewardsEnabled";
bytes32 internal constant SETTING_DEBT_SNAPSHOT_STALE_TIME = "debtSnapshotStaleTime";
bytes32 internal constant SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT = "crossDomainDepositGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT = "crossDomainEscrowGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT = "crossDomainRewardGasLimit";
bytes32 internal constant SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT = "crossDomainWithdrawalGasLimit";
bytes32 internal constant SETTING_ETHER_WRAPPER_MAX_ETH = "etherWrapperMaxETH";
bytes32 internal constant SETTING_ETHER_WRAPPER_MINT_FEE_RATE = "etherWrapperMintFeeRate";
bytes32 internal constant SETTING_ETHER_WRAPPER_BURN_FEE_RATE = "etherWrapperBurnFeeRate";
bytes32 internal constant SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK = "atomicMaxVolumePerBlock";
bytes32 internal constant SETTING_ATOMIC_TWAP_WINDOW = "atomicTwapWindow";
bytes32 internal constant SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING = "atomicEquivalentForDexPricing";
bytes32 internal constant SETTING_ATOMIC_EXCHANGE_FEE_RATE = "atomicExchangeFeeRate";
bytes32 internal constant SETTING_ATOMIC_PRICE_BUFFER = "atomicPriceBuffer";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = "atomicVolConsiderationWindow";
bytes32 internal constant SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD = "atomicVolUpdateThreshold";
bytes32 internal constant CONTRACT_FLEXIBLESTORAGE = "FlexibleStorage";
enum CrossDomainMessageGasLimits {Deposit, Escrow, Reward, Withdrawal}
constructor(address _resolver) internal MixinResolver(_resolver) {}
function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {
addresses = new bytes32[](1);
addresses[0] = CONTRACT_FLEXIBLESTORAGE;
}
function flexibleStorage() internal view returns (IFlexibleStorage) {
return IFlexibleStorage(requireAndGetAddress(CONTRACT_FLEXIBLESTORAGE));
}
function _getGasLimitSetting(CrossDomainMessageGasLimits gasLimitType) internal pure returns (bytes32) {
if (gasLimitType == CrossDomainMessageGasLimits.Deposit) {
return SETTING_CROSS_DOMAIN_DEPOSIT_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Escrow) {
return SETTING_CROSS_DOMAIN_ESCROW_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Reward) {
return SETTING_CROSS_DOMAIN_REWARD_GAS_LIMIT;
} else if (gasLimitType == CrossDomainMessageGasLimits.Withdrawal) {
return SETTING_CROSS_DOMAIN_WITHDRAWAL_GAS_LIMIT;
} else {
revert("Unknown gas limit type");
}
}
function getCrossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, _getGasLimitSetting(gasLimitType));
}
function getTradingRewardsEnabled() internal view returns (bool) {
return flexibleStorage().getBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED);
}
function getWaitingPeriodSecs() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS);
}
function getPriceDeviationThresholdFactor() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR);
}
function getIssuanceRatio() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO);
}
function getFeePeriodDuration() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION);
}
function getTargetThreshold() internal view returns (uint) {
// lookup on flexible storage directly for gas savings (rather than via SystemSettings)
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD);
}
function getLiquidationDelay() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY);
}
function getLiquidationRatio() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO);
}
function getLiquidationPenalty() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY);
}
function getRateStalePeriod() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD);
}
function getExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getMinimumStakeTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME);
}
function getAggregatorWarningFlags() internal view returns (address) {
return flexibleStorage().getAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS);
}
function getDebtSnapshotStaleTime() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME);
}
function getEtherWrapperMaxETH() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH);
}
function getEtherWrapperMintFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE);
}
function getEtherWrapperBurnFeeRate() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE);
}
function getAtomicMaxVolumePerBlock() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK);
}
function getAtomicTwapWindow() internal view returns (uint) {
return flexibleStorage().getUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW);
}
function getAtomicEquivalentForDexPricing(bytes32 currencyKey) internal view returns (address) {
return
flexibleStorage().getAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, currencyKey))
);
}
function getAtomicExchangeFeeRate(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, currencyKey))
);
}
function getAtomicPriceBuffer(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, currencyKey))
);
}
function getAtomicVolatilityConsiderationWindow(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, currencyKey))
);
}
function getAtomicVolatilityUpdateThreshold(bytes32 currencyKey) internal view returns (uint) {
return
flexibleStorage().getUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, currencyKey))
);
}
}
// https://docs.synthetix.io/contracts/source/interfaces/isystemsettings
interface ISystemSettings {
// Views
function waitingPeriodSecs() external view returns (uint);
function priceDeviationThresholdFactor() external view returns (uint);
function issuanceRatio() external view returns (uint);
function feePeriodDuration() external view returns (uint);
function targetThreshold() external view returns (uint);
function liquidationDelay() external view returns (uint);
function liquidationRatio() external view returns (uint);
function liquidationPenalty() external view returns (uint);
function rateStalePeriod() external view returns (uint);
function exchangeFeeRate(bytes32 currencyKey) external view returns (uint);
function minimumStakeTime() external view returns (uint);
function debtSnapshotStaleTime() external view returns (uint);
function aggregatorWarningFlags() external view returns (address);
function tradingRewardsEnabled() external view returns (bool);
// function crossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) external view returns (uint);
function etherWrapperMaxETH() external view returns (uint);
function etherWrapperBurnFeeRate() external view returns (uint);
function etherWrapperMintFeeRate() external view returns (uint);
function atomicMaxVolumePerBlock() external view returns (uint);
function atomicTwapWindow() external view returns (uint);
function atomicEquivalentForDexPricing(bytes32 currencyKey) external view returns (address);
function atomicExchangeFeeRate(bytes32 currencyKey) external view returns (uint);
function atomicPriceBuffer(bytes32 currencyKey) external view returns (uint);
function atomicVolatilityConsiderationWindow(bytes32 currencyKey) external view returns (uint);
function atomicVolatilityUpdateThreshold(bytes32 currencyKey) external view returns (uint);
}
/**
* @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) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// Libraries
// https://docs.synthetix.io/contracts/source/libraries/safedecimalmath
library SafeDecimalMath {
using SafeMath for uint;
/* Number of decimal places in the representations. */
uint8 public constant decimals = 18;
uint8 public constant highPrecisionDecimals = 27;
/* The number representing 1.0. */
uint public constant UNIT = 10**uint(decimals);
/* The number representing 1.0 for higher fidelity numbers. */
uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals);
uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals);
/**
* @return Provides an interface to UNIT.
*/
function unit() external pure returns (uint) {
return UNIT;
}
/**
* @return Provides an interface to PRECISE_UNIT.
*/
function preciseUnit() external pure returns (uint) {
return PRECISE_UNIT;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256. As this is an integer division,
* the internal division always rounds down. This helps save on gas. Rounding
* is more expensive on gas.
*/
function multiplyDecimal(uint x, uint y) internal pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
return x.mul(y) / UNIT;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of the specified precision unit.
*
* @dev The operands should be in the form of a the specified unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function _multiplyDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
/* Divide by UNIT to remove the extra factor introduced by the product. */
uint quotientTimesTen = x.mul(y) / (precisionUnit / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a precise unit.
*
* @dev The operands should be in the precise unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @return The result of safely multiplying x and y, interpreting the operands
* as fixed-point decimals of a standard unit.
*
* @dev The operands should be in the standard unit factor which will be
* divided out after the product of x and y is evaluated, so that product must be
* less than 2**256.
*
* Unlike multiplyDecimal, this function rounds the result to the nearest increment.
* Rounding is useful when you need to retain fidelity for small decimal numbers
* (eg. small fractions or percentages).
*/
function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) {
return _multiplyDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is a high
* precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and UNIT must be less than 2**256. As
* this is an integer division, the result is always rounded down.
* This helps save on gas. Rounding is more expensive on gas.
*/
function divideDecimal(uint x, uint y) internal pure returns (uint) {
/* Reintroduce the UNIT factor that will be divided out by y. */
return x.mul(UNIT).div(y);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* decimal in the precision unit specified in the parameter.
*
* @dev y is divided after the product of x and the specified precision unit
* is evaluated, so the product of x and the specified precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function _divideDecimalRound(
uint x,
uint y,
uint precisionUnit
) private pure returns (uint) {
uint resultTimesTen = x.mul(precisionUnit * 10).div(y);
if (resultTimesTen % 10 >= 5) {
resultTimesTen += 10;
}
return resultTimesTen / 10;
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* standard precision decimal.
*
* @dev y is divided after the product of x and the standard precision unit
* is evaluated, so the product of x and the standard precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRound(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, UNIT);
}
/**
* @return The result of safely dividing x and y. The return value is as a rounded
* high precision decimal.
*
* @dev y is divided after the product of x and the high precision unit
* is evaluated, so the product of x and the high precision unit must
* be less than 2**256. The result is rounded to the nearest increment.
*/
function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) {
return _divideDecimalRound(x, y, PRECISE_UNIT);
}
/**
* @dev Convert a standard decimal representation to a high precision one.
*/
function decimalToPreciseDecimal(uint i) internal pure returns (uint) {
return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR);
}
/**
* @dev Convert a high precision decimal to a standard decimal representation.
*/
function preciseDecimalToDecimal(uint i) internal pure returns (uint) {
uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10);
if (quotientTimesTen % 10 >= 5) {
quotientTimesTen += 10;
}
return quotientTimesTen / 10;
}
// Computes `a - b`, setting the value to 0 if b > a.
function floorsub(uint a, uint b) internal pure returns (uint) {
return b >= a ? 0 : a - b;
}
}
// Inheritance
// Libraries
// https://docs.synthetix.io/contracts/source/contracts/systemsettings
contract SystemSettings is Owned, MixinSystemSettings, ISystemSettings {
using SafeMath for uint;
using SafeDecimalMath for uint;
// No more synths may be issued than the value of SNX backing them.
uint public constant MAX_ISSUANCE_RATIO = 1e18;
// The fee period must be between 1 day and 60 days.
uint public constant MIN_FEE_PERIOD_DURATION = 1 days;
uint public constant MAX_FEE_PERIOD_DURATION = 60 days;
uint public constant MAX_TARGET_THRESHOLD = 50;
uint public constant MAX_LIQUIDATION_RATIO = 1e18; // 100% issuance ratio
uint public constant MAX_LIQUIDATION_PENALTY = 1e18 / 4; // Max 25% liquidation penalty / bonus
uint public constant RATIO_FROM_TARGET_BUFFER = 2e18; // 200% - mininimum buffer between issuance ratio and liquidation ratio
uint public constant MAX_LIQUIDATION_DELAY = 30 days;
uint public constant MIN_LIQUIDATION_DELAY = 1 days;
// Exchange fee may not exceed 10%.
uint public constant MAX_EXCHANGE_FEE_RATE = 1e18 / 10;
// Minimum Stake time may not exceed 1 weeks.
uint public constant MAX_MINIMUM_STAKE_TIME = 1 weeks;
uint public constant MAX_CROSS_DOMAIN_GAS_LIMIT = 8e6;
uint public constant MIN_CROSS_DOMAIN_GAS_LIMIT = 3e6;
// TODO(liamz): these are simple bounds for the mint/burn fee rates (max 100%).
// Can we come up with better values?
uint public constant MAX_ETHER_WRAPPER_MINT_FEE_RATE = 1e18;
uint public constant MAX_ETHER_WRAPPER_BURN_FEE_RATE = 1e18;
// Atomic block volume limit is encoded as uint192.
uint public constant MAX_ATOMIC_VOLUME_PER_BLOCK = uint192(-1);
// TWAP window must be between 1 min and 1 day.
uint public constant MIN_ATOMIC_TWAP_WINDOW = 60;
uint public constant MAX_ATOMIC_TWAP_WINDOW = 86400;
// Volatility consideration window must be between 1 min and 1 day.
uint public constant MIN_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = 60;
uint public constant MAX_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW = 86400;
constructor(address _owner, address _resolver) public Owned(_owner) MixinSystemSettings(_resolver) {}
// ========== VIEWS ==========
// SIP-37 Fee Reclamation
// The number of seconds after an exchange is executed that must be waited
// before settlement.
function waitingPeriodSecs() external view returns (uint) {
return getWaitingPeriodSecs();
}
// SIP-65 Decentralized Circuit Breaker
// The factor amount expressed in decimal format
// E.g. 3e18 = factor 3, meaning movement up to 3x and above or down to 1/3x and below
function priceDeviationThresholdFactor() external view returns (uint) {
return getPriceDeviationThresholdFactor();
}
// The raio of collateral
// Expressed in 18 decimals. So 800% cratio is 100/800 = 0.125 (0.125e18)
function issuanceRatio() external view returns (uint) {
return getIssuanceRatio();
}
// How long a fee period lasts at a minimum. It is required for
// anyone to roll over the periods, so they are not guaranteed
// to roll over at exactly this duration, but the contract enforces
// that they cannot roll over any quicker than this duration.
function feePeriodDuration() external view returns (uint) {
return getFeePeriodDuration();
}
// Users are unable to claim fees if their collateralisation ratio drifts out of target threshold
function targetThreshold() external view returns (uint) {
return getTargetThreshold();
}
// SIP-15 Liquidations
// liquidation time delay after address flagged (seconds)
function liquidationDelay() external view returns (uint) {
return getLiquidationDelay();
}
// SIP-15 Liquidations
// issuance ratio when account can be flagged for liquidation (with 18 decimals), e.g 0.5 issuance ratio
// when flag means 1/0.5 = 200% cratio
function liquidationRatio() external view returns (uint) {
return getLiquidationRatio();
}
// SIP-15 Liquidations
// penalty taken away from target of liquidation (with 18 decimals). E.g. 10% is 0.1e18
function liquidationPenalty() external view returns (uint) {
return getLiquidationPenalty();
}
// How long will the ExchangeRates contract assume the rate of any asset is correct
function rateStalePeriod() external view returns (uint) {
return getRateStalePeriod();
}
function exchangeFeeRate(bytes32 currencyKey) external view returns (uint) {
return getExchangeFeeRate(currencyKey);
}
function minimumStakeTime() external view returns (uint) {
return getMinimumStakeTime();
}
function debtSnapshotStaleTime() external view returns (uint) {
return getDebtSnapshotStaleTime();
}
function aggregatorWarningFlags() external view returns (address) {
return getAggregatorWarningFlags();
}
// SIP-63 Trading incentives
// determines if Exchanger records fee entries in TradingRewards
function tradingRewardsEnabled() external view returns (bool) {
return getTradingRewardsEnabled();
}
function crossDomainMessageGasLimit(CrossDomainMessageGasLimits gasLimitType) external view returns (uint) {
return getCrossDomainMessageGasLimit(gasLimitType);
}
// SIP 112: ETH Wrappr
// The maximum amount of ETH held by the EtherWrapper.
function etherWrapperMaxETH() external view returns (uint) {
return getEtherWrapperMaxETH();
}
// SIP 112: ETH Wrappr
// The fee for depositing ETH into the EtherWrapper.
function etherWrapperMintFeeRate() external view returns (uint) {
return getEtherWrapperMintFeeRate();
}
// SIP 112: ETH Wrappr
// The fee for burning sETH and releasing ETH from the EtherWrapper.
function etherWrapperBurnFeeRate() external view returns (uint) {
return getEtherWrapperBurnFeeRate();
}
// SIP-120 Atomic exchanges
// max allowed volume per block for atomic exchanges
function atomicMaxVolumePerBlock() external view returns (uint) {
return getAtomicMaxVolumePerBlock();
}
// SIP-120 Atomic exchanges
// time window (in seconds) for TWAP prices when considered for atomic exchanges
function atomicTwapWindow() external view returns (uint) {
return getAtomicTwapWindow();
}
// SIP-120 Atomic exchanges
// equivalent asset to use for a synth when considering external prices for atomic exchanges
function atomicEquivalentForDexPricing(bytes32 currencyKey) external view returns (address) {
return getAtomicEquivalentForDexPricing(currencyKey);
}
// SIP-120 Atomic exchanges
// fee rate override for atomic exchanges into a synth
function atomicExchangeFeeRate(bytes32 currencyKey) external view returns (uint) {
return getAtomicExchangeFeeRate(currencyKey);
}
// SIP-120 Atomic exchanges
// price dampener for chainlink prices when considered for atomic exchanges
function atomicPriceBuffer(bytes32 currencyKey) external view returns (uint) {
return getAtomicPriceBuffer(currencyKey);
}
// SIP-120 Atomic exchanges
// consideration window for determining synth volatility
function atomicVolatilityConsiderationWindow(bytes32 currencyKey) external view returns (uint) {
return getAtomicVolatilityConsiderationWindow(currencyKey);
}
// SIP-120 Atomic exchanges
// update threshold for determining synth volatility
function atomicVolatilityUpdateThreshold(bytes32 currencyKey) external view returns (uint) {
return getAtomicVolatilityUpdateThreshold(currencyKey);
}
// ========== RESTRICTED ==========
function setCrossDomainMessageGasLimit(CrossDomainMessageGasLimits _gasLimitType, uint _crossDomainMessageGasLimit)
external
onlyOwner
{
require(
_crossDomainMessageGasLimit >= MIN_CROSS_DOMAIN_GAS_LIMIT &&
_crossDomainMessageGasLimit <= MAX_CROSS_DOMAIN_GAS_LIMIT,
"Out of range xDomain gasLimit"
);
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
_getGasLimitSetting(_gasLimitType),
_crossDomainMessageGasLimit
);
emit CrossDomainMessageGasLimitChanged(_gasLimitType, _crossDomainMessageGasLimit);
}
function setTradingRewardsEnabled(bool _tradingRewardsEnabled) external onlyOwner {
flexibleStorage().setBoolValue(SETTING_CONTRACT_NAME, SETTING_TRADING_REWARDS_ENABLED, _tradingRewardsEnabled);
emit TradingRewardsEnabled(_tradingRewardsEnabled);
}
function setWaitingPeriodSecs(uint _waitingPeriodSecs) external onlyOwner {
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_WAITING_PERIOD_SECS, _waitingPeriodSecs);
emit WaitingPeriodSecsUpdated(_waitingPeriodSecs);
}
function setPriceDeviationThresholdFactor(uint _priceDeviationThresholdFactor) external onlyOwner {
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
SETTING_PRICE_DEVIATION_THRESHOLD_FACTOR,
_priceDeviationThresholdFactor
);
emit PriceDeviationThresholdUpdated(_priceDeviationThresholdFactor);
}
function setIssuanceRatio(uint _issuanceRatio) external onlyOwner {
require(_issuanceRatio <= MAX_ISSUANCE_RATIO, "New issuance ratio cannot exceed MAX_ISSUANCE_RATIO");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ISSUANCE_RATIO, _issuanceRatio);
emit IssuanceRatioUpdated(_issuanceRatio);
}
function setFeePeriodDuration(uint _feePeriodDuration) external onlyOwner {
require(_feePeriodDuration >= MIN_FEE_PERIOD_DURATION, "value < MIN_FEE_PERIOD_DURATION");
require(_feePeriodDuration <= MAX_FEE_PERIOD_DURATION, "value > MAX_FEE_PERIOD_DURATION");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_FEE_PERIOD_DURATION, _feePeriodDuration);
emit FeePeriodDurationUpdated(_feePeriodDuration);
}
function setTargetThreshold(uint _percent) external onlyOwner {
require(_percent <= MAX_TARGET_THRESHOLD, "Threshold too high");
uint _targetThreshold = _percent.mul(SafeDecimalMath.unit()).div(100);
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_TARGET_THRESHOLD, _targetThreshold);
emit TargetThresholdUpdated(_targetThreshold);
}
function setLiquidationDelay(uint time) external onlyOwner {
require(time <= MAX_LIQUIDATION_DELAY, "Must be less than 30 days");
require(time >= MIN_LIQUIDATION_DELAY, "Must be greater than 1 day");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_DELAY, time);
emit LiquidationDelayUpdated(time);
}
// The collateral / issuance ratio ( debt / collateral ) is higher when there is less collateral backing their debt
// Upper bound liquidationRatio is 1 + penalty (100% + 10% = 110%) to allow collateral value to cover debt and liquidation penalty
function setLiquidationRatio(uint _liquidationRatio) external onlyOwner {
require(
_liquidationRatio <= MAX_LIQUIDATION_RATIO.divideDecimal(SafeDecimalMath.unit().add(getLiquidationPenalty())),
"liquidationRatio > MAX_LIQUIDATION_RATIO / (1 + penalty)"
);
// MIN_LIQUIDATION_RATIO is a product of target issuance ratio * RATIO_FROM_TARGET_BUFFER
// Ensures that liquidation ratio is set so that there is a buffer between the issuance ratio and liquidation ratio.
uint MIN_LIQUIDATION_RATIO = getIssuanceRatio().multiplyDecimal(RATIO_FROM_TARGET_BUFFER);
require(_liquidationRatio >= MIN_LIQUIDATION_RATIO, "liquidationRatio < MIN_LIQUIDATION_RATIO");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_RATIO, _liquidationRatio);
emit LiquidationRatioUpdated(_liquidationRatio);
}
function setLiquidationPenalty(uint penalty) external onlyOwner {
require(penalty <= MAX_LIQUIDATION_PENALTY, "penalty > MAX_LIQUIDATION_PENALTY");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_LIQUIDATION_PENALTY, penalty);
emit LiquidationPenaltyUpdated(penalty);
}
function setRateStalePeriod(uint period) external onlyOwner {
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_RATE_STALE_PERIOD, period);
emit RateStalePeriodUpdated(period);
}
function setExchangeFeeRateForSynths(bytes32[] calldata synthKeys, uint256[] calldata exchangeFeeRates)
external
onlyOwner
{
require(synthKeys.length == exchangeFeeRates.length, "Array lengths dont match");
for (uint i = 0; i < synthKeys.length; i++) {
require(exchangeFeeRates[i] <= MAX_EXCHANGE_FEE_RATE, "MAX_EXCHANGE_FEE_RATE exceeded");
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_EXCHANGE_FEE_RATE, synthKeys[i])),
exchangeFeeRates[i]
);
emit ExchangeFeeUpdated(synthKeys[i], exchangeFeeRates[i]);
}
}
function setMinimumStakeTime(uint _seconds) external onlyOwner {
require(_seconds <= MAX_MINIMUM_STAKE_TIME, "stake time exceed maximum 1 week");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_MINIMUM_STAKE_TIME, _seconds);
emit MinimumStakeTimeUpdated(_seconds);
}
function setDebtSnapshotStaleTime(uint _seconds) external onlyOwner {
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_DEBT_SNAPSHOT_STALE_TIME, _seconds);
emit DebtSnapshotStaleTimeUpdated(_seconds);
}
function setAggregatorWarningFlags(address _flags) external onlyOwner {
require(_flags != address(0), "Valid address must be given");
flexibleStorage().setAddressValue(SETTING_CONTRACT_NAME, SETTING_AGGREGATOR_WARNING_FLAGS, _flags);
emit AggregatorWarningFlagsUpdated(_flags);
}
function setEtherWrapperMaxETH(uint _maxETH) external onlyOwner {
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MAX_ETH, _maxETH);
emit EtherWrapperMaxETHUpdated(_maxETH);
}
function setEtherWrapperMintFeeRate(uint _rate) external onlyOwner {
require(_rate <= MAX_ETHER_WRAPPER_MINT_FEE_RATE, "rate > MAX_ETHER_WRAPPER_MINT_FEE_RATE");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_MINT_FEE_RATE, _rate);
emit EtherWrapperMintFeeRateUpdated(_rate);
}
function setEtherWrapperBurnFeeRate(uint _rate) external onlyOwner {
require(_rate <= MAX_ETHER_WRAPPER_BURN_FEE_RATE, "rate > MAX_ETHER_WRAPPER_BURN_FEE_RATE");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ETHER_WRAPPER_BURN_FEE_RATE, _rate);
emit EtherWrapperBurnFeeRateUpdated(_rate);
}
function setAtomicMaxVolumePerBlock(uint _maxVolume) external onlyOwner {
require(_maxVolume <= MAX_ATOMIC_VOLUME_PER_BLOCK, "Atomic max volume exceed maximum uint192");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_MAX_VOLUME_PER_BLOCK, _maxVolume);
emit AtomicMaxVolumePerBlockUpdated(_maxVolume);
}
function setAtomicTwapWindow(uint _window) external onlyOwner {
require(_window >= MIN_ATOMIC_TWAP_WINDOW, "Atomic twap window under minimum 1 min");
require(_window <= MAX_ATOMIC_TWAP_WINDOW, "Atomic twap window exceed maximum 1 day");
flexibleStorage().setUIntValue(SETTING_CONTRACT_NAME, SETTING_ATOMIC_TWAP_WINDOW, _window);
emit AtomicTwapWindowUpdated(_window);
}
function setAtomicEquivalentForDexPricing(bytes32 _currencyKey, address _equivalent) external onlyOwner {
flexibleStorage().setAddressValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EQUIVALENT_FOR_DEX_PRICING, _currencyKey)),
_equivalent
);
emit AtomicEquivalentForDexPricingUpdated(_currencyKey, _equivalent);
}
function setAtomicExchangeFeeRate(bytes32 _currencyKey, uint256 _exchangeFeeRate) external onlyOwner {
require(_exchangeFeeRate <= MAX_EXCHANGE_FEE_RATE, "MAX_EXCHANGE_FEE_RATE exceeded");
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_EXCHANGE_FEE_RATE, _currencyKey)),
_exchangeFeeRate
);
emit AtomicExchangeFeeUpdated(_currencyKey, _exchangeFeeRate);
}
function setAtomicPriceBuffer(bytes32 _currencyKey, uint _buffer) external onlyOwner {
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_PRICE_BUFFER, _currencyKey)),
_buffer
);
emit AtomicPriceBufferUpdated(_currencyKey, _buffer);
}
function setAtomicVolatilityConsiderationWindow(bytes32 _currencyKey, uint _window) external onlyOwner {
if (_window != 0) {
require(
_window >= MIN_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW,
"Atomic volatility consideration window under minimum 1 min"
);
require(
_window <= MAX_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW,
"Atomic volatility consideration window exceed maximum 1 day"
);
}
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_CONSIDERATION_WINDOW, _currencyKey)),
_window
);
emit AtomicVolatilityConsiderationWindowUpdated(_currencyKey, _window);
}
function setAtomicVolatilityUpdateThreshold(bytes32 _currencyKey, uint _threshold) external onlyOwner {
flexibleStorage().setUIntValue(
SETTING_CONTRACT_NAME,
keccak256(abi.encodePacked(SETTING_ATOMIC_VOLATILITY_UPDATE_THRESHOLD, _currencyKey)),
_threshold
);
emit AtomicVolatilityUpdateThresholdUpdated(_currencyKey, _threshold);
}
// ========== EVENTS ==========
event CrossDomainMessageGasLimitChanged(CrossDomainMessageGasLimits gasLimitType, uint newLimit);
event TradingRewardsEnabled(bool enabled);
event WaitingPeriodSecsUpdated(uint waitingPeriodSecs);
event PriceDeviationThresholdUpdated(uint threshold);
event IssuanceRatioUpdated(uint newRatio);
event FeePeriodDurationUpdated(uint newFeePeriodDuration);
event TargetThresholdUpdated(uint newTargetThreshold);
event LiquidationDelayUpdated(uint newDelay);
event LiquidationRatioUpdated(uint newRatio);
event LiquidationPenaltyUpdated(uint newPenalty);
event RateStalePeriodUpdated(uint rateStalePeriod);
event ExchangeFeeUpdated(bytes32 synthKey, uint newExchangeFeeRate);
event MinimumStakeTimeUpdated(uint minimumStakeTime);
event DebtSnapshotStaleTimeUpdated(uint debtSnapshotStaleTime);
event AggregatorWarningFlagsUpdated(address flags);
event EtherWrapperMaxETHUpdated(uint maxETH);
event EtherWrapperMintFeeRateUpdated(uint rate);
event EtherWrapperBurnFeeRateUpdated(uint rate);
event AtomicMaxVolumePerBlockUpdated(uint newMaxVolume);
event AtomicTwapWindowUpdated(uint newWindow);
event AtomicEquivalentForDexPricingUpdated(bytes32 synthKey, address equivalent);
event AtomicExchangeFeeUpdated(bytes32 synthKey, uint newExchangeFeeRate);
event AtomicPriceBufferUpdated(bytes32 synthKey, uint newBuffer);
event AtomicVolatilityConsiderationWindowUpdated(bytes32 synthKey, uint newVolatilityConsiderationWindow);
event AtomicVolatilityUpdateThresholdUpdated(bytes32 synthKey, uint newVolatilityUpdateThreshold);
} | How long a fee period lasts at a minimum. It is required for anyone to roll over the periods, so they are not guaranteed to roll over at exactly this duration, but the contract enforces that they cannot roll over any quicker than this duration. | function feePeriodDuration() external view returns (uint) {
return getFeePeriodDuration();
}
| 242,127 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_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);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
/// @title Fenerbahçe Token Contract
/// @author Stoken/Paribu
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
contract FB_v1 is ERC20Upgradeable, OwnableUpgradeable, PausableUpgradeable {
/// @dev Holds blacklisted addresses
mapping(address => bool) private _blacklist;
// Minting vars start //
/// @dev Minting vars to calculate and track minting rounds
mapping(uint8 => uint256) private _mintingDates;
mapping(uint8 => uint256) private _mintingAmounts;
uint8 private _latestMintRound;
uint256 private _remainingMintingAmount;
// Minting vars end //
// Locking vars start //
/// @dev Locking vars to calculate and track locking
address private _presaleLocked;
uint256 private _nextUnlockAt;
uint256 private _lastUnlockAt;
uint8 private _latestUnlockRound;
uint256 private _presaleLockedAmount;
// Locking vars end //
/// @dev Minter address
address private _minter;
/// @dev Address to mint tokens for
address private _mintingAddress;
modifier onlyMinter() {
require(msg.sender == _minter, "Only minter is allowed to call");
_;
}
/// @dev Initializes contract, set presale locked amounts, setup minting and lock logic
/// @param name Name of the contract
/// @param symbol Symbol of the contract
/// @param mintingAddress Address to mint tokens
/// @param presaleLocked Address to hold locked presale address
/// @param minter Minter address
/// @param address1 Mint address 1
/// @param address2 Mint address 2
/// @param address3 Mint address 3
/// @param address4 Mint address 4
/// @param address5 Mint address 5
function initialize(
string memory name,
string memory symbol,
address mintingAddress,
address presaleLocked,
address minter,
address address1,
address address2,
address address3,
address address4,
address address5
) external initializer {
__ERC20_init(name, symbol);
__Ownable_init_unchained();
__Pausable_init_unchained();
_presaleLockedAmount = 20000000 * 1e6;
_mintingAddress = mintingAddress;
_minter = minter;
_presaleLocked = presaleLocked;
setupLocks();
setupMintingRounds();
_mint(address1, 1700000 * 1e6);
_mint(address2, 1750000 * 1e6);
_mint(address3, 1800000 * 1e6);
_mint(address4, 1200000 * 1e6);
_mint(address5, 2180000 * 1e6);
}
/// @dev Returns token decimals
/// @return uint8
function decimals() public pure override returns (uint8) {
return 6;
}
/// @dev Burns tokens, callable only by the owner
/// @return bool
function burn(uint256 amount) external onlyOwner returns (bool) {
_burn(_msgSender(), amount);
return true;
}
/// @dev Adds an address to blacklist
/// @return bool
function blacklist(address account) external onlyOwner returns (bool) {
_blacklist[account] = true;
return true;
}
/// @dev Removes an address from blacklist
/// @return bool
function unblacklist(address account) external onlyOwner returns (bool) {
delete _blacklist[account];
return true;
}
/// @dev Checks if an address is blacklisted
/// @return bool
function blacklisted(address account) external view virtual returns (bool) {
return _blacklist[account];
}
/// @dev Pauses token transfers
/// @return bool
function pause() external onlyOwner whenNotPaused returns (bool) {
_pause();
return true;
}
/// @dev Unpauses token transfers
/// @return bool
function unpause() external onlyOwner whenPaused returns (bool) {
_unpause();
return true;
}
/// @dev Returns presale locked amount
/// @return uint256
function presaleLockedAmount() external view returns (uint256) {
return _presaleLockedAmount;
}
/// @dev Returns remaining minting amount
/// @return uint256
function remainingMintingAmount() external view returns (uint256) {
return _remainingMintingAmount;
}
/// @dev Returns next minting round
/// @return uint8
function currentMintRound() internal view returns (uint8) {
return _latestMintRound + 1;
}
/// @dev Mints next round tokens, callable only by the owner
function mint() external onlyMinter {
require(_mintingDates[currentMintRound()] < block.timestamp, "Too early to mint next round");
require(_latestMintRound < 73, "Minting is over");
_mint(_mintingAddress, _mintingAmounts[currentMintRound()]);
_remainingMintingAmount -= _mintingAmounts[currentMintRound()];
_latestMintRound++;
}
/// @dev Changes minting address, callable only by current minting address
/// @param newAddress New minting address
function changeMintingAddress(address newAddress) external {
require(_mintingAddress == msg.sender, "Can not change address");
_mintingAddress = newAddress;
}
/// @dev Changes minter, callable only by the owner
/// @param newAddress New minter address
function changeMinter(address newAddress) external onlyOwner {
_minter = newAddress;
}
/// @dev Returns minting address
/// @return address
function mintingAddress() external view returns (address) {
return _mintingAddress;
}
/// @dev Returns minter
/// @return address
function minter() external view returns (address) {
return _minter;
}
/// @dev Setups minting rounds, will be called only on initialization
function setupMintingRounds() internal {
uint256 nextMintingAt = 1631722020; // 15 Sep 2021 19:07:00
for (uint8 i = 1; i <= 73; i++) {
_mintingDates[i] = nextMintingAt;
nextMintingAt += 30 days;
if (i < 53 && (i + 4) % 12 != 0) {
// mints for marketing & tech
uint256 mintingAmount = i <= 17 ? 938959 * 1e6 : 938958 * 1e6;
_mintingAmounts[i] = mintingAmount;
_remainingMintingAmount += mintingAmount;
continue;
}
// mints for treasury
_mintingAmounts[i] = 4680000 * 1e6;
_remainingMintingAmount += 4680000 * 1e6;
}
}
/// @dev Setups next and last unlock date and mints presale locks, will be called only on initialization
function setupLocks() internal {
_nextUnlockAt = 1652630820; // 15 May 2022 19:07:00
_lastUnlockAt = _nextUnlockAt + 420 days;
_mint(_presaleLocked, _presaleLockedAmount);
}
/// @dev Setups next and last unlock date and mints presale locks, will be called only on initialization
/// @param from Address to check locked amount
/// @param amount To check if sent amount available for presale account
function checkLockedAmount(address from, uint256 amount) internal {
// checks locked account on every transfer and decrease locked amount if conditions met
if (from == _presaleLocked && _presaleLockedAmount > 0) {
// runs a while loop to update locked amount
while (_nextUnlockAt <= block.timestamp && _nextUnlockAt <= _lastUnlockAt) {
_latestUnlockRound++;
uint256 unlockAmount = _latestUnlockRound <= 5 ? 1333334 * 1e6 : 1333333 * 1e6;
// increases next unlock timestamp for 30 days
_nextUnlockAt += 30 days;
_presaleLockedAmount -= unlockAmount;
}
// reverts transaction if available balance is insufficient
require(balanceOf(from) >= amount + _presaleLockedAmount, "insufficient funds");
}
}
/** @dev Standard ERC20 hook,
checks if transfer paused,
checks from or to addresses is blacklisted
checks available balance if from address is presaleLocked address
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
require(!paused(), "ERC20Pausable: token transfer while paused");
require(!_blacklist[from], "Token transfer from blacklisted address");
require(!_blacklist[to], "Token transfer to blacklisted address");
checkLockedAmount(from, amount);
}
}
| Changes minting address, callable only by current minting address newAddress New minting address | function changeMintingAddress(address newAddress) external {
require(_mintingAddress == msg.sender, "Can not change address");
_mintingAddress = newAddress;
}
| 14,906,512 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
pragma experimental ABIEncoderV2;
library Internal_Merkle_Library_Sorted_Hash {
// Hashes a and b in the order they are passed
function hash_node(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
hash := keccak256(0x00, 0x40)
}
}
// Hashes a and b in sorted order
function hash_pair(bytes32 a, bytes32 b) internal pure returns (bytes32 hash) {
hash = a < b ? hash_node(a, b) : hash_node(b, a);
}
// Counts number of set bits (1's) in 32-bit unsigned integer
function bit_count_32(uint32 n) internal pure returns (uint32) {
n = n - ((n >> 1) & 0x55555555);
n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
return (((n + (n >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
// Round 32-bit unsigned integer up to the nearest power of 2
function round_up_to_power_of_2(uint32 n) internal pure returns (uint32) {
if (bit_count_32(n) == 1) return n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
return n + 1;
}
// Get the Element Merkle Root for a tree with just a single bytes element in calldata
function get_root_from_one_c(bytes calldata element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes element in memory
function get_root_from_one_m(bytes memory element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get the Element Merkle Root for a tree with just a single bytes32 element in calldata
function get_root_from_one(bytes32 element) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(bytes1(0), element));
}
// Get nodes (parent of leafs) from bytes elements in calldata
function get_nodes_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes elements in memory
function get_nodes_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in calldata
function get_nodes_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get nodes (parent of leafs) from bytes32 elements in memory
function get_nodes_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory nodes) {
uint256 element_count = elements.length;
uint256 node_count = (element_count >> 1) + (element_count & 1);
nodes = new bytes32[](node_count);
uint256 write_index;
uint256 left_index;
while (write_index < node_count) {
left_index = write_index << 1;
if (left_index == element_count - 1) {
nodes[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[left_index]));
break;
}
nodes[write_index++] = hash_pair(
keccak256(abi.encodePacked(bytes1(0), elements[left_index])),
keccak256(abi.encodePacked(bytes1(0), elements[left_index + 1]))
);
}
}
// Get the Element Merkle Root given nodes (parent of leafs)
function get_root_from_nodes(bytes32[] memory nodes) internal pure returns (bytes32) {
uint256 node_count = nodes.length;
uint256 write_index;
uint256 left_index;
while (node_count > 1) {
left_index = write_index << 1;
if (left_index == node_count - 1) {
nodes[write_index] = nodes[left_index];
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
if (left_index >= node_count) {
write_index = 0;
node_count = (node_count >> 1) + (node_count & 1);
continue;
}
nodes[write_index++] = hash_pair(nodes[left_index], nodes[left_index + 1]);
}
return nodes[0];
}
// Get the Element Merkle Root for a tree with several bytes elements in calldata
function get_root_from_many_c(bytes[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes elements in memory
function get_root_from_many_m(bytes[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in calldata
function get_root_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_c(elements));
}
// Get the Element Merkle Root for a tree with several bytes32 elements in memory
function get_root_from_many_m(bytes32[] memory elements) internal pure returns (bytes32) {
return get_root_from_nodes(get_nodes_from_elements_m(elements));
}
// get_root_from_size_proof cannot be implemented with sorted hashed pairs
// Get the original Element Merkle Root, given an index, a leaf, and a Single Proof
function get_root_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
leaf = hash_pair(proof[proof_index], leaf);
proof_index -= 1;
}
index >>= 1;
upper_bound >>= 1;
}
return leaf;
}
// Get the original Element Merkle Root, given an index, a bytes element in calldata, and a Single Proof
function get_root_from_single_proof_c(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes element in memory, and a Single Proof
function get_root_from_single_proof_m(
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original Element Merkle Root, given an index, a bytes32 element, and a Single Proof
function get_root_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
hash = get_root_from_leaf_and_single_proof(index, hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a leaf, an update leaf, and a Single Proof
function get_roots_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 scratch, bytes32) {
uint256 proof_index = proof.length - 1;
uint256 upper_bound = uint256(proof[0]) - 1;
while (proof_index > 0) {
if ((index != upper_bound) || (index & 1 == 1)) {
scratch = proof[proof_index];
proof_index -= 1;
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
}
index >>= 1;
upper_bound >>= 1;
}
return (leaf, update_leaf);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_roots_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_roots_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// Get the original and updated Element Merkle Root, given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_roots_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 hash, bytes32 update_hash) {
hash = keccak256(abi.encodePacked(bytes1(0), element));
update_hash = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_roots_from_leaf_and_single_proof_update(index, hash, update_hash, proof);
}
// get_indices_from_multi_proof cannot be implemented with sorted hashed pairs
// Get leafs from bytes elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_elements_c(bytes32[] calldata elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get leafs from bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_elements_m(bytes32[] memory elements)
internal
pure
returns (bytes32[] memory leafs)
{
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original Element Merkle Root, given leafs and an Existence Multi Proof
function get_root_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 right)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) return leafs[(write_index == 0 ? leaf_count : write_index) - 1];
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
right = (flags & bit_check == bit_check) ? leafs[read_index++] : proof[proof_index++];
read_index %= leaf_count;
leafs[write_index] = hash_pair(right, leafs[read_index]);
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root, given bytes elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in calldata and an Existence Multi Proof
function get_root_from_multi_proof_c(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root, given bytes32 elements in memory and an Existence Multi Proof
function get_root_from_multi_proof_m(bytes32[] memory elements, bytes32[] calldata proof)
internal
pure
returns (bytes32)
{
return get_root_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_m(elements), proof);
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory leafs, bytes32[] memory update_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
leafs = new bytes32[](element_count);
update_leafs = new bytes32[](element_count);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
update_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get the original and updated Element Merkle Root, given leafs, update leafs, and an Existence Multi Proof
function get_roots_from_leafs_and_multi_proof_update(
bytes32[] memory leafs,
bytes32[] memory update_leafs,
bytes32[] calldata proof
) internal pure returns (bytes32 flags, bytes32 skips) {
uint256 leaf_count = update_leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
flags = proof[1];
skips = proof[2];
bytes32 scratch;
uint256 scratch_2;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
return (leafs[read_index], update_leafs[read_index]);
}
leafs[write_index] = leafs[read_index];
update_leafs[write_index] = update_leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (flags & bit_check == bit_check) {
scratch_2 = (read_index + 1) % leaf_count;
leafs[write_index] = hash_pair(leafs[read_index], leafs[scratch_2]);
update_leafs[write_index] = hash_pair(update_leafs[read_index], update_leafs[scratch_2]);
read_index += 2;
} else {
scratch = proof[proof_index++];
leafs[write_index] = hash_pair(scratch, leafs[read_index]);
update_leafs[write_index] = hash_pair(scratch, update_leafs[read_index]);
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_roots_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_c(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original and updated Element Merkle Root,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_roots_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32) {
(bytes32[] memory leafs, bytes32[] memory update_leafs) = get_reversed_leafs_from_current_and_update_elements_m(
elements,
update_elements
);
return get_roots_from_leafs_and_multi_proof_update(leafs, update_leafs, proof);
}
// Get the original Element Merkle Root, given an Append Proof
function get_root_from_append_proof(bytes32[] calldata proof) internal pure returns (bytes32 hash) {
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
while (proof_index > 1) {
proof_index -= 1;
hash = hash_pair(proof[proof_index], hash);
}
}
// Get the original and updated Element Merkle Root, given append leaf and an Append Proof
function get_roots_from_leaf_and_append_proof_single_append(bytes32 append_leaf, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32 scratch)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
hash = proof[proof_index];
append_leaf = hash_pair(hash, append_leaf);
while (proof_index > 1) {
proof_index -= 1;
scratch = proof[proof_index];
append_leaf = hash_pair(scratch, append_leaf);
hash = hash_pair(scratch, hash);
}
return (hash, append_leaf);
}
// Get the original and updated Element Merkle Root, given a bytes append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes append element in memory and an Append Proof
function get_roots_from_append_proof_single_append_m(bytes memory append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get the original and updated Element Merkle Root, given a bytes32 append element in calldata and an Append Proof
function get_roots_from_append_proof_single_append(bytes32 append_element, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_leaf, bytes32)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_roots_from_leaf_and_append_proof_single_append(append_leaf, proof);
}
// Get leafs from bytes elements in calldata
function get_leafs_from_elements_c(bytes[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes elements in memory
function get_leafs_from_elements_m(bytes[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in calldata
function get_leafs_from_elements_c(bytes32[] calldata elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get leafs from bytes32 elements in memory
function get_leafs_from_elements_m(bytes32[] memory elements) internal pure returns (bytes32[] memory leafs) {
uint256 element_count = elements.length;
leafs = new bytes32[](element_count);
while (element_count > 0) {
element_count -= 1;
leafs[element_count] = keccak256(abi.encodePacked(bytes1(0), elements[element_count]));
}
}
// Get the original and updated Element Merkle Root, given append leafs and an Append Proof
function get_roots_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 hash, bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = bit_count_32(uint32(offset));
hash = proof[proof_index];
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
proof_index -= 1;
read_index += 1;
if (proof_index > 0) {
hash = hash_pair(proof[proof_index], hash);
}
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index]);
read_index += 1;
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return (hash, append_leafs[0]);
}
// Get the original and updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_roots_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the original and updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_roots_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32)
{
return get_roots_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given an append leaf and an Append Proof
function get_new_root_from_leafs_and_append_proof_single_append(bytes32 append_leaf, bytes32[] memory proof)
internal
pure
returns (bytes32 append_hash)
{
uint256 proof_index = bit_count_32(uint32(uint256(proof[0])));
append_hash = hash_pair(proof[proof_index], append_leaf);
while (proof_index > 1) {
proof_index -= 1;
append_hash = hash_pair(proof[proof_index], append_hash);
}
}
// Get the updated Element Merkle Root, given a bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append_c(bytes calldata append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_single_append_m(bytes memory append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given a bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_single_append(bytes32 append_element, bytes32[] memory proof)
internal
pure
returns (bytes32 append_leaf)
{
append_leaf = keccak256(abi.encodePacked(bytes1(0), append_element));
return get_new_root_from_leafs_and_append_proof_single_append(append_leaf, proof);
}
// Get the updated Element Merkle Root, given append leafs and an Append Proof
function get_new_root_from_leafs_and_append_proof_multi_append(bytes32[] memory append_leafs, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
uint256 leaf_count = append_leafs.length;
uint256 write_index;
uint256 read_index;
uint256 offset = uint256(proof[0]);
uint256 index = offset;
// reuse leaf_count variable as upper_bound, since leaf_count no longer needed
leaf_count += offset;
leaf_count -= 1;
uint256 proof_index = proof.length - 1;
while (leaf_count > 0) {
if ((write_index == 0) && (index & 1 == 1)) {
append_leafs[0] = hash_pair(proof[proof_index], append_leafs[read_index]);
read_index += 1;
proof_index -= 1;
write_index = 1;
index += 1;
} else if (index < leaf_count) {
append_leafs[write_index++] = hash_pair(append_leafs[read_index++], append_leafs[read_index++]);
index += 2;
}
if (index >= leaf_count) {
if (index == leaf_count) {
append_leafs[write_index] = append_leafs[read_index];
}
read_index = 0;
write_index = 0;
leaf_count >>= 1;
offset >>= 1;
index = offset;
}
}
return append_leafs[0];
}
// Get the updated Element Merkle Root, given bytes append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in calldata and an Append Proof
function get_new_root_from_append_proof_multi_append_c(bytes32[] calldata append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_c(append_elements), proof);
}
// Get the updated Element Merkle Root, given bytes32 append elements in memory and an Append Proof
function get_new_root_from_append_proof_multi_append_m(bytes32[] memory append_elements, bytes32[] memory proof)
internal
pure
returns (bytes32)
{
return get_new_root_from_leafs_and_append_proof_multi_append(get_leafs_from_elements_m(append_elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, an append leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof(
uint256 index,
bytes32 leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes element in calldata, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a bytes32 element, and a Single Proof
function get_append_proof_from_single_proof(
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
return get_append_proof_from_leaf_and_single_proof(index, leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof, given an index, a leaf, an update leaf, and a Single Proof
function get_append_proof_from_leaf_and_single_proof_update(
uint256 index,
bytes32 leaf,
bytes32 update_leaf,
bytes32[] calldata proof
) internal pure returns (bytes32 append_hash, bytes32[] memory append_proof) {
uint256 proof_index = proof.length - 1;
uint256 append_node_index = uint256(proof[0]);
uint256 upper_bound = append_node_index - 1;
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 scratch;
while (proof_index > 0) {
if (index != upper_bound || (index & 1 == 1)) {
scratch = proof[proof_index];
leaf = hash_pair(scratch, leaf);
update_leaf = hash_pair(scratch, update_leaf);
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = scratch;
append_hash = hash_pair(scratch, append_hash);
}
proof_index -= 1;
} else if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_proof[append_proof_index] = update_leaf;
append_hash = leaf;
}
index >>= 1;
upper_bound >>= 1;
append_node_index >>= 1;
}
require(append_proof_index == 2 || append_hash == leaf, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = update_leaf;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in calldata, and a Single Proof
function get_append_proof_from_single_proof_update_c(
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes element in calldata, a bytes update element in memory, and a Single Proof
function get_append_proof_from_single_proof_update_m(
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Get the original Element Merkle Root and derive Append Proof,
// given an index, a bytes32 element, a bytes32 update element, and a Single Proof
function get_append_proof_from_single_proof_update(
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 leaf, bytes32[] memory) {
leaf = keccak256(abi.encodePacked(bytes1(0), element));
bytes32 update_leaf = keccak256(abi.encodePacked(bytes1(0), update_element));
return get_append_proof_from_leaf_and_single_proof_update(index, leaf, update_leaf, proof);
}
// Hashes leaf at read index and next index (circular) to write index
function hash_within_leafs(
bytes32[] memory leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
leafs[write_index] = hash_pair(leafs[read_index], leafs[(read_index + 1) % leaf_count]);
}
// Hashes value with leaf at read index to write index
function hash_with_leafs(
bytes32[] memory leafs,
bytes32 value,
uint256 write_index,
uint256 read_index
) internal pure {
leafs[write_index] = hash_pair(value, leafs[read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof(bytes32[] memory leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = leafs.length;
uint256 read_index;
uint256 write_index;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = uint256(bit_count_32(uint32(append_node_index))) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
bytes32 flags = proof[1];
bytes32 skips = proof[2];
uint256 read_index_of_append_node;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = flags;
}
return (append_hash, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = leafs[read_index]; // TODO scratch this leafs[read_index] above
append_proof[append_proof_index] = leafs[read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
leafs[write_index] = leafs[read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// reuse read_index_of_append_node as temporary scratch variable
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = leafs[read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_leafs(leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_leafs(leafs, proof[proof_index], write_index, read_index);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof, given bytes elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get the original Element Merkle Root and derive Append Proof, given bytes32 elements in calldata and an Existence Multi Proof
function get_append_proof_from_multi_proof(bytes32[] calldata elements, bytes32[] calldata proof)
internal
pure
returns (bytes32, bytes32[] memory)
{
return get_append_proof_from_leafs_and_multi_proof(get_reversed_leafs_from_elements_c(elements), proof);
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes[] calldata elements,
bytes[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes elements in calldata and update bytes elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes[] calldata elements,
bytes[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in calldata, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Get combined current and update leafs from current bytes32 elements in calldata and update bytes32 elements in memory, in reverse order
function get_reversed_combined_leafs_from_current_and_update_elements_m(
bytes32[] calldata elements,
bytes32[] memory update_elements
) internal pure returns (bytes32[] memory combined_leafs) {
uint256 element_count = elements.length;
require(update_elements.length == element_count, "LENGTH_MISMATCH");
combined_leafs = new bytes32[](element_count << 1);
uint256 read_index = element_count - 1;
uint256 write_index;
while (write_index < element_count) {
combined_leafs[write_index] = keccak256(abi.encodePacked(bytes1(0), elements[read_index]));
combined_leafs[element_count + write_index] = keccak256(abi.encodePacked(bytes1(0), update_elements[read_index]));
write_index += 1;
read_index -= 1;
}
}
// Copy leaf and update leaf at read indices and to write indices
function copy_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
}
// Hashes leaf and update leaf at read indices and next indices (circular) to write indices
function hash_within_combined_leafs(
bytes32[] memory combined_leafs,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
uint256 scratch = (read_index + 1) % leaf_count;
combined_leafs[write_index] = hash_pair(combined_leafs[read_index], combined_leafs[scratch]);
combined_leafs[leaf_count + write_index] = hash_pair(
combined_leafs[leaf_count + read_index],
combined_leafs[leaf_count + scratch]
);
}
// Hashes value with leaf and update leaf at read indices to write indices
function hash_with_combined_leafs(
bytes32[] memory combined_leafs,
bytes32 value,
uint256 write_index,
uint256 read_index,
uint256 leaf_count
) internal pure {
combined_leafs[write_index] = hash_pair(value, combined_leafs[read_index]);
combined_leafs[leaf_count + write_index] = hash_pair(value, combined_leafs[leaf_count + read_index]);
}
// Get the original Element Merkle Root and derive Append Proof, given combined leafs and update leafs and an Existence Multi Proof
function get_append_proof_from_leafs_and_multi_proof_update(bytes32[] memory combined_leafs, bytes32[] calldata proof)
internal
pure
returns (bytes32 append_hash, bytes32[] memory append_proof)
{
uint256 leaf_count = combined_leafs.length >> 1;
uint256 read_index;
uint256 write_index;
uint256 read_index_of_append_node;
uint256 proof_index = 3;
uint256 append_node_index = uint256(proof[0]);
uint256 append_proof_index = bit_count_32(uint32(append_node_index)) + 1;
append_proof = new bytes32[](append_proof_index);
append_proof[0] = bytes32(append_node_index);
bytes32 flags = proof[1];
bytes32 skips = proof[2];
bytes32 bit_check = 0x0000000000000000000000000000000000000000000000000000000000000001;
while (true) {
if (skips & bit_check == bit_check) {
if (flags & bit_check == bit_check) {
read_index = (write_index == 0 ? leaf_count : write_index) - 1;
// reuse flags as scratch variable
flags = combined_leafs[read_index];
require(append_proof_index == 2 || append_hash == flags, "INVALID_PROOF");
if (append_proof_index == 2) {
append_proof[1] = combined_leafs[leaf_count + read_index];
}
return (flags, append_proof);
}
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
append_hash = combined_leafs[read_index];
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index];
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
combined_leafs[write_index] = combined_leafs[read_index];
combined_leafs[leaf_count + write_index] = combined_leafs[leaf_count + read_index];
read_index = (read_index + 1) % leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
continue;
}
if (read_index_of_append_node == read_index) {
if (append_node_index & 1 == 1) {
append_proof_index -= 1;
if (flags & bit_check == bit_check) {
// use read_index_of_append_node as temporary scratch
read_index_of_append_node = (read_index + 1) % leaf_count;
append_hash = hash_pair(combined_leafs[read_index_of_append_node], append_hash);
append_proof[append_proof_index] = combined_leafs[leaf_count + read_index_of_append_node];
} else {
append_hash = hash_pair(proof[proof_index], append_hash);
append_proof[append_proof_index] = proof[proof_index];
}
}
read_index_of_append_node = write_index;
append_node_index >>= 1;
}
if (flags & bit_check == bit_check) {
hash_within_combined_leafs(combined_leafs, write_index, read_index, leaf_count);
read_index += 2;
} else {
hash_with_combined_leafs(combined_leafs, proof[proof_index], write_index, read_index, leaf_count);
proof_index += 1;
read_index += 1;
}
read_index %= leaf_count;
write_index = (write_index + 1) % leaf_count;
bit_check <<= 1;
}
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes elements in calldata, bytes update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in calldata, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_c(
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_c(elements, update_elements),
proof
);
}
// Get the original Element Merkle Root and derive Append Proof,
// given bytes32 elements in calldata, bytes32 update elements in memory, and an Existence Multi Proof
function get_append_proof_from_multi_proof_update_m(
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32, bytes32[] memory) {
return
get_append_proof_from_leafs_and_multi_proof_update(
get_reversed_combined_leafs_from_current_and_update_elements_m(elements, update_elements),
proof
);
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_c(index, element, proof)) == root;
}
// INTERFACE: Check if bytes element in calldata exists at index, given a root and a Single Proof
function element_exists_m(
bytes32 root,
uint256 index,
bytes memory element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof_m(index, element, proof)) == root;
}
// INTERFACE: Check if bytes32 element exists at index, given a root and a Single Proof
function element_exists(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_single_proof(index, element, proof)) == root;
}
// INTERFACE: Check if bytes elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in calldata exist, given a root and a Single Proof
function elements_exist_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_c(elements, proof)) == root;
}
// INTERFACE: Check if bytes32 elements in memory exist, given a root and a Single Proof
function elements_exist_m(
bytes32 root,
bytes32[] memory elements,
bytes32[] calldata proof
) internal pure returns (bool) {
return hash_node(proof[0], get_root_from_multi_proof_m(elements, proof)) == root;
}
// get_indices cannot be implemented with sorted hashed pairs
// verify_size_with_proof cannot be implemented with sorted hashed pairs
// INTERFACE: Check tree size, given a the Element Merkle Root
function verify_size(
bytes32 root,
uint256 size,
bytes32 element_root
) internal pure returns (bool) {
if (root == bytes32(0) && size == 0) return true;
return hash_node(bytes32(size), element_root) == root;
}
// INTERFACE: Try to update a bytes element in calldata, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes element in memory, given a root, and index, an bytes element in calldata, and a Single Proof
function try_update_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update a bytes32 element, given a root, and index, an bytes32 element, and a Single Proof
function try_update_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(total_element_count, new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root and an Append Proof
function try_append_one_c(
bytes32 root,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_c(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_c(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root and an Append Proof
function try_append_one_m(
bytes32 root,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one_m(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append_m(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root and an Append Proof
function try_append_one(
bytes32 root,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(uint256(1)), get_root_from_one(append_element));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_single_append(append_element, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + 1), new_element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root and an Append Proof
function try_append_many_c(
bytes32 root,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_c(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_c(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root and an Append Proof
function try_append_many_m(
bytes32 root,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 new_element_root) {
bytes32 total_element_count = proof[0];
require((root == bytes32(0)) == (total_element_count == bytes32(0)), "INVALID_TREE");
if (root == bytes32(0)) return hash_node(bytes32(append_elements.length), get_root_from_many_m(append_elements));
bytes32 old_element_root;
(old_element_root, new_element_root) = get_roots_from_append_proof_multi_append_m(append_elements, proof);
require(hash_node(total_element_count, old_element_root) == root, "INVALID_PROOF");
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), new_element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_one_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, an index, a bytes32 element, and a Single Proof
function try_append_one_using_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, an index, a bytes element in calldata, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, an index, a bytes32 element, and a Single Proof
function try_append_many_using_one_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof(index, element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append a bytes element in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes element in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_one_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append a bytes32 element, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_one_using_many(
bytes32 root,
bytes32[] calldata elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to append bytes elements in calldata, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes elements in memory, given a root, bytes elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in calldata, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to append bytes32 elements in memory, given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_append_many_using_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof(elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append a bytes element in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append a bytes element in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_one_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes32 element and append a bytes32 element,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update a bytes element in calldata and append bytes elements in calldata,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes calldata element,
bytes calldata update_element,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_c(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes element in memory and append bytes elements in memory,
// given a root, an index, a bytes element in calldata, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes calldata element,
bytes memory update_element,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update_m(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in calldata,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_c(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update a bytes32 element and append bytes32 elements in memory,
// given a root, an index, a bytes32 element, and a Single Proof
function try_update_one_and_append_many_m(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append a bytes element in calldata,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes calldata append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_c(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append a bytes element in memory,
// given a root, bytes elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes memory append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append_m(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append a bytes32 element,
// given a root, bytes32 elements in calldata, and a Single Proof
function try_update_many_and_append_one_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
// INTERFACE: Try to update bytes elements in calldata and append bytes elements in calldata,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes[] calldata elements,
bytes[] calldata update_elements,
bytes[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes elements in memory and append bytes elements in memory,
// given a root, bytes elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes[] calldata elements,
bytes[] memory update_elements,
bytes[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in calldata and append bytes32 elements in calldata,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_c(
bytes32 root,
bytes32[] calldata elements,
bytes32[] calldata update_elements,
bytes32[] calldata append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_c(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_c(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Try to update bytes32 elements in memory and append bytes32 elements in memory,
// given a root, bytes32 elements in calldata, and an Existence Multi Proof
function try_update_many_and_append_many_m(
bytes32 root,
bytes32[] calldata elements,
bytes32[] memory update_elements,
bytes32[] memory append_elements,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_multi_proof_update_m(elements, update_elements, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_multi_append_m(append_elements, append_proof);
return hash_node(bytes32(uint256(total_element_count) + append_elements.length), element_root);
}
// INTERFACE: Create a tree and return the root, given a bytes element in calldata
function create_from_one_c(bytes calldata element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_c(element));
}
// INTERFACE: Create a tree and return the root, given a bytes element in memory
function create_from_one_m(bytes memory element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one_m(element));
}
// INTERFACE: Create a tree and return the root, given a bytes32 element
function create_from_one(bytes32 element) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(uint256(1)), get_root_from_one(element));
}
// INTERFACE: Create a tree and return the root, given bytes elements in calldata
function create_from_many_c(bytes[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes elements in memory
function create_from_many_m(bytes[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in calldata
function create_from_many_c(bytes32[] calldata elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_c(elements));
}
// INTERFACE: Create a tree and return the root, given bytes32 elements in memory
function create_from_many_m(bytes32[] memory elements) internal pure returns (bytes32 new_element_root) {
return hash_node(bytes32(elements.length), get_root_from_many_m(elements));
}
}
| INTERFACE: Try to update a bytes32 element and append a bytes32 element, given a root, an index, a bytes32 element, and a Single Proof | function try_update_one_and_append_one(
bytes32 root,
uint256 index,
bytes32 element,
bytes32 update_element,
bytes32 append_element,
bytes32[] calldata proof
) internal pure returns (bytes32 element_root) {
bytes32 total_element_count = proof[0];
require(root != bytes32(0) || total_element_count == bytes32(0), "EMPTY_TREE");
bytes32[] memory append_proof;
(element_root, append_proof) = get_append_proof_from_single_proof_update(index, element, update_element, proof);
require(hash_node(total_element_count, element_root) == root, "INVALID_PROOF");
element_root = get_new_root_from_append_proof_single_append(append_element, append_proof);
return hash_node(bytes32(uint256(total_element_count) + 1), element_root);
}
| 12,859,797 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.